mirror of
https://github.com/nicepkg/ai-workflow.git
synced 2026-11-18 18:04:23 +00:00
feat: introduce legacy-to-ai-ready skill set and resource discovery capabilities, enhancing Claude Code's functionality with new documentation and scripts for skill creation, downloading, and management
This commit is contained in:
@@ -0,0 +1,290 @@
|
||||
---
|
||||
name: legacy-to-ai-ready
|
||||
description: Transform legacy codebases into AI-ready projects with Claude Code configurations. Use when (1) analyzing old projects to generate AI coding configurations, (2) creating CLAUDE.md, skills, subagents, slash commands, hooks, or rules for existing projects, (3) user wants to enable vibe coding for a codebase, (4) onboarding new team members with AI-assisted development, (5) user mentions "make project AI-ready", "generate Claude config", or "create coding standards for AI".
|
||||
---
|
||||
|
||||
# Legacy to AI-Ready
|
||||
|
||||
Transform legacy codebases into AI-ready projects by generating Claude Code configurations.
|
||||
|
||||
## Quick Start (5-Minute Setup)
|
||||
|
||||
For most projects, start with just CLAUDE.md:
|
||||
|
||||
1. **Analyze**: `python scripts/analyze_codebase.py [path]`
|
||||
2. **Create CLAUDE.md** with build commands, code style, architecture overview
|
||||
3. **Done** - Claude can now write code following your project's conventions
|
||||
|
||||
Expand to full configuration only when needed.
|
||||
|
||||
## Interactive Discovery
|
||||
|
||||
Before generating configs, ask these questions:
|
||||
|
||||
**Project Scope:**
|
||||
- What is this project? (web app, API, CLI, library)
|
||||
- Primary language and frameworks?
|
||||
- Team size? (solo, small team, enterprise)
|
||||
|
||||
**Pain Points:**
|
||||
- What mistakes do new developers commonly make?
|
||||
- What patterns should always be followed?
|
||||
- What operations are repeated frequently?
|
||||
|
||||
**Integration Needs:**
|
||||
- External services used? (databases, APIs, cloud)
|
||||
- CI/CD pipeline? (GitHub Actions, Jenkins)
|
||||
- Code quality tools? (linters, formatters)
|
||||
|
||||
## Configuration Decision Tree
|
||||
|
||||
```
|
||||
Start
|
||||
│
|
||||
├─ Small project / Solo dev
|
||||
│ └─ CLAUDE.md only
|
||||
│
|
||||
├─ Team project
|
||||
│ ├─ Multi-language? → Add .claude/rules/
|
||||
│ ├─ Complex domain? → Add .claude/skills/
|
||||
│ ├─ Code reviews? → Add .claude/agents/
|
||||
│ └─ Repeated tasks? → Add .claude/commands/
|
||||
│
|
||||
└─ Enterprise / Large team
|
||||
└─ All configurations + MCP servers + Hooks
|
||||
```
|
||||
|
||||
## Generated Configurations
|
||||
|
||||
| Config | Purpose | When to Create |
|
||||
|--------|---------|----------------|
|
||||
| **CLAUDE.md** | Project memory (shared) | Always (required) |
|
||||
| **CLAUDE.local.md** | Personal preferences (git-ignored) | Individual customization |
|
||||
| **.claudeignore** | Files Claude should not access | Sensitive files exist |
|
||||
| **.claude/rules/** | Path-specific rules | Multi-module projects |
|
||||
| **.claude/skills/** | Domain knowledge | Complex business logic |
|
||||
| **.claude/agents/** | Task specialists | Repeated review/debug tasks |
|
||||
| **.claude/commands/** | Quick prompts | Common workflows |
|
||||
| **.claude/settings.json** | Hooks + permissions | Auto-formatting, security |
|
||||
| **MCP servers** | External tools | Database/API integrations |
|
||||
|
||||
## Workflow
|
||||
|
||||
### Phase 1: Automated Analysis
|
||||
|
||||
```bash
|
||||
python scripts/analyze_codebase.py [project-path]
|
||||
```
|
||||
|
||||
The script detects:
|
||||
- Languages and frameworks
|
||||
- Directory structure patterns
|
||||
- Development tools (linters, formatters)
|
||||
- Git commit patterns
|
||||
- Environment variables
|
||||
- Code style indicators
|
||||
- **CI/CD configurations** (GitHub Actions, etc.)
|
||||
- **Sensitive files** (warns about .env, credentials)
|
||||
|
||||
**Output includes:**
|
||||
- Recommendations for which configs to create
|
||||
- Security warnings for sensitive files
|
||||
- Suggested .claudeignore patterns
|
||||
|
||||
### Phase 2: Context Gathering
|
||||
|
||||
Claude should read:
|
||||
|
||||
1. **3-5 representative source files** - understand naming, patterns
|
||||
2. **Test files** - understand testing approach
|
||||
3. **Config files** - package.json, tsconfig, etc.
|
||||
4. **README/docs** - project overview
|
||||
5. **Recent commits** - understand commit style
|
||||
|
||||
### Phase 2.5: Discover Existing Resources
|
||||
|
||||
Before creating custom configs, search for existing skills and MCP servers:
|
||||
|
||||
1. **Search skill marketplaces** - SkillsMP, SkillHub.club, Claude Skills Hub
|
||||
2. **Check GitHub repositories** - awesome-claude-skills, themed skill collections
|
||||
3. **Find relevant MCP servers** - Glama, MCP Market, official registry
|
||||
|
||||
See [references/resource-discovery.md](references/resource-discovery.md) for complete directory of sources.
|
||||
|
||||
**Tip**: Many common needs (git commit, code review, database patterns) already have well-maintained skills available.
|
||||
|
||||
### Phase 3: Generate Configurations
|
||||
|
||||
#### 1. CLAUDE.md (Required)
|
||||
|
||||
Create at project root with:
|
||||
- Quick reference commands (build, test, lint)
|
||||
- Naming conventions
|
||||
- Architecture overview
|
||||
- Testing guidelines
|
||||
- Git workflow
|
||||
|
||||
See [references/claude-md-patterns.md](references/claude-md-patterns.md).
|
||||
|
||||
#### 2. Rules (If Multi-Module)
|
||||
|
||||
Create `.claude/rules/` when:
|
||||
- Multiple languages need different conventions
|
||||
- Modules have distinct patterns (frontend/backend)
|
||||
- Path-specific requirements exist
|
||||
|
||||
See [references/rules-patterns.md](references/rules-patterns.md).
|
||||
|
||||
#### 3. Skills (If Complex Domain)
|
||||
|
||||
Create `.claude/skills/` when:
|
||||
- Domain-specific workflows exist (database, API patterns)
|
||||
- Team knowledge needs preservation
|
||||
- Complex procedures are repeated
|
||||
|
||||
See [references/skills-patterns.md](references/skills-patterns.md).
|
||||
|
||||
#### 4. Subagents (If Specialized Tasks)
|
||||
|
||||
Create `.claude/agents/` for:
|
||||
- Code review automation
|
||||
- Debugging assistance
|
||||
- Security auditing
|
||||
- Documentation generation
|
||||
|
||||
See [references/agents-patterns.md](references/agents-patterns.md).
|
||||
|
||||
#### 5. Commands (If Common Operations)
|
||||
|
||||
Create `.claude/commands/` for:
|
||||
- Git commit workflow
|
||||
- PR review process
|
||||
- Deployment steps
|
||||
- Test running
|
||||
|
||||
See [references/commands-patterns.md](references/commands-patterns.md).
|
||||
|
||||
#### 6. Hooks (If Auto-Formatting Needed)
|
||||
|
||||
Configure `.claude/settings.json` for:
|
||||
- Auto-format on file edit
|
||||
- Protected files
|
||||
- Command logging
|
||||
|
||||
See [references/hooks-patterns.md](references/hooks-patterns.md).
|
||||
|
||||
#### 7. MCP Servers (If External Integrations)
|
||||
|
||||
Configure MCP for:
|
||||
- Database access
|
||||
- GitHub integration
|
||||
- Slack notifications
|
||||
- Custom internal tools
|
||||
|
||||
See [references/mcp-patterns.md](references/mcp-patterns.md).
|
||||
|
||||
### Phase 4: Validate
|
||||
|
||||
1. Ask Claude to perform a typical task
|
||||
2. Verify it follows project conventions
|
||||
3. Iterate based on gaps discovered
|
||||
|
||||
## Output Structure
|
||||
|
||||
Minimal (small projects):
|
||||
```
|
||||
project/
|
||||
├── CLAUDE.md
|
||||
└── [existing files]
|
||||
```
|
||||
|
||||
Standard (team projects):
|
||||
```
|
||||
project/
|
||||
├── CLAUDE.md
|
||||
├── .claude/
|
||||
│ ├── rules/
|
||||
│ │ └── code-style.md
|
||||
│ └── commands/
|
||||
│ └── commit.md
|
||||
└── [existing files]
|
||||
```
|
||||
|
||||
Complete (enterprise):
|
||||
```
|
||||
project/
|
||||
├── CLAUDE.md # Shared project memory
|
||||
├── CLAUDE.local.md # Personal (git-ignored)
|
||||
├── .claudeignore # Files to protect
|
||||
├── .claude/
|
||||
│ ├── settings.json # Hooks + permissions
|
||||
│ ├── rules/
|
||||
│ ├── skills/
|
||||
│ ├── agents/
|
||||
│ └── commands/
|
||||
└── [existing files]
|
||||
```
|
||||
|
||||
## Reference Materials
|
||||
|
||||
| Reference | When to Read |
|
||||
|-----------|--------------|
|
||||
| [examples.md](references/examples.md) | **Complete real-world examples** |
|
||||
| [resource-discovery.md](references/resource-discovery.md) | **Find existing skills & MCP servers** |
|
||||
| [advanced-patterns.md](references/advanced-patterns.md) | **Migrations, team collab, monorepos** |
|
||||
| [claude-md-patterns.md](references/claude-md-patterns.md) | Creating CLAUDE.md |
|
||||
| [rules-patterns.md](references/rules-patterns.md) | Module-specific rules |
|
||||
| [skills-patterns.md](references/skills-patterns.md) | Domain knowledge |
|
||||
| [agents-patterns.md](references/agents-patterns.md) | Task specialists |
|
||||
| [commands-patterns.md](references/commands-patterns.md) | Quick prompts |
|
||||
| [hooks-patterns.md](references/hooks-patterns.md) | Auto-formatting |
|
||||
| [mcp-patterns.md](references/mcp-patterns.md) | External tools |
|
||||
|
||||
## Templates & Bundled Skills
|
||||
|
||||
Templates:
|
||||
- `assets/CLAUDE.md.template` - Project memory template
|
||||
- `assets/settings.json.template` - Hooks configuration
|
||||
- `assets/claudeignore.template` - File ignore patterns
|
||||
|
||||
Bundled skills to install in target project:
|
||||
- `assets/skill-creator/` - For creating new project-specific skills
|
||||
- `assets/skill-downloader/` - For downloading additional skills
|
||||
- `assets/resource-scout/` - For discovering existing skills & MCP servers
|
||||
|
||||
### Installing Bundled Skills
|
||||
|
||||
Copy these skills to the target project's `.claude/skills/` directory:
|
||||
|
||||
```bash
|
||||
cp -r assets/skill-creator [target-project]/.claude/skills/
|
||||
cp -r assets/skill-downloader [target-project]/.claude/skills/
|
||||
cp -r assets/resource-scout [target-project]/.claude/skills/
|
||||
```
|
||||
|
||||
This enables the target project to:
|
||||
1. **resource-scout** - Discover existing skills & MCP servers before building custom
|
||||
2. **skill-downloader** - Download and install skills from GitHub or archives
|
||||
3. **skill-creator** - Create custom skills tailored to their domain
|
||||
|
||||
## Language Quick Reference
|
||||
|
||||
### TypeScript/JavaScript
|
||||
- Extract: eslint, prettier, tsconfig
|
||||
- Hooks: prettier auto-format
|
||||
- Skills: API patterns, component patterns
|
||||
|
||||
### Python
|
||||
- Extract: black, ruff, mypy, pyproject.toml
|
||||
- Hooks: black/ruff auto-format
|
||||
- Skills: API patterns, ORM patterns
|
||||
|
||||
### Go
|
||||
- Extract: gofmt, golangci-lint
|
||||
- Hooks: gofmt auto-format
|
||||
- Skills: error handling patterns
|
||||
|
||||
### Rust
|
||||
- Extract: rustfmt, clippy
|
||||
- Hooks: rustfmt auto-format
|
||||
- Skills: error handling, async patterns
|
||||
@@ -0,0 +1,76 @@
|
||||
# {{PROJECT_NAME}}
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| Build | `{{BUILD_CMD}}` |
|
||||
| Test | `{{TEST_CMD}}` |
|
||||
| Lint | `{{LINT_CMD}}` |
|
||||
| Format | `{{FORMAT_CMD}}` |
|
||||
| Dev | `{{DEV_CMD}}` |
|
||||
|
||||
## Code Style
|
||||
|
||||
### Naming Conventions
|
||||
{{NAMING_CONVENTIONS}}
|
||||
|
||||
### File Organization
|
||||
{{FILE_ORGANIZATION}}
|
||||
|
||||
### Import Order
|
||||
{{IMPORT_ORDER}}
|
||||
|
||||
## Architecture
|
||||
|
||||
### Project Structure
|
||||
```
|
||||
{{DIRECTORY_STRUCTURE}}
|
||||
```
|
||||
|
||||
### Core Patterns
|
||||
{{ARCHITECTURE_PATTERNS}}
|
||||
|
||||
### Data Flow
|
||||
{{DATA_FLOW}}
|
||||
|
||||
## Testing
|
||||
|
||||
### Test Organization
|
||||
{{TEST_ORGANIZATION}}
|
||||
|
||||
### Running Tests
|
||||
{{TEST_COMMANDS}}
|
||||
|
||||
## Git Workflow
|
||||
|
||||
- Branch naming: `{{BRANCH_PATTERN}}`
|
||||
- Commit format: `{{COMMIT_FORMAT}}`
|
||||
- PR process: {{PR_PROCESS}}
|
||||
|
||||
## Environment
|
||||
|
||||
### Required Variables
|
||||
{{ENV_VARS}}
|
||||
|
||||
### Local Setup
|
||||
{{SETUP_STEPS}}
|
||||
|
||||
---
|
||||
|
||||
## Additional Resources
|
||||
|
||||
{{#IF_RULES}}
|
||||
See `.claude/rules/` for module-specific guidelines:
|
||||
{{RULES_LIST}}
|
||||
{{/IF_RULES}}
|
||||
|
||||
{{#IF_SKILLS}}
|
||||
See `.claude/skills/` for specialized knowledge:
|
||||
{{SKILLS_LIST}}
|
||||
{{/IF_SKILLS}}
|
||||
|
||||
{{#IF_COMMANDS}}
|
||||
Custom commands available:
|
||||
{{COMMANDS_LIST}}
|
||||
{{/IF_COMMANDS}}
|
||||
@@ -0,0 +1,65 @@
|
||||
# .claudeignore - Files Claude should not read or modify
|
||||
# Syntax is the same as .gitignore
|
||||
|
||||
# === Secrets and Credentials ===
|
||||
.env
|
||||
.env.*
|
||||
*.pem
|
||||
*.key
|
||||
*.p12
|
||||
*.keystore
|
||||
*.jks
|
||||
credentials*.json
|
||||
service-account*.json
|
||||
*secret*
|
||||
secrets/
|
||||
|
||||
# === Cloud Configurations ===
|
||||
.aws/
|
||||
.gcp/
|
||||
.azure/
|
||||
kubeconfig*
|
||||
|
||||
# === Large Generated Files ===
|
||||
dist/
|
||||
build/
|
||||
.next/
|
||||
.nuxt/
|
||||
coverage/
|
||||
*.min.js
|
||||
*.bundle.js
|
||||
*.map
|
||||
|
||||
# === Dependencies (already ignored by default) ===
|
||||
# node_modules/
|
||||
# vendor/
|
||||
# __pycache__/
|
||||
|
||||
# === Binary and Media Files ===
|
||||
*.png
|
||||
*.jpg
|
||||
*.jpeg
|
||||
*.gif
|
||||
*.ico
|
||||
*.pdf
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.mp4
|
||||
*.mp3
|
||||
|
||||
# === Database Files ===
|
||||
*.sql
|
||||
*.db
|
||||
*.sqlite
|
||||
*.dump
|
||||
|
||||
# === IDE Configs with Potential Secrets ===
|
||||
.idea/
|
||||
.vscode/settings.json
|
||||
|
||||
# === Logs ===
|
||||
*.log
|
||||
logs/
|
||||
|
||||
# === Project-Specific ===
|
||||
# Add your project-specific patterns below
|
||||
@@ -0,0 +1,165 @@
|
||||
---
|
||||
name: resource-scout
|
||||
description: Search and discover Claude Code skills and MCP servers from marketplaces, GitHub repositories, and registries. Use when (1) user asks to find skills for a specific task, (2) looking for MCP servers to connect external tools, (3) user mentions "find skill", "search MCP", "discover tools", or "what skills exist for X", (4) before creating a custom skill to check if one already exists.
|
||||
---
|
||||
|
||||
# Resource Scout
|
||||
|
||||
Search and discover existing Claude Code skills and MCP servers before building custom solutions.
|
||||
|
||||
## Quick Search Strategy
|
||||
|
||||
**For Skills:**
|
||||
1. WebSearch: `site:skillsmp.com [topic]` or `claude skill [topic]`
|
||||
2. Check GitHub: `awesome-claude-skills [topic]`
|
||||
3. Browse: skillhub.club, claudeskills.info
|
||||
|
||||
**For MCP:**
|
||||
1. WebSearch: `MCP server [tool/service name]`
|
||||
2. Check: glama.ai/mcp/servers, mcpmarket.com
|
||||
3. Official: github.com/modelcontextprotocol/servers
|
||||
|
||||
## Skill Search Workflow
|
||||
|
||||
### Step 1: Define Need
|
||||
|
||||
Before searching, clarify:
|
||||
- What task needs to be accomplished?
|
||||
- What tools/services are involved?
|
||||
- Is it a common pattern (git, testing, API) or domain-specific?
|
||||
|
||||
### Step 2: Search Marketplaces
|
||||
|
||||
**Primary sources (largest catalogs):**
|
||||
|
||||
| Source | URL | Best For |
|
||||
|--------|-----|----------|
|
||||
| SkillsMP | skillsmp.com | 71000+ skills, long-tail search |
|
||||
| SkillHub.club | skillhub.club | AI-evaluated, quality filter |
|
||||
| Claude Skills Hub | claudeskills.info | UI-friendly browsing |
|
||||
|
||||
**Search patterns:**
|
||||
```
|
||||
# On SkillsMP
|
||||
[domain] skill → "marketing skill", "database skill"
|
||||
[framework] claude → "react claude", "fastapi claude"
|
||||
[task] automation → "deployment automation"
|
||||
```
|
||||
|
||||
### Step 3: Search GitHub
|
||||
|
||||
**Curated lists:**
|
||||
- `github.com/keyuyuan/skillhub-awesome-skills` - 精选清单
|
||||
- `github.com/VoltAgent/awesome-claude-skills` - 生态大全
|
||||
- `github.com/ComposioHQ/awesome-claude-skills` - 大量通用技能
|
||||
|
||||
**Ready-to-use repositories:**
|
||||
- `github.com/alirezarezvani/claude-skills` - Content/Marketing
|
||||
- `github.com/gked2121/claude-skills` - Workflow思维
|
||||
- `github.com/Microck/ordinary-claude-skills` - 超大集合
|
||||
- `github.com/sickn33/antigravity-awesome-skills` - 结构化
|
||||
|
||||
**Search command:**
|
||||
```bash
|
||||
# Use WebSearch tool
|
||||
site:github.com "claude skill" [topic]
|
||||
site:github.com "SKILL.md" [topic]
|
||||
```
|
||||
|
||||
### Step 4: Evaluate & Install
|
||||
|
||||
When skill found:
|
||||
1. Check last update date (prefer recent)
|
||||
2. Review SKILL.md for quality
|
||||
3. Check if has scripts/references
|
||||
4. Install with skill-downloader or manual copy
|
||||
|
||||
## MCP Server Search Workflow
|
||||
|
||||
### Step 1: Identify Integration Need
|
||||
|
||||
Common patterns:
|
||||
- Database access → postgres, mysql, sqlite MCP
|
||||
- GitHub workflow → github MCP
|
||||
- Cloud services → AWS, GCP, Azure MCPs
|
||||
- Communication → slack, discord MCPs
|
||||
- File systems → filesystem MCP
|
||||
|
||||
### Step 2: Search Official Sources
|
||||
|
||||
**Primary:**
|
||||
- Official registry: `registry.modelcontextprotocol.io`
|
||||
- Official repo: `github.com/modelcontextprotocol/servers`
|
||||
|
||||
**Directories:**
|
||||
| Source | URL | Features |
|
||||
|--------|-----|----------|
|
||||
| Glama | glama.ai/mcp/servers | Stars, downloads, updates |
|
||||
| MCP Market | mcpmarket.com | Skills + MCP combined |
|
||||
| mcpservers.org | mcpservers.org | Categorized |
|
||||
| PulseMCP | pulsemcp.com/servers | Daily updates |
|
||||
| Smithery | smithery.ai | Registry/distribution |
|
||||
|
||||
### Step 3: Search GitHub
|
||||
|
||||
```bash
|
||||
# Use WebSearch tool
|
||||
site:github.com "mcp server" [service]
|
||||
site:github.com "@modelcontextprotocol" [service]
|
||||
```
|
||||
|
||||
**Awesome lists:**
|
||||
- `github.com/punkpeye/awesome-mcp-servers`
|
||||
- `github.com/wong2/awesome-mcp-servers`
|
||||
|
||||
### Step 4: Verify & Configure
|
||||
|
||||
When MCP found:
|
||||
1. Check compatibility (stdio vs HTTP)
|
||||
2. Review required environment variables
|
||||
3. Test connection locally
|
||||
4. Add to `.claude/settings.json`
|
||||
|
||||
## Search by Category
|
||||
|
||||
### Development Tools
|
||||
```
|
||||
Skills: "code review skill", "git commit skill", "testing skill"
|
||||
MCP: "github mcp", "gitlab mcp", "jira mcp"
|
||||
```
|
||||
|
||||
### Databases
|
||||
```
|
||||
Skills: "database skill", "sql skill", "migration skill"
|
||||
MCP: "postgres mcp", "mysql mcp", "mongodb mcp"
|
||||
```
|
||||
|
||||
### Content & Marketing
|
||||
```
|
||||
Skills: "content creator skill", "seo skill", "social media skill"
|
||||
MCP: "wordpress mcp", "notion mcp"
|
||||
```
|
||||
|
||||
### Cloud & DevOps
|
||||
```
|
||||
Skills: "deployment skill", "kubernetes skill", "terraform skill"
|
||||
MCP: "aws mcp", "gcp mcp", "azure mcp"
|
||||
```
|
||||
|
||||
### AI & Data
|
||||
```
|
||||
Skills: "data analysis skill", "ml skill"
|
||||
MCP: "openai mcp", "huggingface mcp"
|
||||
```
|
||||
|
||||
## Complete Source Reference
|
||||
|
||||
See [references/sources.md](references/sources.md) for full directory of all skill and MCP sources with detailed descriptions.
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Search before build** - Always check existing resources first
|
||||
2. **Prefer maintained** - Choose skills with recent updates
|
||||
3. **Check quality** - Review SKILL.md structure and content
|
||||
4. **Consider combining** - Multiple simple skills > one complex custom
|
||||
5. **Verify security** - Review MCP permissions and token scopes
|
||||
@@ -0,0 +1,250 @@
|
||||
# Complete Resource Directory
|
||||
|
||||
Full directory of all skill and MCP discovery sources.
|
||||
|
||||
## Table of Contents
|
||||
- [Skills: Marketplaces & Directories](#skills-marketplaces--directories)
|
||||
- [Skills: GitHub Awesome Lists](#skills-github-awesome-lists)
|
||||
- [Skills: Ready-to-Use Repositories](#skills-ready-to-use-repositories)
|
||||
- [Skills: Tools & Documentation](#skills-tools--documentation)
|
||||
- [MCP: Official Resources](#mcp-official-resources)
|
||||
- [MCP: Marketplaces & Directories](#mcp-marketplaces--directories)
|
||||
- [MCP: GitHub Lists](#mcp-github-lists)
|
||||
|
||||
---
|
||||
|
||||
## Skills: Marketplaces & Directories
|
||||
|
||||
### SkillsMP
|
||||
- **URL**: https://skillsmp.com/
|
||||
- **Type**: Large marketplace
|
||||
- **Size**: 71,000+ skills
|
||||
- **Features**: Search by author, popularity, category
|
||||
- **Best for**: Long-tail search, discovering niche skills
|
||||
- **Docs**: https://skillsmp.com/docs
|
||||
|
||||
### SkillHub.club
|
||||
- **URL**: https://www.skillhub.club/
|
||||
- **Type**: Curated marketplace
|
||||
- **Features**: AI-evaluated quality, stars/ratings
|
||||
- **Best for**: Finding verified, quality skills
|
||||
|
||||
### agent-skills.md
|
||||
- **URL**: https://agent-skills.md/
|
||||
- **Type**: Online directory
|
||||
- **Features**: Direct install commands, file structure preview
|
||||
- **Best for**: Quick browse and install
|
||||
|
||||
### Claude Skills Hub
|
||||
- **URL**: https://claudeskills.info/
|
||||
- **Type**: Online directory
|
||||
- **Features**: User-friendly UI, category browsing
|
||||
- **Best for**: Discovery, "window shopping"
|
||||
|
||||
### MCP Market (Skills Section)
|
||||
- **URL**: https://mcpmarket.com/
|
||||
- **Type**: Combined marketplace
|
||||
- **Features**: Skills + MCP servers in one place
|
||||
- **Best for**: Finding both skills and related MCPs
|
||||
|
||||
### AwesomeClaude Visual Directory
|
||||
- **URL**: https://awesomeclaude.ai/awesome-claude-skills
|
||||
- **Type**: Visual browser
|
||||
- **Features**: UI for ComposioHQ collection
|
||||
- **Best for**: Non-technical users, visual browsing
|
||||
|
||||
---
|
||||
|
||||
## Skills: GitHub Awesome Lists
|
||||
|
||||
### Skillhub Awesome Skills
|
||||
- **URL**: https://github.com/keyuyuan/skillhub-awesome-skills
|
||||
- **Type**: Curated list
|
||||
- **Features**: Categorized, verified skills
|
||||
- **Best for**: Quick discovery of proven skills
|
||||
|
||||
### Awesome Claude Skills (VoltAgent)
|
||||
- **URL**: https://github.com/VoltAgent/awesome-claude-skills
|
||||
- **Type**: Ecosystem overview
|
||||
- **Features**: Broad coverage, resource compilation
|
||||
- **Best for**: Understanding the ecosystem
|
||||
|
||||
### Awesome Claude Skills (travisvn)
|
||||
- **URL**: https://github.com/travisvn/awesome-claude-skills
|
||||
- **Type**: Curated list
|
||||
- **Features**: Alternative curation perspective
|
||||
- **Best for**: Cross-reference validation
|
||||
|
||||
### Awesome Claude Skills (ComposioHQ)
|
||||
- **URL**: https://github.com/ComposioHQ/awesome-claude-skills
|
||||
- **Type**: Large collection
|
||||
- **Features**: High volume, general/utility skills
|
||||
- **Best for**: Finding common utilities
|
||||
|
||||
### Awesome Agent Skills (heilcheng)
|
||||
- **URL**: https://github.com/heilcheng/awesome-agent-skills
|
||||
- **Type**: Multi-platform list
|
||||
- **Features**: Covers Claude, Codex, Copilot
|
||||
- **Best for**: Cross-platform skill discovery
|
||||
|
||||
---
|
||||
|
||||
## Skills: Ready-to-Use Repositories
|
||||
|
||||
### alirezarezvani/claude-skills
|
||||
- **URL**: https://github.com/alirezarezvani/claude-skills
|
||||
- **Focus**: Content Creator, Marketing
|
||||
- **Quality**: Production-ready
|
||||
- **Best for**: Direct workflow integration
|
||||
|
||||
### gked2121/claude-skills
|
||||
- **URL**: https://github.com/gked2121/claude-skills
|
||||
- **Focus**: Workflow-oriented, creation pipelines
|
||||
- **Quality**: Well-structured
|
||||
- **Best for**: Understanding workflow patterns
|
||||
|
||||
### Microck/ordinary-claude-skills
|
||||
- **URL**: https://github.com/Microck/ordinary-claude-skills
|
||||
- **Focus**: Large general collection
|
||||
- **Quality**: Variable
|
||||
- **Best for**: Mining for specific needs
|
||||
|
||||
### sickn33/antigravity-awesome-skills
|
||||
- **URL**: https://github.com/sickn33/antigravity-awesome-skills
|
||||
- **Focus**: Registry-style organization
|
||||
- **Quality**: Highly structured
|
||||
- **Best for**: Easy browsing and copying
|
||||
|
||||
### synapz-org/marketing-ops-hub
|
||||
- **URL**: https://github.com/synapz-org/marketing-ops-hub
|
||||
- **Focus**: Marketing, operations, growth
|
||||
- **Quality**: Domain-specific
|
||||
- **Best for**: Marketing automation workflows
|
||||
|
||||
### m2ai-portfolio/claude-skills
|
||||
- **URL**: https://github.com/m2ai-portfolio/claude-skills
|
||||
- **Focus**: Creator, growth, writing
|
||||
- **Quality**: Platform-oriented
|
||||
- **Best for**: Content creation workflows
|
||||
|
||||
---
|
||||
|
||||
## Skills: Tools & Documentation
|
||||
|
||||
### SkillHub Desktop
|
||||
- **URL**: https://github.com/skillhub-club/skillhub-desktop
|
||||
- **Type**: Desktop manager
|
||||
- **Features**: Cross-tool sync (Claude/Cursor)
|
||||
- **Best for**: Team skill management
|
||||
|
||||
### Official Claude Skills Docs
|
||||
- **URL**: https://code.claude.com/docs/en/skills
|
||||
- **Type**: Official documentation
|
||||
- **Content**: Structure, rules, best practices
|
||||
- **Best for**: Creating/modifying skills
|
||||
|
||||
### Official OpenAI Codex Skills Docs
|
||||
- **URL**: https://developers.openai.com/codex/skills/
|
||||
- **Type**: Official documentation
|
||||
- **Content**: Codex/ChatGPT skill usage
|
||||
- **Best for**: Cross-platform compatibility
|
||||
|
||||
---
|
||||
|
||||
## MCP: Official Resources
|
||||
|
||||
### MCP Official Servers Repository
|
||||
- **URL**: https://github.com/modelcontextprotocol/servers
|
||||
- **Type**: Official reference
|
||||
- **Content**: Reference implementations, community index
|
||||
- **Best for**: Starting point, official servers
|
||||
|
||||
### MCP Official Examples
|
||||
- **URL**: https://modelcontextprotocol.io/examples
|
||||
- **Type**: Official examples
|
||||
- **Content**: Integration examples, tutorials
|
||||
- **Best for**: Learning MCP patterns
|
||||
|
||||
### MCP Registry (Repository)
|
||||
- **URL**: https://github.com/modelcontextprotocol/registry
|
||||
- **Type**: Registry service code
|
||||
- **Content**: Self-hosted registry implementation
|
||||
- **Best for**: Enterprise internal distribution
|
||||
|
||||
### MCP Registry (Web)
|
||||
- **URL**: https://registry.modelcontextprotocol.io/
|
||||
- **Type**: Official registry
|
||||
- **Content**: Browse registered MCPs
|
||||
- **Best for**: Finding official/verified MCPs
|
||||
|
||||
---
|
||||
|
||||
## MCP: Marketplaces & Directories
|
||||
|
||||
### Glama MCP Directory
|
||||
- **URL**: https://glama.ai/mcp/servers
|
||||
- **Type**: Large directory
|
||||
- **Features**: Stars, downloads, last updated
|
||||
- **Best for**: Finding popular, maintained servers
|
||||
|
||||
### Glama MCP Entry
|
||||
- **URL**: https://glama.ai/mcp
|
||||
- **Type**: Portal
|
||||
- **Features**: Servers, clients, tools navigation
|
||||
- **Best for**: Team unified entry point
|
||||
|
||||
### MCP Market
|
||||
- **URL**: https://mcpmarket.com/
|
||||
- **Type**: Marketplace
|
||||
- **Features**: MCP servers + clients
|
||||
- **Best for**: Combined skill/MCP discovery
|
||||
|
||||
### Awesome MCP Servers (mcpservers.org)
|
||||
- **URL**: https://mcpservers.org/
|
||||
- **Type**: Categorized directory
|
||||
- **Features**: Official/Remote/Clients categories
|
||||
- **Best for**: Structured browsing
|
||||
|
||||
### PulseMCP Servers
|
||||
- **URL**: https://www.pulsemcp.com/servers
|
||||
- **Type**: Index
|
||||
- **Features**: Full index, daily updates
|
||||
- **Best for**: Tracking new arrivals
|
||||
|
||||
### MCP.so Servers
|
||||
- **URL**: https://mcp.so/servers
|
||||
- **Type**: Directory
|
||||
- **Features**: Multi-language (CN/EN)
|
||||
- **Best for**: Wide coverage
|
||||
|
||||
### Smithery
|
||||
- **URL**: https://smithery.ai/
|
||||
- **Type**: Registry/distribution
|
||||
- **Features**: Publish, discover, install
|
||||
- **Best for**: "App store" experience
|
||||
|
||||
---
|
||||
|
||||
## MCP: GitHub Lists
|
||||
|
||||
### punkpeye/awesome-mcp-servers
|
||||
- **URL**: https://github.com/punkpeye/awesome-mcp-servers
|
||||
- **Type**: Awesome list
|
||||
- **Features**: Domain categorization
|
||||
- **Best for**: Classic curated list
|
||||
|
||||
### wong2/awesome-mcp-servers
|
||||
- **URL**: https://github.com/wong2/awesome-mcp-servers
|
||||
- **Type**: Awesome list
|
||||
- **Features**: Alternative curation
|
||||
- **Best for**: Additional discoveries
|
||||
|
||||
---
|
||||
|
||||
## Enterprise Resources
|
||||
|
||||
### GitHub MCP Registry Configuration
|
||||
- **URL**: https://docs.github.com/en/copilot/how-tos/administer-copilot/manage-mcp-usage/configure-mcp-registry
|
||||
- **Type**: Documentation
|
||||
- **Content**: Organization-level MCP registry setup
|
||||
- **Best for**: Enterprise governance, compliance
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "{{FORMAT_HOOK}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "{{PROTECT_FILES_HOOK}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
---
|
||||
name: skill-creator
|
||||
description: Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends Claude's capabilities with specialized knowledge, workflows, or tool integrations.
|
||||
license: Complete terms in LICENSE.txt
|
||||
---
|
||||
|
||||
# Skill Creator
|
||||
|
||||
This skill provides guidance for creating effective skills.
|
||||
|
||||
## About Skills
|
||||
|
||||
Skills are modular, self-contained packages that extend Claude's capabilities by providing
|
||||
specialized knowledge, workflows, and tools. Think of them as "onboarding guides" for specific
|
||||
domains or tasks—they transform Claude from a general-purpose agent into a specialized agent
|
||||
equipped with procedural knowledge that no model can fully possess.
|
||||
|
||||
### What Skills Provide
|
||||
|
||||
1. Specialized workflows - Multi-step procedures for specific domains
|
||||
2. Tool integrations - Instructions for working with specific file formats or APIs
|
||||
3. Domain expertise - Company-specific knowledge, schemas, business logic
|
||||
4. Bundled resources - Scripts, references, and assets for complex and repetitive tasks
|
||||
|
||||
## Core Principles
|
||||
|
||||
### Concise is Key
|
||||
|
||||
The context window is a public good. Skills share the context window with everything else Claude needs: system prompt, conversation history, other Skills' metadata, and the actual user request.
|
||||
|
||||
**Default assumption: Claude is already very smart.** Only add context Claude doesn't already have. Challenge each piece of information: "Does Claude really need this explanation?" and "Does this paragraph justify its token cost?"
|
||||
|
||||
Prefer concise examples over verbose explanations.
|
||||
|
||||
### Set Appropriate Degrees of Freedom
|
||||
|
||||
Match the level of specificity to the task's fragility and variability:
|
||||
|
||||
**High freedom (text-based instructions)**: Use when multiple approaches are valid, decisions depend on context, or heuristics guide the approach.
|
||||
|
||||
**Medium freedom (pseudocode or scripts with parameters)**: Use when a preferred pattern exists, some variation is acceptable, or configuration affects behavior.
|
||||
|
||||
**Low freedom (specific scripts, few parameters)**: Use when operations are fragile and error-prone, consistency is critical, or a specific sequence must be followed.
|
||||
|
||||
Think of Claude as exploring a path: a narrow bridge with cliffs needs specific guardrails (low freedom), while an open field allows many routes (high freedom).
|
||||
|
||||
### Anatomy of a Skill
|
||||
|
||||
Every skill consists of a required SKILL.md file and optional bundled resources:
|
||||
|
||||
```
|
||||
skill-name/
|
||||
├── SKILL.md (required)
|
||||
│ ├── YAML frontmatter metadata (required)
|
||||
│ │ ├── name: (required)
|
||||
│ │ └── description: (required)
|
||||
│ └── Markdown instructions (required)
|
||||
└── Bundled Resources (optional)
|
||||
├── scripts/ - Executable code (Python/Bash/etc.)
|
||||
├── references/ - Documentation intended to be loaded into context as needed
|
||||
└── assets/ - Files used in output (templates, icons, fonts, etc.)
|
||||
```
|
||||
|
||||
#### SKILL.md (required)
|
||||
|
||||
Every SKILL.md consists of:
|
||||
|
||||
- **Frontmatter** (YAML): Contains `name` and `description` fields. These are the only fields that Claude reads to determine when the skill gets used, thus it is very important to be clear and comprehensive in describing what the skill is, and when it should be used.
|
||||
- **Body** (Markdown): Instructions and guidance for using the skill. Only loaded AFTER the skill triggers (if at all).
|
||||
|
||||
#### Bundled Resources (optional)
|
||||
|
||||
##### Scripts (`scripts/`)
|
||||
|
||||
Executable code (Python/Bash/etc.) for tasks that require deterministic reliability or are repeatedly rewritten.
|
||||
|
||||
- **When to include**: When the same code is being rewritten repeatedly or deterministic reliability is needed
|
||||
- **Example**: `scripts/rotate_pdf.py` for PDF rotation tasks
|
||||
- **Benefits**: Token efficient, deterministic, may be executed without loading into context
|
||||
- **Note**: Scripts may still need to be read by Claude for patching or environment-specific adjustments
|
||||
|
||||
##### References (`references/`)
|
||||
|
||||
Documentation and reference material intended to be loaded as needed into context to inform Claude's process and thinking.
|
||||
|
||||
- **When to include**: For documentation that Claude should reference while working
|
||||
- **Examples**: `references/finance.md` for financial schemas, `references/mnda.md` for company NDA template, `references/policies.md` for company policies, `references/api_docs.md` for API specifications
|
||||
- **Use cases**: Database schemas, API documentation, domain knowledge, company policies, detailed workflow guides
|
||||
- **Benefits**: Keeps SKILL.md lean, loaded only when Claude determines it's needed
|
||||
- **Best practice**: If files are large (>10k words), include grep search patterns in SKILL.md
|
||||
- **Avoid duplication**: Information should live in either SKILL.md or references files, not both. Prefer references files for detailed information unless it's truly core to the skill—this keeps SKILL.md lean while making information discoverable without hogging the context window. Keep only essential procedural instructions and workflow guidance in SKILL.md; move detailed reference material, schemas, and examples to references files.
|
||||
|
||||
##### Assets (`assets/`)
|
||||
|
||||
Files not intended to be loaded into context, but rather used within the output Claude produces.
|
||||
|
||||
- **When to include**: When the skill needs files that will be used in the final output
|
||||
- **Examples**: `assets/logo.png` for brand assets, `assets/slides.pptx` for PowerPoint templates, `assets/frontend-template/` for HTML/React boilerplate, `assets/font.ttf` for typography
|
||||
- **Use cases**: Templates, images, icons, boilerplate code, fonts, sample documents that get copied or modified
|
||||
- **Benefits**: Separates output resources from documentation, enables Claude to use files without loading them into context
|
||||
|
||||
#### What to Not Include in a Skill
|
||||
|
||||
A skill should only contain essential files that directly support its functionality. Do NOT create extraneous documentation or auxiliary files, including:
|
||||
|
||||
- README.md
|
||||
- INSTALLATION_GUIDE.md
|
||||
- QUICK_REFERENCE.md
|
||||
- CHANGELOG.md
|
||||
- etc.
|
||||
|
||||
The skill should only contain the information needed for an AI agent to do the job at hand. It should not contain auxilary context about the process that went into creating it, setup and testing procedures, user-facing documentation, etc. Creating additional documentation files just adds clutter and confusion.
|
||||
|
||||
### Progressive Disclosure Design Principle
|
||||
|
||||
Skills use a three-level loading system to manage context efficiently:
|
||||
|
||||
1. **Metadata (name + description)** - Always in context (~100 words)
|
||||
2. **SKILL.md body** - When skill triggers (<5k words)
|
||||
3. **Bundled resources** - As needed by Claude (Unlimited because scripts can be executed without reading into context window)
|
||||
|
||||
#### Progressive Disclosure Patterns
|
||||
|
||||
Keep SKILL.md body to the essentials and under 500 lines to minimize context bloat. Split content into separate files when approaching this limit. When splitting out content into other files, it is very important to reference them from SKILL.md and describe clearly when to read them, to ensure the reader of the skill knows they exist and when to use them.
|
||||
|
||||
**Key principle:** When a skill supports multiple variations, frameworks, or options, keep only the core workflow and selection guidance in SKILL.md. Move variant-specific details (patterns, examples, configuration) into separate reference files.
|
||||
|
||||
**Pattern 1: High-level guide with references**
|
||||
|
||||
```markdown
|
||||
# PDF Processing
|
||||
|
||||
## Quick start
|
||||
|
||||
Extract text with pdfplumber:
|
||||
[code example]
|
||||
|
||||
## Advanced features
|
||||
|
||||
- **Form filling**: See [FORMS.md](FORMS.md) for complete guide
|
||||
- **API reference**: See [REFERENCE.md](REFERENCE.md) for all methods
|
||||
- **Examples**: See [EXAMPLES.md](EXAMPLES.md) for common patterns
|
||||
```
|
||||
|
||||
Claude loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed.
|
||||
|
||||
**Pattern 2: Domain-specific organization**
|
||||
|
||||
For Skills with multiple domains, organize content by domain to avoid loading irrelevant context:
|
||||
|
||||
```
|
||||
bigquery-skill/
|
||||
├── SKILL.md (overview and navigation)
|
||||
└── reference/
|
||||
├── finance.md (revenue, billing metrics)
|
||||
├── sales.md (opportunities, pipeline)
|
||||
├── product.md (API usage, features)
|
||||
└── marketing.md (campaigns, attribution)
|
||||
```
|
||||
|
||||
When a user asks about sales metrics, Claude only reads sales.md.
|
||||
|
||||
Similarly, for skills supporting multiple frameworks or variants, organize by variant:
|
||||
|
||||
```
|
||||
cloud-deploy/
|
||||
├── SKILL.md (workflow + provider selection)
|
||||
└── references/
|
||||
├── aws.md (AWS deployment patterns)
|
||||
├── gcp.md (GCP deployment patterns)
|
||||
└── azure.md (Azure deployment patterns)
|
||||
```
|
||||
|
||||
When the user chooses AWS, Claude only reads aws.md.
|
||||
|
||||
**Pattern 3: Conditional details**
|
||||
|
||||
Show basic content, link to advanced content:
|
||||
|
||||
```markdown
|
||||
# DOCX Processing
|
||||
|
||||
## Creating documents
|
||||
|
||||
Use docx-js for new documents. See [DOCX-JS.md](DOCX-JS.md).
|
||||
|
||||
## Editing documents
|
||||
|
||||
For simple edits, modify the XML directly.
|
||||
|
||||
**For tracked changes**: See [REDLINING.md](REDLINING.md)
|
||||
**For OOXML details**: See [OOXML.md](OOXML.md)
|
||||
```
|
||||
|
||||
Claude reads REDLINING.md or OOXML.md only when the user needs those features.
|
||||
|
||||
**Important guidelines:**
|
||||
|
||||
- **Avoid deeply nested references** - Keep references one level deep from SKILL.md. All reference files should link directly from SKILL.md.
|
||||
- **Structure longer reference files** - For files longer than 100 lines, include a table of contents at the top so Claude can see the full scope when previewing.
|
||||
|
||||
## Skill Creation Process
|
||||
|
||||
Skill creation involves these steps:
|
||||
|
||||
1. Understand the skill with concrete examples
|
||||
2. Plan reusable skill contents (scripts, references, assets)
|
||||
3. Initialize the skill (run init_skill.py)
|
||||
4. Edit the skill (implement resources and write SKILL.md)
|
||||
5. Package the skill (run package_skill.py)
|
||||
6. Iterate based on real usage
|
||||
|
||||
Follow these steps in order, skipping only if there is a clear reason why they are not applicable.
|
||||
|
||||
### Step 1: Understanding the Skill with Concrete Examples
|
||||
|
||||
Skip this step only when the skill's usage patterns are already clearly understood. It remains valuable even when working with an existing skill.
|
||||
|
||||
To create an effective skill, clearly understand concrete examples of how the skill will be used. This understanding can come from either direct user examples or generated examples that are validated with user feedback.
|
||||
|
||||
For example, when building an image-editor skill, relevant questions include:
|
||||
|
||||
- "What functionality should the image-editor skill support? Editing, rotating, anything else?"
|
||||
- "Can you give some examples of how this skill would be used?"
|
||||
- "I can imagine users asking for things like 'Remove the red-eye from this image' or 'Rotate this image'. Are there other ways you imagine this skill being used?"
|
||||
- "What would a user say that should trigger this skill?"
|
||||
|
||||
To avoid overwhelming users, avoid asking too many questions in a single message. Start with the most important questions and follow up as needed for better effectiveness.
|
||||
|
||||
Conclude this step when there is a clear sense of the functionality the skill should support.
|
||||
|
||||
### Step 2: Planning the Reusable Skill Contents
|
||||
|
||||
To turn concrete examples into an effective skill, analyze each example by:
|
||||
|
||||
1. Considering how to execute on the example from scratch
|
||||
2. Identifying what scripts, references, and assets would be helpful when executing these workflows repeatedly
|
||||
|
||||
Example: When building a `pdf-editor` skill to handle queries like "Help me rotate this PDF," the analysis shows:
|
||||
|
||||
1. Rotating a PDF requires re-writing the same code each time
|
||||
2. A `scripts/rotate_pdf.py` script would be helpful to store in the skill
|
||||
|
||||
Example: When designing a `frontend-webapp-builder` skill for queries like "Build me a todo app" or "Build me a dashboard to track my steps," the analysis shows:
|
||||
|
||||
1. Writing a frontend webapp requires the same boilerplate HTML/React each time
|
||||
2. An `assets/hello-world/` template containing the boilerplate HTML/React project files would be helpful to store in the skill
|
||||
|
||||
Example: When building a `big-query` skill to handle queries like "How many users have logged in today?" the analysis shows:
|
||||
|
||||
1. Querying BigQuery requires re-discovering the table schemas and relationships each time
|
||||
2. A `references/schema.md` file documenting the table schemas would be helpful to store in the skill
|
||||
|
||||
To establish the skill's contents, analyze each concrete example to create a list of the reusable resources to include: scripts, references, and assets.
|
||||
|
||||
### Step 3: Initializing the Skill
|
||||
|
||||
At this point, it is time to actually create the skill.
|
||||
|
||||
Skip this step only if the skill being developed already exists, and iteration or packaging is needed. In this case, continue to the next step.
|
||||
|
||||
When creating a new skill from scratch, always run the `init_skill.py` script. The script conveniently generates a new template skill directory that automatically includes everything a skill requires, making the skill creation process much more efficient and reliable.
|
||||
|
||||
Usage:
|
||||
|
||||
```bash
|
||||
scripts/init_skill.py <skill-name> --path <output-directory>
|
||||
```
|
||||
|
||||
The script:
|
||||
|
||||
- Creates the skill directory at the specified path
|
||||
- Generates a SKILL.md template with proper frontmatter and TODO placeholders
|
||||
- Creates example resource directories: `scripts/`, `references/`, and `assets/`
|
||||
- Adds example files in each directory that can be customized or deleted
|
||||
|
||||
After initialization, customize or remove the generated SKILL.md and example files as needed.
|
||||
|
||||
### Step 4: Edit the Skill
|
||||
|
||||
When editing the (newly-generated or existing) skill, remember that the skill is being created for another instance of Claude to use. Include information that would be beneficial and non-obvious to Claude. Consider what procedural knowledge, domain-specific details, or reusable assets would help another Claude instance execute these tasks more effectively.
|
||||
|
||||
#### Learn Proven Design Patterns
|
||||
|
||||
Consult these helpful guides based on your skill's needs:
|
||||
|
||||
- **Multi-step processes**: See references/workflows.md for sequential workflows and conditional logic
|
||||
- **Specific output formats or quality standards**: See references/output-patterns.md for template and example patterns
|
||||
|
||||
These files contain established best practices for effective skill design.
|
||||
|
||||
#### Start with Reusable Skill Contents
|
||||
|
||||
To begin implementation, start with the reusable resources identified above: `scripts/`, `references/`, and `assets/` files. Note that this step may require user input. For example, when implementing a `brand-guidelines` skill, the user may need to provide brand assets or templates to store in `assets/`, or documentation to store in `references/`.
|
||||
|
||||
Added scripts must be tested by actually running them to ensure there are no bugs and that the output matches what is expected. If there are many similar scripts, only a representative sample needs to be tested to ensure confidence that they all work while balancing time to completion.
|
||||
|
||||
Any example files and directories not needed for the skill should be deleted. The initialization script creates example files in `scripts/`, `references/`, and `assets/` to demonstrate structure, but most skills won't need all of them.
|
||||
|
||||
#### Update SKILL.md
|
||||
|
||||
**Writing Guidelines:** Always use imperative/infinitive form.
|
||||
|
||||
##### Frontmatter
|
||||
|
||||
Write the YAML frontmatter with `name` and `description`:
|
||||
|
||||
- `name`: The skill name
|
||||
- `description`: This is the primary triggering mechanism for your skill, and helps Claude understand when to use the skill.
|
||||
- Include both what the Skill does and specific triggers/contexts for when to use it.
|
||||
- Include all "when to use" information here - Not in the body. The body is only loaded after triggering, so "When to Use This Skill" sections in the body are not helpful to Claude.
|
||||
- Example description for a `docx` skill: "Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. Use when Claude needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks"
|
||||
|
||||
Do not include any other fields in YAML frontmatter.
|
||||
|
||||
##### Body
|
||||
|
||||
Write instructions for using the skill and its bundled resources.
|
||||
|
||||
### Step 5: Packaging a Skill
|
||||
|
||||
Once development of the skill is complete, it must be packaged into a distributable .skill file that gets shared with the user. The packaging process automatically validates the skill first to ensure it meets all requirements:
|
||||
|
||||
```bash
|
||||
scripts/package_skill.py <path/to/skill-folder>
|
||||
```
|
||||
|
||||
Optional output directory specification:
|
||||
|
||||
```bash
|
||||
scripts/package_skill.py <path/to/skill-folder> ./dist
|
||||
```
|
||||
|
||||
The packaging script will:
|
||||
|
||||
1. **Validate** the skill automatically, checking:
|
||||
- YAML frontmatter format and required fields
|
||||
- Skill naming conventions and directory structure
|
||||
- Description completeness and quality
|
||||
- File organization and resource references
|
||||
|
||||
2. **Package** the skill if validation passes, creating a .skill file named after the skill (e.g., `my-skill.skill`) that includes all files and maintains the proper directory structure for distribution. The .skill file is a zip file with a .skill extension.
|
||||
|
||||
If validation fails, the script will report the errors and exit without creating a package. Fix any validation errors and run the packaging command again.
|
||||
|
||||
### Step 6: Iterate
|
||||
|
||||
After testing the skill, users may request improvements. Often this happens right after using the skill, with fresh context of how the skill performed.
|
||||
|
||||
**Iteration workflow:**
|
||||
|
||||
1. Use the skill on real tasks
|
||||
2. Notice struggles or inefficiencies
|
||||
3. Identify how SKILL.md or bundled resources should be updated
|
||||
4. Implement changes and test again
|
||||
@@ -0,0 +1,92 @@
|
||||
# Output Patterns
|
||||
|
||||
Use these patterns when skills need to produce consistent, high-quality output.
|
||||
|
||||
## Template Pattern
|
||||
|
||||
Provide templates for output format. Match the level of strictness to your needs.
|
||||
|
||||
**For strict requirements (like API responses or data formats):**
|
||||
|
||||
```markdown
|
||||
## Report structure
|
||||
|
||||
ALWAYS use this exact template structure:
|
||||
|
||||
# [Analysis Title]
|
||||
|
||||
## Executive summary
|
||||
|
||||
[One-paragraph overview of key findings]
|
||||
|
||||
## Key findings
|
||||
|
||||
- Finding 1 with supporting data
|
||||
- Finding 2 with supporting data
|
||||
- Finding 3 with supporting data
|
||||
|
||||
## Recommendations
|
||||
|
||||
1. Specific actionable recommendation
|
||||
2. Specific actionable recommendation
|
||||
```
|
||||
|
||||
**For flexible guidance (when adaptation is useful):**
|
||||
|
||||
```markdown
|
||||
## Report structure
|
||||
|
||||
Here is a sensible default format, but use your best judgment:
|
||||
|
||||
# [Analysis Title]
|
||||
|
||||
## Executive summary
|
||||
|
||||
[Overview]
|
||||
|
||||
## Key findings
|
||||
|
||||
[Adapt sections based on what you discover]
|
||||
|
||||
## Recommendations
|
||||
|
||||
[Tailor to the specific context]
|
||||
|
||||
Adjust sections as needed for the specific analysis type.
|
||||
```
|
||||
|
||||
## Examples Pattern
|
||||
|
||||
For skills where output quality depends on seeing examples, provide input/output pairs:
|
||||
|
||||
```markdown
|
||||
## Commit message format
|
||||
|
||||
Generate commit messages following these examples:
|
||||
|
||||
**Example 1:**
|
||||
Input: Added user authentication with JWT tokens
|
||||
Output:
|
||||
```
|
||||
|
||||
feat(auth): implement JWT-based authentication
|
||||
|
||||
Add login endpoint and token validation middleware
|
||||
|
||||
```
|
||||
|
||||
**Example 2:**
|
||||
Input: Fixed bug where dates displayed incorrectly in reports
|
||||
Output:
|
||||
```
|
||||
|
||||
fix(reports): correct date formatting in timezone conversion
|
||||
|
||||
Use UTC timestamps consistently across report generation
|
||||
|
||||
```
|
||||
|
||||
Follow this style: type(scope): brief description, then detailed explanation.
|
||||
```
|
||||
|
||||
Examples help Claude understand the desired style and level of detail more clearly than descriptions alone.
|
||||
@@ -0,0 +1,28 @@
|
||||
# Workflow Patterns
|
||||
|
||||
## Sequential Workflows
|
||||
|
||||
For complex tasks, break operations into clear, sequential steps. It is often helpful to give Claude an overview of the process towards the beginning of SKILL.md:
|
||||
|
||||
```markdown
|
||||
Filling a PDF form involves these steps:
|
||||
|
||||
1. Analyze the form (run analyze_form.py)
|
||||
2. Create field mapping (edit fields.json)
|
||||
3. Validate mapping (run validate_fields.py)
|
||||
4. Fill the form (run fill_form.py)
|
||||
5. Verify output (run verify_output.py)
|
||||
```
|
||||
|
||||
## Conditional Workflows
|
||||
|
||||
For tasks with branching logic, guide Claude through decision points:
|
||||
|
||||
```markdown
|
||||
1. Determine the modification type:
|
||||
**Creating new content?** → Follow "Creation workflow" below
|
||||
**Editing existing content?** → Follow "Editing workflow" below
|
||||
|
||||
2. Creation workflow: [steps]
|
||||
3. Editing workflow: [steps]
|
||||
```
|
||||
@@ -0,0 +1,303 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Skill Initializer - Creates a new skill from template
|
||||
|
||||
Usage:
|
||||
init_skill.py <skill-name> --path <path>
|
||||
|
||||
Examples:
|
||||
init_skill.py my-new-skill --path skills/public
|
||||
init_skill.py my-api-helper --path skills/private
|
||||
init_skill.py custom-skill --path /custom/location
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
SKILL_TEMPLATE = """---
|
||||
name: {skill_name}
|
||||
description: [TODO: Complete and informative explanation of what the skill does and when to use it. Include WHEN to use this skill - specific scenarios, file types, or tasks that trigger it.]
|
||||
---
|
||||
|
||||
# {skill_title}
|
||||
|
||||
## Overview
|
||||
|
||||
[TODO: 1-2 sentences explaining what this skill enables]
|
||||
|
||||
## Structuring This Skill
|
||||
|
||||
[TODO: Choose the structure that best fits this skill's purpose. Common patterns:
|
||||
|
||||
**1. Workflow-Based** (best for sequential processes)
|
||||
- Works well when there are clear step-by-step procedures
|
||||
- Example: DOCX skill with "Workflow Decision Tree" → "Reading" → "Creating" → "Editing"
|
||||
- Structure: ## Overview → ## Workflow Decision Tree → ## Step 1 → ## Step 2...
|
||||
|
||||
**2. Task-Based** (best for tool collections)
|
||||
- Works well when the skill offers different operations/capabilities
|
||||
- Example: PDF skill with "Quick Start" → "Merge PDFs" → "Split PDFs" → "Extract Text"
|
||||
- Structure: ## Overview → ## Quick Start → ## Task Category 1 → ## Task Category 2...
|
||||
|
||||
**3. Reference/Guidelines** (best for standards or specifications)
|
||||
- Works well for brand guidelines, coding standards, or requirements
|
||||
- Example: Brand styling with "Brand Guidelines" → "Colors" → "Typography" → "Features"
|
||||
- Structure: ## Overview → ## Guidelines → ## Specifications → ## Usage...
|
||||
|
||||
**4. Capabilities-Based** (best for integrated systems)
|
||||
- Works well when the skill provides multiple interrelated features
|
||||
- Example: Product Management with "Core Capabilities" → numbered capability list
|
||||
- Structure: ## Overview → ## Core Capabilities → ### 1. Feature → ### 2. Feature...
|
||||
|
||||
Patterns can be mixed and matched as needed. Most skills combine patterns (e.g., start with task-based, add workflow for complex operations).
|
||||
|
||||
Delete this entire "Structuring This Skill" section when done - it's just guidance.]
|
||||
|
||||
## [TODO: Replace with the first main section based on chosen structure]
|
||||
|
||||
[TODO: Add content here. See examples in existing skills:
|
||||
- Code samples for technical skills
|
||||
- Decision trees for complex workflows
|
||||
- Concrete examples with realistic user requests
|
||||
- References to scripts/templates/references as needed]
|
||||
|
||||
## Resources
|
||||
|
||||
This skill includes example resource directories that demonstrate how to organize different types of bundled resources:
|
||||
|
||||
### scripts/
|
||||
Executable code (Python/Bash/etc.) that can be run directly to perform specific operations.
|
||||
|
||||
**Examples from other skills:**
|
||||
- PDF skill: `fill_fillable_fields.py`, `extract_form_field_info.py` - utilities for PDF manipulation
|
||||
- DOCX skill: `document.py`, `utilities.py` - Python modules for document processing
|
||||
|
||||
**Appropriate for:** Python scripts, shell scripts, or any executable code that performs automation, data processing, or specific operations.
|
||||
|
||||
**Note:** Scripts may be executed without loading into context, but can still be read by Claude for patching or environment adjustments.
|
||||
|
||||
### references/
|
||||
Documentation and reference material intended to be loaded into context to inform Claude's process and thinking.
|
||||
|
||||
**Examples from other skills:**
|
||||
- Product management: `communication.md`, `context_building.md` - detailed workflow guides
|
||||
- BigQuery: API reference documentation and query examples
|
||||
- Finance: Schema documentation, company policies
|
||||
|
||||
**Appropriate for:** In-depth documentation, API references, database schemas, comprehensive guides, or any detailed information that Claude should reference while working.
|
||||
|
||||
### assets/
|
||||
Files not intended to be loaded into context, but rather used within the output Claude produces.
|
||||
|
||||
**Examples from other skills:**
|
||||
- Brand styling: PowerPoint template files (.pptx), logo files
|
||||
- Frontend builder: HTML/React boilerplate project directories
|
||||
- Typography: Font files (.ttf, .woff2)
|
||||
|
||||
**Appropriate for:** Templates, boilerplate code, document templates, images, icons, fonts, or any files meant to be copied or used in the final output.
|
||||
|
||||
---
|
||||
|
||||
**Any unneeded directories can be deleted.** Not every skill requires all three types of resources.
|
||||
"""
|
||||
|
||||
EXAMPLE_SCRIPT = '''#!/usr/bin/env python3
|
||||
"""
|
||||
Example helper script for {skill_name}
|
||||
|
||||
This is a placeholder script that can be executed directly.
|
||||
Replace with actual implementation or delete if not needed.
|
||||
|
||||
Example real scripts from other skills:
|
||||
- pdf/scripts/fill_fillable_fields.py - Fills PDF form fields
|
||||
- pdf/scripts/convert_pdf_to_images.py - Converts PDF pages to images
|
||||
"""
|
||||
|
||||
def main():
|
||||
print("This is an example script for {skill_name}")
|
||||
# TODO: Add actual script logic here
|
||||
# This could be data processing, file conversion, API calls, etc.
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
'''
|
||||
|
||||
EXAMPLE_REFERENCE = """# Reference Documentation for {skill_title}
|
||||
|
||||
This is a placeholder for detailed reference documentation.
|
||||
Replace with actual reference content or delete if not needed.
|
||||
|
||||
Example real reference docs from other skills:
|
||||
- product-management/references/communication.md - Comprehensive guide for status updates
|
||||
- product-management/references/context_building.md - Deep-dive on gathering context
|
||||
- bigquery/references/ - API references and query examples
|
||||
|
||||
## When Reference Docs Are Useful
|
||||
|
||||
Reference docs are ideal for:
|
||||
- Comprehensive API documentation
|
||||
- Detailed workflow guides
|
||||
- Complex multi-step processes
|
||||
- Information too lengthy for main SKILL.md
|
||||
- Content that's only needed for specific use cases
|
||||
|
||||
## Structure Suggestions
|
||||
|
||||
### API Reference Example
|
||||
- Overview
|
||||
- Authentication
|
||||
- Endpoints with examples
|
||||
- Error codes
|
||||
- Rate limits
|
||||
|
||||
### Workflow Guide Example
|
||||
- Prerequisites
|
||||
- Step-by-step instructions
|
||||
- Common patterns
|
||||
- Troubleshooting
|
||||
- Best practices
|
||||
"""
|
||||
|
||||
EXAMPLE_ASSET = """# Example Asset File
|
||||
|
||||
This placeholder represents where asset files would be stored.
|
||||
Replace with actual asset files (templates, images, fonts, etc.) or delete if not needed.
|
||||
|
||||
Asset files are NOT intended to be loaded into context, but rather used within
|
||||
the output Claude produces.
|
||||
|
||||
Example asset files from other skills:
|
||||
- Brand guidelines: logo.png, slides_template.pptx
|
||||
- Frontend builder: hello-world/ directory with HTML/React boilerplate
|
||||
- Typography: custom-font.ttf, font-family.woff2
|
||||
- Data: sample_data.csv, test_dataset.json
|
||||
|
||||
## Common Asset Types
|
||||
|
||||
- Templates: .pptx, .docx, boilerplate directories
|
||||
- Images: .png, .jpg, .svg, .gif
|
||||
- Fonts: .ttf, .otf, .woff, .woff2
|
||||
- Boilerplate code: Project directories, starter files
|
||||
- Icons: .ico, .svg
|
||||
- Data files: .csv, .json, .xml, .yaml
|
||||
|
||||
Note: This is a text placeholder. Actual assets can be any file type.
|
||||
"""
|
||||
|
||||
|
||||
def title_case_skill_name(skill_name):
|
||||
"""Convert hyphenated skill name to Title Case for display."""
|
||||
return ' '.join(word.capitalize() for word in skill_name.split('-'))
|
||||
|
||||
|
||||
def init_skill(skill_name, path):
|
||||
"""
|
||||
Initialize a new skill directory with template SKILL.md.
|
||||
|
||||
Args:
|
||||
skill_name: Name of the skill
|
||||
path: Path where the skill directory should be created
|
||||
|
||||
Returns:
|
||||
Path to created skill directory, or None if error
|
||||
"""
|
||||
# Determine skill directory path
|
||||
skill_dir = Path(path).resolve() / skill_name
|
||||
|
||||
# Check if directory already exists
|
||||
if skill_dir.exists():
|
||||
print(f"❌ Error: Skill directory already exists: {skill_dir}")
|
||||
return None
|
||||
|
||||
# Create skill directory
|
||||
try:
|
||||
skill_dir.mkdir(parents=True, exist_ok=False)
|
||||
print(f"✅ Created skill directory: {skill_dir}")
|
||||
except Exception as e:
|
||||
print(f"❌ Error creating directory: {e}")
|
||||
return None
|
||||
|
||||
# Create SKILL.md from template
|
||||
skill_title = title_case_skill_name(skill_name)
|
||||
skill_content = SKILL_TEMPLATE.format(
|
||||
skill_name=skill_name,
|
||||
skill_title=skill_title
|
||||
)
|
||||
|
||||
skill_md_path = skill_dir / 'SKILL.md'
|
||||
try:
|
||||
skill_md_path.write_text(skill_content)
|
||||
print("✅ Created SKILL.md")
|
||||
except Exception as e:
|
||||
print(f"❌ Error creating SKILL.md: {e}")
|
||||
return None
|
||||
|
||||
# Create resource directories with example files
|
||||
try:
|
||||
# Create scripts/ directory with example script
|
||||
scripts_dir = skill_dir / 'scripts'
|
||||
scripts_dir.mkdir(exist_ok=True)
|
||||
example_script = scripts_dir / 'example.py'
|
||||
example_script.write_text(EXAMPLE_SCRIPT.format(skill_name=skill_name))
|
||||
example_script.chmod(0o755)
|
||||
print("✅ Created scripts/example.py")
|
||||
|
||||
# Create references/ directory with example reference doc
|
||||
references_dir = skill_dir / 'references'
|
||||
references_dir.mkdir(exist_ok=True)
|
||||
example_reference = references_dir / 'api_reference.md'
|
||||
example_reference.write_text(EXAMPLE_REFERENCE.format(skill_title=skill_title))
|
||||
print("✅ Created references/api_reference.md")
|
||||
|
||||
# Create assets/ directory with example asset placeholder
|
||||
assets_dir = skill_dir / 'assets'
|
||||
assets_dir.mkdir(exist_ok=True)
|
||||
example_asset = assets_dir / 'example_asset.txt'
|
||||
example_asset.write_text(EXAMPLE_ASSET)
|
||||
print("✅ Created assets/example_asset.txt")
|
||||
except Exception as e:
|
||||
print(f"❌ Error creating resource directories: {e}")
|
||||
return None
|
||||
|
||||
# Print next steps
|
||||
print(f"\n✅ Skill '{skill_name}' initialized successfully at {skill_dir}")
|
||||
print("\nNext steps:")
|
||||
print("1. Edit SKILL.md to complete the TODO items and update the description")
|
||||
print("2. Customize or delete the example files in scripts/, references/, and assets/")
|
||||
print("3. Run the validator when ready to check the skill structure")
|
||||
|
||||
return skill_dir
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 4 or sys.argv[2] != '--path':
|
||||
print("Usage: init_skill.py <skill-name> --path <path>")
|
||||
print("\nSkill name requirements:")
|
||||
print(" - Hyphen-case identifier (e.g., 'data-analyzer')")
|
||||
print(" - Lowercase letters, digits, and hyphens only")
|
||||
print(" - Max 40 characters")
|
||||
print(" - Must match directory name exactly")
|
||||
print("\nExamples:")
|
||||
print(" init_skill.py my-new-skill --path skills/public")
|
||||
print(" init_skill.py my-api-helper --path skills/private")
|
||||
print(" init_skill.py custom-skill --path /custom/location")
|
||||
sys.exit(1)
|
||||
|
||||
skill_name = sys.argv[1]
|
||||
path = sys.argv[3]
|
||||
|
||||
print(f"🚀 Initializing skill: {skill_name}")
|
||||
print(f" Location: {path}")
|
||||
print()
|
||||
|
||||
result = init_skill(skill_name, path)
|
||||
|
||||
if result:
|
||||
sys.exit(0)
|
||||
else:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Skill Packager - Creates a distributable .skill file of a skill folder
|
||||
|
||||
Usage:
|
||||
python utils/package_skill.py <path/to/skill-folder> [output-directory]
|
||||
|
||||
Example:
|
||||
python utils/package_skill.py skills/public/my-skill
|
||||
python utils/package_skill.py skills/public/my-skill ./dist
|
||||
"""
|
||||
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from quick_validate import validate_skill
|
||||
|
||||
|
||||
def package_skill(skill_path, output_dir=None):
|
||||
"""
|
||||
Package a skill folder into a .skill file.
|
||||
|
||||
Args:
|
||||
skill_path: Path to the skill folder
|
||||
output_dir: Optional output directory for the .skill file (defaults to current directory)
|
||||
|
||||
Returns:
|
||||
Path to the created .skill file, or None if error
|
||||
"""
|
||||
skill_path = Path(skill_path).resolve()
|
||||
|
||||
# Validate skill folder exists
|
||||
if not skill_path.exists():
|
||||
print(f"❌ Error: Skill folder not found: {skill_path}")
|
||||
return None
|
||||
|
||||
if not skill_path.is_dir():
|
||||
print(f"❌ Error: Path is not a directory: {skill_path}")
|
||||
return None
|
||||
|
||||
# Validate SKILL.md exists
|
||||
skill_md = skill_path / "SKILL.md"
|
||||
if not skill_md.exists():
|
||||
print(f"❌ Error: SKILL.md not found in {skill_path}")
|
||||
return None
|
||||
|
||||
# Run validation before packaging
|
||||
print("🔍 Validating skill...")
|
||||
valid, message = validate_skill(skill_path)
|
||||
if not valid:
|
||||
print(f"❌ Validation failed: {message}")
|
||||
print(" Please fix the validation errors before packaging.")
|
||||
return None
|
||||
print(f"✅ {message}\n")
|
||||
|
||||
# Determine output location
|
||||
skill_name = skill_path.name
|
||||
if output_dir:
|
||||
output_path = Path(output_dir).resolve()
|
||||
output_path.mkdir(parents=True, exist_ok=True)
|
||||
else:
|
||||
output_path = Path.cwd()
|
||||
|
||||
skill_filename = output_path / f"{skill_name}.skill"
|
||||
|
||||
# Create the .skill file (zip format)
|
||||
try:
|
||||
with zipfile.ZipFile(skill_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
||||
# Walk through the skill directory
|
||||
for file_path in skill_path.rglob('*'):
|
||||
if file_path.is_file():
|
||||
# Calculate the relative path within the zip
|
||||
arcname = file_path.relative_to(skill_path.parent)
|
||||
zipf.write(file_path, arcname)
|
||||
print(f" Added: {arcname}")
|
||||
|
||||
print(f"\n✅ Successfully packaged skill to: {skill_filename}")
|
||||
return skill_filename
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error creating .skill file: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: python utils/package_skill.py <path/to/skill-folder> [output-directory]")
|
||||
print("\nExample:")
|
||||
print(" python utils/package_skill.py skills/public/my-skill")
|
||||
print(" python utils/package_skill.py skills/public/my-skill ./dist")
|
||||
sys.exit(1)
|
||||
|
||||
skill_path = sys.argv[1]
|
||||
output_dir = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
|
||||
print(f"📦 Packaging skill: {skill_path}")
|
||||
if output_dir:
|
||||
print(f" Output directory: {output_dir}")
|
||||
print()
|
||||
|
||||
result = package_skill(skill_path, output_dir)
|
||||
|
||||
if result:
|
||||
sys.exit(0)
|
||||
else:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Quick validation script for skills - minimal version
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import re
|
||||
import yaml
|
||||
from pathlib import Path
|
||||
|
||||
def validate_skill(skill_path):
|
||||
"""Basic validation of a skill"""
|
||||
skill_path = Path(skill_path)
|
||||
|
||||
# Check SKILL.md exists
|
||||
skill_md = skill_path / 'SKILL.md'
|
||||
if not skill_md.exists():
|
||||
return False, "SKILL.md not found"
|
||||
|
||||
# Read and validate frontmatter
|
||||
content = skill_md.read_text()
|
||||
if not content.startswith('---'):
|
||||
return False, "No YAML frontmatter found"
|
||||
|
||||
# Extract frontmatter
|
||||
match = re.match(r'^---\n(.*?)\n---', content, re.DOTALL)
|
||||
if not match:
|
||||
return False, "Invalid frontmatter format"
|
||||
|
||||
frontmatter_text = match.group(1)
|
||||
|
||||
# Parse YAML frontmatter
|
||||
try:
|
||||
frontmatter = yaml.safe_load(frontmatter_text)
|
||||
if not isinstance(frontmatter, dict):
|
||||
return False, "Frontmatter must be a YAML dictionary"
|
||||
except yaml.YAMLError as e:
|
||||
return False, f"Invalid YAML in frontmatter: {e}"
|
||||
|
||||
# Define allowed properties
|
||||
ALLOWED_PROPERTIES = {'name', 'description', 'license', 'allowed-tools', 'metadata'}
|
||||
|
||||
# Check for unexpected properties (excluding nested keys under metadata)
|
||||
unexpected_keys = set(frontmatter.keys()) - ALLOWED_PROPERTIES
|
||||
if unexpected_keys:
|
||||
return False, (
|
||||
f"Unexpected key(s) in SKILL.md frontmatter: {', '.join(sorted(unexpected_keys))}. "
|
||||
f"Allowed properties are: {', '.join(sorted(ALLOWED_PROPERTIES))}"
|
||||
)
|
||||
|
||||
# Check required fields
|
||||
if 'name' not in frontmatter:
|
||||
return False, "Missing 'name' in frontmatter"
|
||||
if 'description' not in frontmatter:
|
||||
return False, "Missing 'description' in frontmatter"
|
||||
|
||||
# Extract name for validation
|
||||
name = frontmatter.get('name', '')
|
||||
if not isinstance(name, str):
|
||||
return False, f"Name must be a string, got {type(name).__name__}"
|
||||
name = name.strip()
|
||||
if name:
|
||||
# Check naming convention (hyphen-case: lowercase with hyphens)
|
||||
if not re.match(r'^[a-z0-9-]+$', name):
|
||||
return False, f"Name '{name}' should be hyphen-case (lowercase letters, digits, and hyphens only)"
|
||||
if name.startswith('-') or name.endswith('-') or '--' in name:
|
||||
return False, f"Name '{name}' cannot start/end with hyphen or contain consecutive hyphens"
|
||||
# Check name length (max 64 characters per spec)
|
||||
if len(name) > 64:
|
||||
return False, f"Name is too long ({len(name)} characters). Maximum is 64 characters."
|
||||
|
||||
# Extract and validate description
|
||||
description = frontmatter.get('description', '')
|
||||
if not isinstance(description, str):
|
||||
return False, f"Description must be a string, got {type(description).__name__}"
|
||||
description = description.strip()
|
||||
if description:
|
||||
# Check for angle brackets
|
||||
if '<' in description or '>' in description:
|
||||
return False, "Description cannot contain angle brackets (< or >)"
|
||||
# Check description length (max 1024 characters per spec)
|
||||
if len(description) > 1024:
|
||||
return False, f"Description is too long ({len(description)} characters). Maximum is 1024 characters."
|
||||
|
||||
return True, "Skill is valid!"
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 2:
|
||||
print("Usage: python quick_validate.py <skill_directory>")
|
||||
sys.exit(1)
|
||||
|
||||
valid, message = validate_skill(sys.argv[1])
|
||||
print(message)
|
||||
sys.exit(0 if valid else 1)
|
||||
@@ -0,0 +1,123 @@
|
||||
---
|
||||
name: skill-downloader
|
||||
description: Download and install Claude Code skills from various sources. Supports GitHub repositories, compressed archives (.zip, .tar.gz, .skill), and direct URLs. Use when user wants to download, install, or add a skill from GitHub, URL, or archive file. Triggers on "download skill", "install skill", "add skill from", "get skill".
|
||||
---
|
||||
|
||||
# Skill Downloader
|
||||
|
||||
Download and install Claude Code skills from multiple sources.
|
||||
|
||||
## Supported Sources
|
||||
|
||||
| Source Type | Examples |
|
||||
|-------------|----------|
|
||||
| GitHub Repository | `https://github.com/user/repo`, `github.com/user/repo` |
|
||||
| Compressed Archive | `.zip`, `.tar.gz`, `.tgz`, `.skill` (renamed zip) |
|
||||
| Direct URL | URL pointing to archive or skill folder |
|
||||
|
||||
## Usage
|
||||
|
||||
### Download from GitHub
|
||||
|
||||
```bash
|
||||
python scripts/download_from_github.py <repo-url> <skill-path> --output <target-dir>
|
||||
```
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
# Official Anthropic skills
|
||||
python scripts/download_from_github.py https://github.com/anthropics/skills skills/docx --output ./.claude/skills/
|
||||
|
||||
# Community skills (root level)
|
||||
python scripts/download_from_github.py https://github.com/gked2121/claude-skills social-repurposer --output ./.claude/skills/
|
||||
|
||||
# Nested skill path
|
||||
python scripts/download_from_github.py https://github.com/MadAppGang/claude-code skills/content-brief --output ./.claude/skills/
|
||||
```
|
||||
|
||||
### Download from Archive
|
||||
|
||||
```bash
|
||||
python scripts/download_from_archive.py <url-or-path> --output <target-dir>
|
||||
```
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
# From URL
|
||||
python scripts/download_from_archive.py https://example.com/skills/my-skill.zip --output ./.claude/skills/
|
||||
|
||||
# From local file
|
||||
python scripts/download_from_archive.py ./downloads/my-skill.tar.gz --output ./.claude/skills/
|
||||
|
||||
# .skill files (renamed zip)
|
||||
python scripts/download_from_archive.py https://skillhub.club/download/awesome-skill.skill --output ./.claude/skills/
|
||||
```
|
||||
|
||||
### Unified Download Command
|
||||
|
||||
```bash
|
||||
python scripts/download_skill.py <source> --output <target-dir>
|
||||
```
|
||||
|
||||
Automatically detects source type:
|
||||
- GitHub URL → Uses git sparse checkout
|
||||
- Archive URL/path → Downloads and extracts
|
||||
- Directory path → Copies directly
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
# Auto-detect GitHub
|
||||
python scripts/download_skill.py https://github.com/anthropics/skills/tree/main/skills/docx --output ./.claude/skills/
|
||||
|
||||
# Auto-detect archive
|
||||
python scripts/download_skill.py https://example.com/my-skill.zip --output ./.claude/skills/
|
||||
```
|
||||
|
||||
## Validation
|
||||
|
||||
All download methods validate:
|
||||
1. Skill folder contains `SKILL.md`
|
||||
2. `SKILL.md` has valid YAML frontmatter with `name` and `description`
|
||||
3. No malicious content patterns detected
|
||||
|
||||
## Output Structure
|
||||
|
||||
Downloaded skills are placed in:
|
||||
```
|
||||
<output-dir>/
|
||||
└── <skill-name>/
|
||||
├── SKILL.md # Required
|
||||
├── scripts/ # Optional
|
||||
└── ...
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| Skill already exists | Target directory exists | Use `--force` to overwrite |
|
||||
| SKILL.md not found | Invalid skill package | Verify source contains SKILL.md |
|
||||
| Invalid archive | Corrupted or unsupported format | Check file integrity |
|
||||
| Network error | Download failed | Retry or check URL |
|
||||
|
||||
## Integration with Workflow Creator
|
||||
|
||||
When used with workflow-creator, download skills to workflow's `.claude/skills/` directory:
|
||||
|
||||
```bash
|
||||
# Create workflow first
|
||||
python /path/to/workflow-creator/scripts/create_workflow.py my-workflow --path ./workflows
|
||||
|
||||
# Then download skills
|
||||
python scripts/download_skill.py https://github.com/anthropics/skills/tree/main/skills/docx --output ./workflows/my-workflow/.claude/skills/
|
||||
```
|
||||
|
||||
## Skill Sources Reference
|
||||
|
||||
Popular skill repositories:
|
||||
- [Anthropic Official](https://github.com/anthropics/skills) - docx, pdf, pptx
|
||||
- [gked2121/claude-skills](https://github.com/gked2121/claude-skills) - social-repurposer, canvas-design
|
||||
- [ComposioHQ/awesome-claude-skills](https://github.com/ComposioHQ/awesome-claude-skills) - Collection
|
||||
- [MadAppGang/claude-code](https://github.com/MadAppGang/claude-code) - SEO, content skills
|
||||
- [daymade/claude-code-skills](https://github.com/daymade/claude-code-skills) - twitter-reader, fact-checker
|
||||
- [skillhub.club](https://www.skillhub.club) - 1000+ skills collection
|
||||
Executable
+254
@@ -0,0 +1,254 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Download and extract a skill from compressed archive.
|
||||
|
||||
Supported formats: .zip, .tar.gz, .tgz, .skill (renamed zip)
|
||||
|
||||
Usage:
|
||||
python download_from_archive.py <url-or-path> --output <output-dir>
|
||||
|
||||
Examples:
|
||||
python download_from_archive.py https://example.com/my-skill.zip --output ./.claude/skills/
|
||||
python download_from_archive.py ./downloads/my-skill.tar.gz --output ./.claude/skills/
|
||||
python download_from_archive.py https://skillhub.club/download/skill.skill --output ./.claude/skills/
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
|
||||
def is_url(source: str) -> bool:
|
||||
"""Check if source is a URL."""
|
||||
parsed = urlparse(source)
|
||||
return parsed.scheme in ('http', 'https')
|
||||
|
||||
|
||||
def get_archive_type(path: str) -> str:
|
||||
"""Determine archive type from path/extension."""
|
||||
path_lower = path.lower()
|
||||
|
||||
if path_lower.endswith('.zip') or path_lower.endswith('.skill'):
|
||||
return 'zip'
|
||||
elif path_lower.endswith('.tar.gz') or path_lower.endswith('.tgz'):
|
||||
return 'tar.gz'
|
||||
elif path_lower.endswith('.tar'):
|
||||
return 'tar'
|
||||
else:
|
||||
# Try to detect by content
|
||||
return 'unknown'
|
||||
|
||||
|
||||
def download_file(url: str, target_path: Path) -> None:
|
||||
"""Download file from URL."""
|
||||
print(f"📥 Downloading from {url}...")
|
||||
|
||||
# Create request with User-Agent
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
headers={'User-Agent': 'Mozilla/5.0 (skill-downloader)'}
|
||||
)
|
||||
|
||||
with urllib.request.urlopen(request, timeout=60) as response:
|
||||
with open(target_path, 'wb') as f:
|
||||
shutil.copyfileobj(response, f)
|
||||
|
||||
print(f" Downloaded to {target_path}")
|
||||
|
||||
|
||||
def extract_archive(archive_path: Path, extract_dir: Path, archive_type: str) -> Path:
|
||||
"""
|
||||
Extract archive and return path to skill directory.
|
||||
|
||||
Returns:
|
||||
Path to the extracted skill directory containing SKILL.md
|
||||
"""
|
||||
print(f"📦 Extracting {archive_type} archive...")
|
||||
|
||||
if archive_type == 'zip':
|
||||
with zipfile.ZipFile(archive_path, 'r') as zf:
|
||||
zf.extractall(extract_dir)
|
||||
elif archive_type in ('tar.gz', 'tar'):
|
||||
mode = 'r:gz' if archive_type == 'tar.gz' else 'r'
|
||||
with tarfile.open(archive_path, mode) as tf:
|
||||
tf.extractall(extract_dir)
|
||||
else:
|
||||
# Try zip first, then tar
|
||||
try:
|
||||
with zipfile.ZipFile(archive_path, 'r') as zf:
|
||||
zf.extractall(extract_dir)
|
||||
except zipfile.BadZipFile:
|
||||
try:
|
||||
with tarfile.open(archive_path, 'r:*') as tf:
|
||||
tf.extractall(extract_dir)
|
||||
except tarfile.TarError:
|
||||
raise ValueError("Unable to extract archive. Unsupported format.")
|
||||
|
||||
# Find SKILL.md in extracted content
|
||||
skill_md_path = find_skill_md(extract_dir)
|
||||
if not skill_md_path:
|
||||
raise FileNotFoundError("SKILL.md not found in archive")
|
||||
|
||||
return skill_md_path.parent
|
||||
|
||||
|
||||
def find_skill_md(directory: Path) -> Path | None:
|
||||
"""Recursively find SKILL.md in directory."""
|
||||
# Check current directory first
|
||||
skill_md = directory / "SKILL.md"
|
||||
if skill_md.exists():
|
||||
return skill_md
|
||||
|
||||
# Search subdirectories (max depth 3)
|
||||
for root, dirs, files in os.walk(directory):
|
||||
depth = len(Path(root).relative_to(directory).parts)
|
||||
if depth > 3:
|
||||
continue
|
||||
if "SKILL.md" in files:
|
||||
return Path(root) / "SKILL.md"
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def validate_skill_md(skill_md_path: Path) -> str:
|
||||
"""Validate SKILL.md and return skill name."""
|
||||
content = skill_md_path.read_text()
|
||||
|
||||
if not content.startswith('---'):
|
||||
raise ValueError("SKILL.md missing YAML frontmatter")
|
||||
|
||||
# Extract frontmatter
|
||||
parts = content.split('---', 2)
|
||||
if len(parts) < 3:
|
||||
raise ValueError("SKILL.md has invalid frontmatter format")
|
||||
|
||||
frontmatter = parts[1]
|
||||
|
||||
if 'name:' not in frontmatter:
|
||||
raise ValueError("SKILL.md missing required 'name' field")
|
||||
if 'description:' not in frontmatter:
|
||||
raise ValueError("SKILL.md missing required 'description' field")
|
||||
|
||||
# Extract name
|
||||
for line in frontmatter.split('\n'):
|
||||
if line.strip().startswith('name:'):
|
||||
name = line.split(':', 1)[1].strip().strip('"\'')
|
||||
return name
|
||||
|
||||
raise ValueError("Could not parse skill name from SKILL.md")
|
||||
|
||||
|
||||
def download_from_archive(
|
||||
source: str,
|
||||
output_dir: str,
|
||||
force: bool = False,
|
||||
skill_name: str | None = None
|
||||
) -> Path:
|
||||
"""
|
||||
Download and extract skill from archive.
|
||||
|
||||
Args:
|
||||
source: URL or local path to archive
|
||||
output_dir: Directory to install skill
|
||||
force: Overwrite if exists
|
||||
skill_name: Override skill name
|
||||
|
||||
Returns:
|
||||
Path to installed skill directory
|
||||
"""
|
||||
output_path = Path(output_dir)
|
||||
output_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
temp_path = Path(temp_dir)
|
||||
|
||||
# Get archive to local path
|
||||
if is_url(source):
|
||||
# Extract filename from URL
|
||||
url_path = urlparse(source).path
|
||||
filename = os.path.basename(url_path) or 'skill.zip'
|
||||
archive_path = temp_path / filename
|
||||
download_file(source, archive_path)
|
||||
else:
|
||||
archive_path = Path(source)
|
||||
if not archive_path.exists():
|
||||
raise FileNotFoundError(f"Archive not found: {source}")
|
||||
|
||||
# Determine archive type
|
||||
archive_type = get_archive_type(str(archive_path))
|
||||
|
||||
# Extract archive
|
||||
extract_dir = temp_path / "extracted"
|
||||
extract_dir.mkdir()
|
||||
skill_source = extract_archive(archive_path, extract_dir, archive_type)
|
||||
|
||||
# Validate and get skill name
|
||||
skill_md = skill_source / "SKILL.md"
|
||||
extracted_name = validate_skill_md(skill_md)
|
||||
final_name = skill_name or extracted_name
|
||||
|
||||
# Check if exists
|
||||
target_dir = output_path / final_name
|
||||
if target_dir.exists():
|
||||
if force:
|
||||
print(f"⚠️ Removing existing skill '{final_name}'...")
|
||||
shutil.rmtree(target_dir)
|
||||
else:
|
||||
print(f"⚠️ Skill '{final_name}' already exists at {target_dir}")
|
||||
print(" Use --force to overwrite")
|
||||
return target_dir
|
||||
|
||||
# Copy to output
|
||||
print(f"📦 Installing skill to {target_dir}...")
|
||||
shutil.copytree(skill_source, target_dir)
|
||||
|
||||
# Remove any .git directory
|
||||
git_dir = target_dir / ".git"
|
||||
if git_dir.exists():
|
||||
shutil.rmtree(git_dir)
|
||||
|
||||
print(f"✅ Installed skill '{final_name}' to {target_dir}")
|
||||
return target_dir
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Download and extract skill from archive"
|
||||
)
|
||||
parser.add_argument(
|
||||
"source",
|
||||
help="URL or local path to archive (.zip, .tar.gz, .skill)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output", "-o",
|
||||
default="./.claude/skills/",
|
||||
help="Output directory (default: ./.claude/skills/)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--force", "-f",
|
||||
action="store_true",
|
||||
help="Overwrite existing skill"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--name", "-n",
|
||||
help="Override skill name"
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
download_from_archive(args.source, args.output, args.force, args.name)
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+229
@@ -0,0 +1,229 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Download a skill from GitHub repository.
|
||||
|
||||
Usage:
|
||||
python download_from_github.py <repo-url> <skill-path> --output <output-dir>
|
||||
|
||||
Examples:
|
||||
python download_from_github.py https://github.com/anthropics/skills skills/docx --output ./.claude/skills/
|
||||
python download_from_github.py https://github.com/gked2121/claude-skills social-repurposer --output ./.claude/skills/
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def parse_github_url(url: str) -> tuple[str, str | None]:
|
||||
"""
|
||||
Parse GitHub URL and extract repo URL and optional path.
|
||||
|
||||
Handles:
|
||||
- https://github.com/user/repo
|
||||
- https://github.com/user/repo/tree/main/path/to/skill
|
||||
- github.com/user/repo
|
||||
|
||||
Returns:
|
||||
Tuple of (repo_url, skill_path or None)
|
||||
"""
|
||||
# Remove trailing slash
|
||||
url = url.rstrip('/')
|
||||
|
||||
# Add https if missing
|
||||
if not url.startswith('http'):
|
||||
url = 'https://' + url
|
||||
|
||||
# Match GitHub URL with optional path
|
||||
pattern = r'https://github\.com/([^/]+)/([^/]+)(?:/tree/[^/]+/(.+))?'
|
||||
match = re.match(pattern, url)
|
||||
|
||||
if match:
|
||||
user, repo, path = match.groups()
|
||||
repo_url = f'https://github.com/{user}/{repo}.git'
|
||||
return repo_url, path
|
||||
|
||||
# Simple repo URL
|
||||
if 'github.com' in url:
|
||||
if not url.endswith('.git'):
|
||||
url = url + '.git'
|
||||
return url, None
|
||||
|
||||
raise ValueError(f"Invalid GitHub URL: {url}")
|
||||
|
||||
|
||||
def download_skill(repo_url: str, skill_path: str, output_dir: str, force: bool = False) -> Path:
|
||||
"""
|
||||
Download a skill folder from a GitHub repository.
|
||||
|
||||
Args:
|
||||
repo_url: GitHub repository URL
|
||||
skill_path: Path to skill within repository
|
||||
output_dir: Local directory to save the skill
|
||||
force: Overwrite if exists
|
||||
|
||||
Returns:
|
||||
Path to the downloaded skill directory
|
||||
"""
|
||||
output_path = Path(output_dir)
|
||||
output_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Extract skill name from path
|
||||
skill_name = Path(skill_path).name
|
||||
|
||||
# Check if skill already exists
|
||||
target_dir = output_path / skill_name
|
||||
if target_dir.exists():
|
||||
if force:
|
||||
print(f"⚠️ Removing existing skill '{skill_name}'...")
|
||||
shutil.rmtree(target_dir)
|
||||
else:
|
||||
print(f"⚠️ Skill '{skill_name}' already exists at {target_dir}")
|
||||
print(" Use --force to overwrite")
|
||||
return target_dir
|
||||
|
||||
# Create temp directory
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
temp_path = Path(temp_dir)
|
||||
|
||||
# Clone repository with depth 1 for speed
|
||||
print(f"📥 Cloning {repo_url}...")
|
||||
try:
|
||||
subprocess.run(
|
||||
["git", "clone", "--depth", "1", "--filter=blob:none", "--sparse", repo_url, "repo"],
|
||||
cwd=temp_path,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True
|
||||
)
|
||||
except subprocess.CalledProcessError:
|
||||
# Fallback to full clone if sparse checkout fails
|
||||
print(" Sparse checkout not supported, using full clone...")
|
||||
subprocess.run(
|
||||
["git", "clone", "--depth", "1", repo_url, "repo"],
|
||||
cwd=temp_path,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True
|
||||
)
|
||||
|
||||
repo_path = temp_path / "repo"
|
||||
|
||||
# Try sparse checkout for efficiency
|
||||
try:
|
||||
subprocess.run(
|
||||
["git", "sparse-checkout", "set", skill_path],
|
||||
cwd=repo_path,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True
|
||||
)
|
||||
except subprocess.CalledProcessError:
|
||||
pass # Sparse checkout optional, continue with full clone
|
||||
|
||||
# Find the skill directory
|
||||
skill_source = repo_path / skill_path
|
||||
if not skill_source.exists():
|
||||
# Try alternative paths
|
||||
alternatives = [
|
||||
repo_path / skill_name,
|
||||
repo_path / f".claude/skills/{skill_name}",
|
||||
repo_path / f"skills/{skill_name}",
|
||||
]
|
||||
for alt in alternatives:
|
||||
if alt.exists():
|
||||
skill_source = alt
|
||||
break
|
||||
else:
|
||||
raise FileNotFoundError(
|
||||
f"Skill not found at {skill_path}\n"
|
||||
f"Tried: {skill_path}, {skill_name}, .claude/skills/{skill_name}, skills/{skill_name}"
|
||||
)
|
||||
|
||||
# Verify SKILL.md exists
|
||||
skill_md = skill_source / "SKILL.md"
|
||||
if not skill_md.exists():
|
||||
raise FileNotFoundError(f"SKILL.md not found in {skill_source}")
|
||||
|
||||
# Validate SKILL.md has required frontmatter
|
||||
validate_skill_md(skill_md)
|
||||
|
||||
# Copy skill to output directory
|
||||
print(f"📦 Copying skill to {target_dir}...")
|
||||
shutil.copytree(skill_source, target_dir)
|
||||
|
||||
# Remove .git if present
|
||||
git_dir = target_dir / ".git"
|
||||
if git_dir.exists():
|
||||
shutil.rmtree(git_dir)
|
||||
|
||||
print(f"✅ Downloaded skill '{skill_name}' to {target_dir}")
|
||||
return target_dir
|
||||
|
||||
|
||||
def validate_skill_md(skill_md_path: Path) -> None:
|
||||
"""Validate SKILL.md has required YAML frontmatter."""
|
||||
content = skill_md_path.read_text()
|
||||
|
||||
if not content.startswith('---'):
|
||||
raise ValueError("SKILL.md missing YAML frontmatter (must start with ---)")
|
||||
|
||||
# Extract frontmatter
|
||||
parts = content.split('---', 2)
|
||||
if len(parts) < 3:
|
||||
raise ValueError("SKILL.md has invalid frontmatter format")
|
||||
|
||||
frontmatter = parts[1]
|
||||
|
||||
if 'name:' not in frontmatter:
|
||||
raise ValueError("SKILL.md missing required 'name' field")
|
||||
if 'description:' not in frontmatter:
|
||||
raise ValueError("SKILL.md missing required 'description' field")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Download a skill from GitHub repository"
|
||||
)
|
||||
parser.add_argument(
|
||||
"repo_url",
|
||||
help="GitHub repository URL"
|
||||
)
|
||||
parser.add_argument(
|
||||
"skill_path",
|
||||
help="Path to skill within repository (e.g., 'skills/docx')"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output", "-o",
|
||||
default="./.claude/skills/",
|
||||
help="Output directory (default: ./.claude/skills/)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--force", "-f",
|
||||
action="store_true",
|
||||
help="Overwrite existing skill"
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
# Parse URL to get clean repo URL
|
||||
repo_url, url_path = parse_github_url(args.repo_url)
|
||||
|
||||
# Use path from URL if skill_path not explicitly provided
|
||||
skill_path = args.skill_path
|
||||
if url_path and args.skill_path == '.':
|
||||
skill_path = url_path
|
||||
|
||||
download_skill(repo_url, skill_path, args.output, args.force)
|
||||
except Exception as e:
|
||||
print(f"❌ Error downloading skill: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Unified skill downloader - auto-detects source type.
|
||||
|
||||
Supports:
|
||||
- GitHub repositories (full URL or tree URL)
|
||||
- Compressed archives (.zip, .tar.gz, .tgz, .skill)
|
||||
- Direct URLs to archives
|
||||
- Local archive files
|
||||
|
||||
Usage:
|
||||
python download_skill.py <source> [skill-path] --output <output-dir>
|
||||
|
||||
Examples:
|
||||
# GitHub (auto-detect)
|
||||
python download_skill.py https://github.com/anthropics/skills skills/docx --output ./.claude/skills/
|
||||
python download_skill.py https://github.com/anthropics/skills/tree/main/skills/docx --output ./.claude/skills/
|
||||
|
||||
# Archive (auto-detect)
|
||||
python download_skill.py https://example.com/my-skill.zip --output ./.claude/skills/
|
||||
python download_skill.py ./downloads/my-skill.tar.gz --output ./.claude/skills/
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
# Import the specialized downloaders
|
||||
from download_from_github import download_skill as download_github, parse_github_url
|
||||
from download_from_archive import download_from_archive, is_url, get_archive_type
|
||||
|
||||
|
||||
def detect_source_type(source: str) -> str:
|
||||
"""
|
||||
Detect the type of source.
|
||||
|
||||
Returns:
|
||||
'github', 'archive', 'local_archive', or 'unknown'
|
||||
"""
|
||||
# Check for GitHub URL
|
||||
if 'github.com' in source.lower():
|
||||
return 'github'
|
||||
|
||||
# Check for archive URL
|
||||
if is_url(source):
|
||||
path = urlparse(source).path.lower()
|
||||
if any(path.endswith(ext) for ext in ['.zip', '.tar.gz', '.tgz', '.tar', '.skill']):
|
||||
return 'archive'
|
||||
# Might still be an archive with no extension
|
||||
return 'archive'
|
||||
|
||||
# Check for local file
|
||||
source_path = Path(source)
|
||||
if source_path.exists():
|
||||
if source_path.is_file():
|
||||
return 'local_archive'
|
||||
elif source_path.is_dir():
|
||||
return 'local_dir'
|
||||
|
||||
return 'unknown'
|
||||
|
||||
|
||||
def download_skill(
|
||||
source: str,
|
||||
skill_path: str | None = None,
|
||||
output_dir: str = "./.claude/skills/",
|
||||
force: bool = False
|
||||
) -> Path:
|
||||
"""
|
||||
Download skill from any supported source.
|
||||
|
||||
Args:
|
||||
source: GitHub URL, archive URL, or local path
|
||||
skill_path: Path within repo (for GitHub sources)
|
||||
output_dir: Directory to install skill
|
||||
force: Overwrite if exists
|
||||
|
||||
Returns:
|
||||
Path to installed skill directory
|
||||
"""
|
||||
source_type = detect_source_type(source)
|
||||
|
||||
if source_type == 'github':
|
||||
# Parse GitHub URL
|
||||
repo_url, url_path = parse_github_url(source)
|
||||
|
||||
# Determine skill path
|
||||
if url_path:
|
||||
# URL contains path (e.g., .../tree/main/skills/docx)
|
||||
final_path = url_path
|
||||
elif skill_path:
|
||||
final_path = skill_path
|
||||
else:
|
||||
raise ValueError(
|
||||
"For GitHub repositories, provide either:\n"
|
||||
"1. Full tree URL: https://github.com/user/repo/tree/main/path/to/skill\n"
|
||||
"2. Skill path argument: download_skill.py <repo-url> <skill-path>"
|
||||
)
|
||||
|
||||
return download_github(repo_url, final_path, output_dir, force)
|
||||
|
||||
elif source_type in ('archive', 'local_archive'):
|
||||
return download_from_archive(source, output_dir, force)
|
||||
|
||||
elif source_type == 'local_dir':
|
||||
# Copy local directory
|
||||
import shutil
|
||||
|
||||
source_path = Path(source)
|
||||
skill_md = source_path / "SKILL.md"
|
||||
|
||||
if not skill_md.exists():
|
||||
raise FileNotFoundError(f"SKILL.md not found in {source_path}")
|
||||
|
||||
# Read skill name
|
||||
content = skill_md.read_text()
|
||||
name = None
|
||||
if content.startswith('---'):
|
||||
for line in content.split('---')[1].split('\n'):
|
||||
if line.strip().startswith('name:'):
|
||||
name = line.split(':', 1)[1].strip().strip('"\'')
|
||||
break
|
||||
|
||||
if not name:
|
||||
name = source_path.name
|
||||
|
||||
output_path = Path(output_dir)
|
||||
output_path.mkdir(parents=True, exist_ok=True)
|
||||
target_dir = output_path / name
|
||||
|
||||
if target_dir.exists():
|
||||
if force:
|
||||
shutil.rmtree(target_dir)
|
||||
else:
|
||||
print(f"⚠️ Skill '{name}' already exists at {target_dir}")
|
||||
return target_dir
|
||||
|
||||
shutil.copytree(source_path, target_dir)
|
||||
print(f"✅ Copied skill '{name}' to {target_dir}")
|
||||
return target_dir
|
||||
|
||||
else:
|
||||
raise ValueError(
|
||||
f"Unable to determine source type for: {source}\n"
|
||||
"Supported: GitHub URLs, archive URLs/files (.zip, .tar.gz, .skill)"
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Download skill from GitHub, archive, or URL (auto-detect)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"source",
|
||||
help="GitHub URL, archive URL, or local path"
|
||||
)
|
||||
parser.add_argument(
|
||||
"skill_path",
|
||||
nargs="?",
|
||||
default=None,
|
||||
help="Path to skill within repository (for GitHub sources)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output", "-o",
|
||||
default="./.claude/skills/",
|
||||
help="Output directory (default: ./.claude/skills/)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--force", "-f",
|
||||
action="store_true",
|
||||
help="Overwrite existing skill"
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
download_skill(args.source, args.skill_path, args.output, args.force)
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,474 @@
|
||||
# Advanced Patterns & Edge Cases
|
||||
|
||||
Handling special scenarios, migrations, and team collaboration.
|
||||
|
||||
## Table of Contents
|
||||
- [Local Configuration](#local-configuration)
|
||||
- [File Ignoring](#file-ignoring)
|
||||
- [Permissions](#permissions)
|
||||
- [Migration Strategies](#migration-strategies)
|
||||
- [Team Collaboration](#team-collaboration)
|
||||
- [Monorepo Patterns](#monorepo-patterns)
|
||||
- [Sensitive Files](#sensitive-files)
|
||||
|
||||
---
|
||||
|
||||
## Local Configuration
|
||||
|
||||
### CLAUDE.local.md
|
||||
|
||||
Personal preferences not shared with team. Place at project root.
|
||||
|
||||
**Use cases:**
|
||||
- Personal shortcuts and aliases
|
||||
- Local environment specifics
|
||||
- Individual workflow preferences
|
||||
- Experimental settings
|
||||
|
||||
**Example:**
|
||||
```markdown
|
||||
# My Local Preferences
|
||||
|
||||
## Shortcuts
|
||||
- I prefer verbose error messages
|
||||
- Always show full stack traces
|
||||
- Use my preferred test runner flags: --watch --coverage
|
||||
|
||||
## Environment
|
||||
- My local DB is on port 5433 (not 5432)
|
||||
- Use localhost instead of Docker for services
|
||||
|
||||
## Personal Style
|
||||
- I like detailed comments explaining "why"
|
||||
- Prefer longer variable names for clarity
|
||||
```
|
||||
|
||||
**Git configuration:**
|
||||
```gitignore
|
||||
# .gitignore
|
||||
CLAUDE.local.md
|
||||
```
|
||||
|
||||
### When to Use CLAUDE.local.md
|
||||
|
||||
| Scenario | Use CLAUDE.md | Use CLAUDE.local.md |
|
||||
|----------|---------------|---------------------|
|
||||
| Coding standards | ✓ | |
|
||||
| Build commands | ✓ | |
|
||||
| Personal shortcuts | | ✓ |
|
||||
| Local port overrides | | ✓ |
|
||||
| Experimental features | | ✓ |
|
||||
|
||||
---
|
||||
|
||||
## File Ignoring
|
||||
|
||||
### .claudeignore
|
||||
|
||||
Control which files Claude should not read or modify.
|
||||
|
||||
**Location:** Project root (`.claudeignore`)
|
||||
|
||||
**Syntax:** Same as .gitignore
|
||||
|
||||
**Common patterns:**
|
||||
```gitignore
|
||||
# Secrets and credentials
|
||||
.env
|
||||
.env.*
|
||||
*.pem
|
||||
*.key
|
||||
credentials.json
|
||||
secrets/
|
||||
|
||||
# Large generated files
|
||||
dist/
|
||||
build/
|
||||
node_modules/
|
||||
*.min.js
|
||||
*.bundle.js
|
||||
|
||||
# Binary files
|
||||
*.png
|
||||
*.jpg
|
||||
*.pdf
|
||||
*.zip
|
||||
|
||||
# Sensitive data
|
||||
**/data/production/
|
||||
**/backups/
|
||||
*.sql.gz
|
||||
|
||||
# Vendor code (don't modify)
|
||||
vendor/
|
||||
third_party/
|
||||
```
|
||||
|
||||
### Auto-generating .claudeignore
|
||||
|
||||
Based on .gitignore analysis:
|
||||
|
||||
```python
|
||||
# Patterns to always include in .claudeignore
|
||||
ALWAYS_IGNORE = [
|
||||
"# Secrets",
|
||||
".env",
|
||||
".env.*",
|
||||
"*.pem",
|
||||
"*.key",
|
||||
"credentials*.json",
|
||||
"secrets/",
|
||||
"",
|
||||
"# Large/Binary",
|
||||
"*.min.js",
|
||||
"*.bundle.js",
|
||||
"*.map",
|
||||
"",
|
||||
"# Data",
|
||||
"*.sql",
|
||||
"*.db",
|
||||
"*.sqlite",
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Permissions
|
||||
|
||||
### .claude/settings.json permissions
|
||||
|
||||
Control what tools Claude can use:
|
||||
|
||||
```json
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Read",
|
||||
"Edit",
|
||||
"Write",
|
||||
"Bash(npm:*)",
|
||||
"Bash(git:*)",
|
||||
"Bash(pnpm:*)"
|
||||
],
|
||||
"deny": [
|
||||
"Bash(rm -rf:*)",
|
||||
"Bash(sudo:*)",
|
||||
"Bash(curl|wget:*)"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Permission patterns
|
||||
|
||||
| Pattern | Meaning |
|
||||
|---------|---------|
|
||||
| `Bash(npm:*)` | Allow npm commands |
|
||||
| `Bash(git add:*)` | Allow git add only |
|
||||
| `mcp__github` | Allow all GitHub MCP tools |
|
||||
| `mcp__postgres__query` | Allow only query, not execute |
|
||||
|
||||
### Recommended defaults
|
||||
|
||||
```json
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Read",
|
||||
"Glob",
|
||||
"Grep",
|
||||
"Bash(npm:*)",
|
||||
"Bash(pnpm:*)",
|
||||
"Bash(yarn:*)",
|
||||
"Bash(git:*)",
|
||||
"Bash(python:*)",
|
||||
"Bash(pytest:*)",
|
||||
"Edit",
|
||||
"Write"
|
||||
],
|
||||
"deny": [
|
||||
"Bash(rm -rf /*:*)",
|
||||
"Bash(sudo:*)",
|
||||
"Bash(*--force*:*)"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Migration Strategies
|
||||
|
||||
### Scenario 1: No existing configuration
|
||||
|
||||
Standard workflow applies. Create from scratch.
|
||||
|
||||
### Scenario 2: Has README but no CLAUDE.md
|
||||
|
||||
1. **Extract from README:**
|
||||
- Build/test commands
|
||||
- Setup instructions
|
||||
- Architecture overview
|
||||
|
||||
2. **Convert to CLAUDE.md format:**
|
||||
- Keep README for humans
|
||||
- CLAUDE.md for AI-specific instructions
|
||||
|
||||
### Scenario 3: Has basic CLAUDE.md
|
||||
|
||||
1. **Audit existing content:**
|
||||
- Check if follows best practices
|
||||
- Identify gaps
|
||||
|
||||
2. **Enhance incrementally:**
|
||||
- Add missing sections
|
||||
- Don't remove working content
|
||||
- Add rules/skills as needed
|
||||
|
||||
### Scenario 4: Has complete .claude/ setup
|
||||
|
||||
1. **Validate structure:**
|
||||
- Check skill formats
|
||||
- Verify agent configurations
|
||||
- Test commands
|
||||
|
||||
2. **Update patterns:**
|
||||
- Align with latest best practices
|
||||
- Add new features (MCP, hooks)
|
||||
|
||||
### Migration checklist
|
||||
|
||||
```markdown
|
||||
## Migration Audit
|
||||
|
||||
### Current State
|
||||
- [ ] Has CLAUDE.md?
|
||||
- [ ] Has .claude/ directory?
|
||||
- [ ] Has rules files?
|
||||
- [ ] Has skills?
|
||||
- [ ] Has agents?
|
||||
- [ ] Has commands?
|
||||
- [ ] Has hooks configured?
|
||||
|
||||
### Quality Check
|
||||
- [ ] CLAUDE.md < 500 lines?
|
||||
- [ ] Skills have proper frontmatter?
|
||||
- [ ] Commands have descriptions?
|
||||
- [ ] No sensitive data exposed?
|
||||
|
||||
### Gaps to Fill
|
||||
- [ ] Missing: ___
|
||||
- [ ] Outdated: ___
|
||||
- [ ] Needs improvement: ___
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Team Collaboration
|
||||
|
||||
### Git workflow for .claude/
|
||||
|
||||
**What to commit:**
|
||||
```
|
||||
CLAUDE.md ✓ Commit
|
||||
.claude/rules/ ✓ Commit
|
||||
.claude/skills/ ✓ Commit
|
||||
.claude/agents/ ✓ Commit
|
||||
.claude/commands/ ✓ Commit
|
||||
.claude/settings.json ✓ Commit (without secrets)
|
||||
```
|
||||
|
||||
**What to ignore:**
|
||||
```gitignore
|
||||
CLAUDE.local.md
|
||||
.claude/settings.local.json
|
||||
```
|
||||
|
||||
### Code review for AI configs
|
||||
|
||||
When reviewing .claude/ changes:
|
||||
|
||||
1. **CLAUDE.md changes:**
|
||||
- Does it accurately reflect current practices?
|
||||
- Is it concise enough?
|
||||
- Any outdated information?
|
||||
|
||||
2. **Skill changes:**
|
||||
- Is the description clear?
|
||||
- Does it follow skill patterns?
|
||||
- Is it tested?
|
||||
|
||||
3. **Command changes:**
|
||||
- Is it useful for the team?
|
||||
- Does it have proper permissions?
|
||||
|
||||
### Ownership model
|
||||
|
||||
```markdown
|
||||
## Config Ownership
|
||||
|
||||
| Config | Owner | Review Required |
|
||||
|--------|-------|-----------------|
|
||||
| CLAUDE.md | Tech Lead | Yes |
|
||||
| rules/*.md | Module Owner | Yes |
|
||||
| skills/* | Skill Author | Yes |
|
||||
| commands/* | Any | Lightweight |
|
||||
| settings.json | DevOps | Yes |
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Monorepo Patterns
|
||||
|
||||
### Structure
|
||||
|
||||
```
|
||||
monorepo/
|
||||
├── CLAUDE.md # Root: shared conventions
|
||||
├── .claude/
|
||||
│ ├── rules/
|
||||
│ │ └── shared.md # Shared rules
|
||||
│ └── skills/
|
||||
│ └── monorepo-nav/ # Navigation helper
|
||||
├── packages/
|
||||
│ ├── frontend/
|
||||
│ │ ├── CLAUDE.md # Package-specific
|
||||
│ │ └── .claude/rules/
|
||||
│ ├── backend/
|
||||
│ │ ├── CLAUDE.md
|
||||
│ │ └── .claude/rules/
|
||||
│ └── shared/
|
||||
│ └── CLAUDE.md
|
||||
└── apps/
|
||||
└── web/
|
||||
└── CLAUDE.md
|
||||
```
|
||||
|
||||
### Root CLAUDE.md
|
||||
|
||||
```markdown
|
||||
# Monorepo
|
||||
|
||||
## Structure
|
||||
- `packages/` - Shared libraries
|
||||
- `apps/` - Applications
|
||||
- `tools/` - Build tools
|
||||
|
||||
## Commands
|
||||
- `pnpm install` - Install all deps
|
||||
- `pnpm build` - Build all packages
|
||||
- `pnpm test` - Test all packages
|
||||
|
||||
## Working in packages
|
||||
Each package has its own CLAUDE.md with specific conventions.
|
||||
Navigate to package directory for package-specific context.
|
||||
|
||||
## Cross-package changes
|
||||
When modifying shared packages, check dependents:
|
||||
\`\`\`bash
|
||||
pnpm why [package-name]
|
||||
\`\`\`
|
||||
```
|
||||
|
||||
### Package-specific CLAUDE.md
|
||||
|
||||
```markdown
|
||||
# Frontend Package
|
||||
|
||||
## This Package
|
||||
React component library for the design system.
|
||||
|
||||
## Local Commands
|
||||
- `pnpm dev` - Storybook
|
||||
- `pnpm test` - Jest tests
|
||||
- `pnpm build` - Build library
|
||||
|
||||
## Dependencies
|
||||
- Uses: `@repo/shared`, `@repo/types`
|
||||
- Used by: `apps/web`, `apps/mobile`
|
||||
|
||||
## Conventions
|
||||
[Package-specific patterns]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Sensitive Files
|
||||
|
||||
### Detection patterns
|
||||
|
||||
Files to protect:
|
||||
|
||||
```python
|
||||
SENSITIVE_PATTERNS = [
|
||||
# Environment
|
||||
".env", ".env.*",
|
||||
|
||||
# Keys and certs
|
||||
"*.pem", "*.key", "*.crt", "*.p12",
|
||||
"*.keystore", "*.jks",
|
||||
|
||||
# Credentials
|
||||
"credentials*.json",
|
||||
"service-account*.json",
|
||||
"*secret*",
|
||||
"*password*",
|
||||
|
||||
# Cloud configs
|
||||
".aws/", ".gcp/", ".azure/",
|
||||
"kubeconfig*",
|
||||
|
||||
# Database
|
||||
"*.sql", "*.dump",
|
||||
"database.yml",
|
||||
|
||||
# IDE with potential secrets
|
||||
".idea/", ".vscode/settings.json",
|
||||
]
|
||||
```
|
||||
|
||||
### Protection strategies
|
||||
|
||||
1. **Add to .claudeignore:**
|
||||
```gitignore
|
||||
.env*
|
||||
*.pem
|
||||
credentials*.json
|
||||
```
|
||||
|
||||
2. **Configure hooks to block:**
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [{
|
||||
"matcher": "Edit|Write|Read",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": "python -c \"import sys,json; p=json.load(sys.stdin).get('tool_input',{}).get('file_path',''); sys.exit(2 if any(x in p for x in ['.env','.pem','secret','credential']) else 0)\""
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
3. **Document in CLAUDE.md:**
|
||||
```markdown
|
||||
## Security
|
||||
NEVER read or modify:
|
||||
- .env files
|
||||
- Any file with 'secret' or 'credential' in name
|
||||
- *.pem, *.key files
|
||||
```
|
||||
|
||||
### Audit command
|
||||
|
||||
```bash
|
||||
# Find potentially sensitive files
|
||||
find . -type f \( \
|
||||
-name "*.env*" -o \
|
||||
-name "*.pem" -o \
|
||||
-name "*.key" -o \
|
||||
-name "*secret*" -o \
|
||||
-name "*credential*" \
|
||||
\) -not -path "./node_modules/*" -not -path "./.git/*"
|
||||
```
|
||||
@@ -0,0 +1,270 @@
|
||||
# Subagents Design Patterns Reference
|
||||
|
||||
## Purpose
|
||||
|
||||
Subagents are specialized AI assistants that handle specific task types. Create subagents when:
|
||||
- Tasks need isolation from main conversation context
|
||||
- Specific tool restrictions are needed
|
||||
- Specialized system prompts improve performance
|
||||
|
||||
## Subagent Structure
|
||||
|
||||
```
|
||||
.claude/agents/
|
||||
├── code-reviewer.md
|
||||
├── debugger.md
|
||||
├── test-runner.md
|
||||
└── security-auditor.md
|
||||
```
|
||||
|
||||
## Subagent Template
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: agent-name
|
||||
description: What this agent does. Use proactively when [trigger conditions].
|
||||
tools: Read, Grep, Glob, Bash
|
||||
model: sonnet
|
||||
---
|
||||
|
||||
You are a [role description].
|
||||
|
||||
When invoked:
|
||||
1. [First action]
|
||||
2. [Second action]
|
||||
3. [Third action]
|
||||
|
||||
## Guidelines
|
||||
- [Guideline 1]
|
||||
- [Guideline 2]
|
||||
|
||||
## Output Format
|
||||
[Expected output structure]
|
||||
```
|
||||
|
||||
## Frontmatter Options
|
||||
|
||||
| Field | Required | Description |
|
||||
|-------|----------|-------------|
|
||||
| `name` | Yes | Unique identifier (lowercase, hyphens) |
|
||||
| `description` | Yes | When Claude should delegate to this agent |
|
||||
| `tools` | No | Tool restrictions (defaults to all) |
|
||||
| `model` | No | `sonnet`, `opus`, `haiku`, or `inherit` |
|
||||
| `permissionMode` | No | `default`, `acceptEdits`, `plan`, etc. |
|
||||
| `skills` | No | Skills to load into agent context |
|
||||
|
||||
## Common Project Subagents
|
||||
|
||||
### Code Reviewer
|
||||
```markdown
|
||||
---
|
||||
name: code-reviewer
|
||||
description: Expert code reviewer. Use proactively after code changes to review for quality, security, and maintainability.
|
||||
tools: Read, Grep, Glob, Bash
|
||||
model: sonnet
|
||||
---
|
||||
|
||||
You are a senior code reviewer ensuring code quality.
|
||||
|
||||
When invoked:
|
||||
1. Run `git diff` to see recent changes
|
||||
2. Analyze modified files
|
||||
3. Provide structured feedback
|
||||
|
||||
## Review Checklist
|
||||
- Code clarity and readability
|
||||
- Proper error handling
|
||||
- Security vulnerabilities
|
||||
- Test coverage
|
||||
- Performance concerns
|
||||
|
||||
## Output Format
|
||||
### Critical Issues (must fix)
|
||||
- [Issue description]
|
||||
|
||||
### Warnings (should fix)
|
||||
- [Issue description]
|
||||
|
||||
### Suggestions (consider)
|
||||
- [Improvement idea]
|
||||
```
|
||||
|
||||
### Debugger
|
||||
```markdown
|
||||
---
|
||||
name: debugger
|
||||
description: Debugging specialist. Use when encountering errors, test failures, or unexpected behavior.
|
||||
tools: Read, Edit, Bash, Grep, Glob
|
||||
model: sonnet
|
||||
---
|
||||
|
||||
You are an expert debugger.
|
||||
|
||||
When invoked:
|
||||
1. Capture error message and stack trace
|
||||
2. Identify reproduction steps
|
||||
3. Isolate failure location
|
||||
4. Implement minimal fix
|
||||
5. Verify solution
|
||||
|
||||
## Debugging Process
|
||||
- Analyze error messages
|
||||
- Check recent code changes
|
||||
- Form and test hypotheses
|
||||
- Add strategic logging
|
||||
- Inspect variable states
|
||||
|
||||
## Output Format
|
||||
### Root Cause
|
||||
[Explanation]
|
||||
|
||||
### Evidence
|
||||
[Supporting details]
|
||||
|
||||
### Fix
|
||||
[Code changes]
|
||||
|
||||
### Prevention
|
||||
[How to avoid in future]
|
||||
```
|
||||
|
||||
### Test Runner
|
||||
```markdown
|
||||
---
|
||||
name: test-runner
|
||||
description: Test execution and analysis. Use proactively after code changes to run tests and fix failures.
|
||||
tools: Read, Edit, Bash, Grep, Glob
|
||||
model: sonnet
|
||||
---
|
||||
|
||||
You are a testing specialist.
|
||||
|
||||
When invoked:
|
||||
1. Run relevant test suite
|
||||
2. Analyze failures
|
||||
3. Fix failing tests or code
|
||||
4. Verify fixes pass
|
||||
|
||||
## Test Commands
|
||||
- Unit tests: `npm test`
|
||||
- Integration: `npm run test:integration`
|
||||
- E2E: `npm run test:e2e`
|
||||
|
||||
## Failure Analysis
|
||||
- Check assertion messages
|
||||
- Review test setup/teardown
|
||||
- Verify test data
|
||||
- Check for race conditions
|
||||
```
|
||||
|
||||
### Security Auditor
|
||||
```markdown
|
||||
---
|
||||
name: security-auditor
|
||||
description: Security review specialist. Use when reviewing authentication, authorization, or handling sensitive data.
|
||||
tools: Read, Grep, Glob
|
||||
model: sonnet
|
||||
permissionMode: plan
|
||||
---
|
||||
|
||||
You are a security expert conducting code audits.
|
||||
|
||||
When invoked:
|
||||
1. Identify security-sensitive code
|
||||
2. Check for common vulnerabilities
|
||||
3. Review authentication/authorization
|
||||
4. Report findings
|
||||
|
||||
## Security Checklist
|
||||
- Input validation
|
||||
- SQL injection prevention
|
||||
- XSS prevention
|
||||
- CSRF protection
|
||||
- Authentication bypasses
|
||||
- Secrets exposure
|
||||
- Dependency vulnerabilities
|
||||
|
||||
## Output Format
|
||||
### Critical Vulnerabilities
|
||||
- [Vulnerability with risk level]
|
||||
|
||||
### Security Warnings
|
||||
- [Potential issue]
|
||||
|
||||
### Recommendations
|
||||
- [Improvement suggestion]
|
||||
```
|
||||
|
||||
### Documentation Writer
|
||||
```markdown
|
||||
---
|
||||
name: doc-writer
|
||||
description: Documentation specialist. Use when creating or updating documentation, API docs, or README files.
|
||||
tools: Read, Write, Grep, Glob
|
||||
model: sonnet
|
||||
---
|
||||
|
||||
You are a technical documentation expert.
|
||||
|
||||
When invoked:
|
||||
1. Understand the code/feature
|
||||
2. Identify target audience
|
||||
3. Create clear documentation
|
||||
4. Include examples
|
||||
|
||||
## Documentation Standards
|
||||
- Start with overview/purpose
|
||||
- Include usage examples
|
||||
- Document parameters/options
|
||||
- Add troubleshooting section
|
||||
|
||||
## Style Guide
|
||||
- Active voice
|
||||
- Present tense
|
||||
- Concise sentences
|
||||
- Code examples for all features
|
||||
```
|
||||
|
||||
## Extraction Patterns
|
||||
|
||||
When analyzing legacy code for subagents:
|
||||
|
||||
1. **Identify repetitive review tasks**
|
||||
- Code review patterns
|
||||
- Security checking procedures
|
||||
- Performance analysis steps
|
||||
|
||||
2. **Find specialized expertise needs**
|
||||
- Database optimization
|
||||
- API design review
|
||||
- Frontend accessibility
|
||||
|
||||
3. **Document debugging workflows**
|
||||
- Error investigation steps
|
||||
- Log analysis procedures
|
||||
- Performance profiling
|
||||
|
||||
4. **Map tool restrictions**
|
||||
- Read-only tasks → limit to Read, Grep, Glob
|
||||
- Modification tasks → include Edit, Write
|
||||
- Execution tasks → include Bash
|
||||
|
||||
## Tool Combinations
|
||||
|
||||
| Agent Type | Recommended Tools |
|
||||
|------------|-------------------|
|
||||
| Reviewer | Read, Grep, Glob, Bash |
|
||||
| Debugger | Read, Edit, Bash, Grep, Glob |
|
||||
| Security | Read, Grep, Glob (read-only) |
|
||||
| Documentation | Read, Write, Grep, Glob |
|
||||
| Test Runner | Read, Edit, Bash, Grep, Glob |
|
||||
| Refactoring | Read, Edit, Grep, Glob |
|
||||
|
||||
## Permission Modes
|
||||
|
||||
| Mode | Use Case |
|
||||
|------|----------|
|
||||
| `default` | Standard permission checking |
|
||||
| `acceptEdits` | Auto-accept file changes |
|
||||
| `plan` | Read-only exploration |
|
||||
| `dontAsk` | Auto-deny unknown permissions |
|
||||
@@ -0,0 +1,183 @@
|
||||
# CLAUDE.md Patterns Reference
|
||||
|
||||
## Purpose
|
||||
|
||||
CLAUDE.md is the project memory file loaded into every Claude Code conversation. It should contain:
|
||||
- Project-wide coding standards and conventions
|
||||
- Common commands and workflows
|
||||
- Architecture decisions and patterns
|
||||
- Team-specific knowledge
|
||||
|
||||
## Structure Template
|
||||
|
||||
```markdown
|
||||
# [Project Name]
|
||||
|
||||
## Quick Reference
|
||||
- Build: `[build command]`
|
||||
- Test: `[test command]`
|
||||
- Lint: `[lint command]`
|
||||
- Deploy: `[deploy command]`
|
||||
|
||||
## Code Style
|
||||
|
||||
### Naming Conventions
|
||||
- [Convention rules]
|
||||
|
||||
### File Organization
|
||||
- [Directory structure conventions]
|
||||
|
||||
### Import Order
|
||||
- [Import ordering rules]
|
||||
|
||||
## Architecture
|
||||
|
||||
### Core Patterns
|
||||
- [Key architectural patterns used]
|
||||
|
||||
### Data Flow
|
||||
- [How data moves through the system]
|
||||
|
||||
### Error Handling
|
||||
- [Error handling conventions]
|
||||
|
||||
## Testing
|
||||
|
||||
### Test Organization
|
||||
- [How tests are structured]
|
||||
|
||||
### Testing Patterns
|
||||
- [Common testing patterns]
|
||||
|
||||
## Git Workflow
|
||||
- Branch naming: `[pattern]`
|
||||
- Commit format: `[format]`
|
||||
- PR requirements: `[requirements]`
|
||||
|
||||
## Environment
|
||||
- Required env vars: `[list]`
|
||||
- Local setup: `[steps]`
|
||||
```
|
||||
|
||||
## Content Guidelines
|
||||
|
||||
### What to Include
|
||||
1. **Frequently used commands** - Build, test, lint, deploy
|
||||
2. **Coding conventions** - Naming, formatting, imports
|
||||
3. **Architecture patterns** - Domain boundaries, data flow
|
||||
4. **Git workflow** - Branch naming, commit format
|
||||
5. **Environment setup** - Required variables, local config
|
||||
|
||||
### What to Avoid
|
||||
1. Generic advice Claude already knows
|
||||
2. Verbose explanations (prefer examples)
|
||||
3. Information that changes frequently
|
||||
4. Sensitive data or secrets
|
||||
|
||||
## Language-Specific Patterns
|
||||
|
||||
### TypeScript/JavaScript Projects
|
||||
```markdown
|
||||
## Code Style
|
||||
- Use TypeScript strict mode
|
||||
- Prefer `const` over `let`
|
||||
- Use named exports, avoid default exports
|
||||
- Imports: external → internal → relative
|
||||
|
||||
## Patterns
|
||||
- Use Zod for runtime validation
|
||||
- Prefer composition over inheritance
|
||||
- Use Result types for error handling
|
||||
```
|
||||
|
||||
### Python Projects
|
||||
```markdown
|
||||
## Code Style
|
||||
- Follow PEP 8
|
||||
- Use type hints for all public functions
|
||||
- Docstrings: Google style
|
||||
- Imports: stdlib → third-party → local
|
||||
|
||||
## Patterns
|
||||
- Use dataclasses for data containers
|
||||
- Prefer Protocol over ABC for interfaces
|
||||
- Use contextmanager for resource management
|
||||
```
|
||||
|
||||
### Go Projects
|
||||
```markdown
|
||||
## Code Style
|
||||
- Run `gofmt` before commit
|
||||
- Error handling: wrap with context
|
||||
- Package naming: singular, lowercase
|
||||
|
||||
## Patterns
|
||||
- Use interfaces at consumption point
|
||||
- Prefer composition over embedding
|
||||
- Context propagation for cancellation
|
||||
```
|
||||
|
||||
## Imports in CLAUDE.md
|
||||
|
||||
Use `@path/to/file` to import additional files:
|
||||
|
||||
```markdown
|
||||
# Project Memory
|
||||
|
||||
## Core Guidelines
|
||||
@docs/coding-standards.md
|
||||
@docs/architecture.md
|
||||
|
||||
## API Reference
|
||||
@docs/api/README.md
|
||||
```
|
||||
|
||||
## Rules Directory Alternative
|
||||
|
||||
For larger projects, use `.claude/rules/` for modular organization:
|
||||
|
||||
```
|
||||
.claude/rules/
|
||||
├── code-style.md # Coding conventions
|
||||
├── testing.md # Test guidelines
|
||||
├── api-design.md # API patterns
|
||||
└── security.md # Security requirements
|
||||
```
|
||||
|
||||
Each rule file can have path-specific scope:
|
||||
|
||||
```yaml
|
||||
---
|
||||
paths:
|
||||
- "src/api/**/*.ts"
|
||||
---
|
||||
# API Rules
|
||||
- All endpoints must validate input
|
||||
- Use standard error response format
|
||||
```
|
||||
|
||||
## Extraction Patterns
|
||||
|
||||
When analyzing a legacy codebase, extract:
|
||||
|
||||
1. **From package.json/pyproject.toml/go.mod**
|
||||
- Build/test commands
|
||||
- Dependencies and their purposes
|
||||
|
||||
2. **From .eslintrc/.prettierrc/etc.**
|
||||
- Formatting rules
|
||||
- Linting conventions
|
||||
|
||||
3. **From existing README**
|
||||
- Project overview
|
||||
- Setup instructions
|
||||
|
||||
4. **From code structure**
|
||||
- Directory organization patterns
|
||||
- Module boundaries
|
||||
- Naming conventions
|
||||
|
||||
5. **From git history**
|
||||
- Commit message format
|
||||
- Branch naming patterns
|
||||
- PR workflow
|
||||
@@ -0,0 +1,294 @@
|
||||
# Slash Commands Design Patterns Reference
|
||||
|
||||
## Purpose
|
||||
|
||||
Slash commands are quick, reusable prompts triggered by `/command`. Create commands for:
|
||||
- Frequently used prompts
|
||||
- Common workflows
|
||||
- Quick reminders or templates
|
||||
- Team-standardized operations
|
||||
|
||||
## Command Structure
|
||||
|
||||
```
|
||||
.claude/commands/
|
||||
├── commit.md # /commit
|
||||
├── review.md # /review
|
||||
├── deploy.md # /deploy
|
||||
└── frontend/
|
||||
└── component.md # /component (project:frontend)
|
||||
```
|
||||
|
||||
## Command Template
|
||||
|
||||
```markdown
|
||||
---
|
||||
description: Brief description shown in /help
|
||||
allowed-tools: Tool1, Tool2
|
||||
argument-hint: [optional-args]
|
||||
---
|
||||
|
||||
# Command Instructions
|
||||
|
||||
[Detailed prompt for Claude to follow]
|
||||
```
|
||||
|
||||
## Frontmatter Options
|
||||
|
||||
| Field | Required | Description |
|
||||
|-------|----------|-------------|
|
||||
| `description` | No | Shown in `/help` (uses first line if not set) |
|
||||
| `allowed-tools` | No | Tools the command can use |
|
||||
| `argument-hint` | No | Args shown in autocomplete |
|
||||
| `model` | No | Specific model to use |
|
||||
| `context` | No | Set to `fork` for isolated execution |
|
||||
| `agent` | No | Agent type when `context: fork` |
|
||||
|
||||
## Common Project Commands
|
||||
|
||||
### Git Commit
|
||||
```markdown
|
||||
---
|
||||
description: Create a git commit with proper message format
|
||||
allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)
|
||||
argument-hint: [optional message]
|
||||
---
|
||||
|
||||
## Context
|
||||
- Current git status: !`git status`
|
||||
- Current git diff: !`git diff HEAD`
|
||||
- Recent commits: !`git log --oneline -5`
|
||||
|
||||
## Instructions
|
||||
Create a git commit following this format:
|
||||
- type(scope): subject
|
||||
- Body explaining what and why
|
||||
|
||||
Types: feat, fix, docs, style, refactor, test, chore
|
||||
|
||||
If $ARGUMENTS provided, use as commit message hint.
|
||||
```
|
||||
|
||||
### PR Review
|
||||
```markdown
|
||||
---
|
||||
description: Review pull request changes
|
||||
allowed-tools: Bash(git:*), Read, Grep
|
||||
argument-hint: [branch-name]
|
||||
---
|
||||
|
||||
## Context
|
||||
- Changes to review: !`git diff main...$1`
|
||||
- Changed files: !`git diff --name-only main...$1`
|
||||
|
||||
## Instructions
|
||||
Review the PR changes for:
|
||||
1. Code quality and clarity
|
||||
2. Potential bugs or edge cases
|
||||
3. Test coverage
|
||||
4. Security concerns
|
||||
5. Performance implications
|
||||
|
||||
Provide structured feedback with:
|
||||
- Approval recommendation
|
||||
- Required changes (if any)
|
||||
- Suggestions for improvement
|
||||
```
|
||||
|
||||
### Deploy
|
||||
```markdown
|
||||
---
|
||||
description: Deploy to specified environment
|
||||
allowed-tools: Bash
|
||||
argument-hint: [staging|production]
|
||||
---
|
||||
|
||||
## Instructions
|
||||
Deploy to $1 environment:
|
||||
|
||||
1. Verify current branch is deployable
|
||||
2. Run pre-deployment checks
|
||||
3. Execute deployment command
|
||||
4. Verify deployment success
|
||||
|
||||
For staging: `npm run deploy:staging`
|
||||
For production: `npm run deploy:prod`
|
||||
```
|
||||
|
||||
### Test
|
||||
```markdown
|
||||
---
|
||||
description: Run tests with coverage
|
||||
allowed-tools: Bash
|
||||
argument-hint: [file-pattern]
|
||||
---
|
||||
|
||||
## Instructions
|
||||
Run tests:
|
||||
- If $ARGUMENTS provided, run tests matching pattern
|
||||
- Otherwise, run full test suite
|
||||
|
||||
Command: `npm test $ARGUMENTS`
|
||||
|
||||
After tests complete:
|
||||
1. Report pass/fail summary
|
||||
2. Highlight any failures
|
||||
3. Show coverage changes if available
|
||||
```
|
||||
|
||||
### Create Component
|
||||
```markdown
|
||||
---
|
||||
description: Create a new React component
|
||||
allowed-tools: Write, Read
|
||||
argument-hint: [ComponentName]
|
||||
---
|
||||
|
||||
## Instructions
|
||||
Create a new React component named $1:
|
||||
|
||||
1. Create `src/components/$1/$1.tsx`:
|
||||
\`\`\`tsx
|
||||
import { FC } from 'react';
|
||||
import styles from './$1.module.css';
|
||||
|
||||
interface $1Props {
|
||||
// TODO: Define props
|
||||
}
|
||||
|
||||
export const $1: FC<$1Props> = (props) => {
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
{/* TODO: Implement */}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
\`\`\`
|
||||
|
||||
2. Create `src/components/$1/$1.module.css`
|
||||
3. Create `src/components/$1/$1.test.tsx`
|
||||
4. Export from `src/components/$1/index.ts`
|
||||
```
|
||||
|
||||
### API Endpoint
|
||||
```markdown
|
||||
---
|
||||
description: Create a new API endpoint
|
||||
allowed-tools: Write, Read
|
||||
argument-hint: [resource] [method]
|
||||
---
|
||||
|
||||
## Instructions
|
||||
Create API endpoint for $1 with $2 method:
|
||||
|
||||
1. Create route handler in `src/api/$1/route.ts`
|
||||
2. Add request/response types
|
||||
3. Implement handler logic
|
||||
4. Add input validation
|
||||
5. Create test file
|
||||
|
||||
Follow project API patterns from .claude/skills/api-patterns/
|
||||
```
|
||||
|
||||
### Database Migration
|
||||
```markdown
|
||||
---
|
||||
description: Create a database migration
|
||||
allowed-tools: Bash, Write
|
||||
argument-hint: [migration-name]
|
||||
---
|
||||
|
||||
## Context
|
||||
- Existing migrations: !`ls -la src/db/migrations/`
|
||||
|
||||
## Instructions
|
||||
Create a new migration named $1:
|
||||
|
||||
1. Run: `npm run migrate:create $1`
|
||||
2. Edit the generated migration file
|
||||
3. Implement both up and down functions
|
||||
4. Test locally: `npm run migrate:dev`
|
||||
```
|
||||
|
||||
### Format Code
|
||||
```markdown
|
||||
---
|
||||
description: Format and lint code
|
||||
allowed-tools: Bash
|
||||
argument-hint: [file-or-directory]
|
||||
---
|
||||
|
||||
## Instructions
|
||||
Format and lint code:
|
||||
|
||||
1. Run formatter: `npm run format $ARGUMENTS`
|
||||
2. Run linter: `npm run lint $ARGUMENTS`
|
||||
3. Report any remaining issues
|
||||
```
|
||||
|
||||
## Bash Command Execution
|
||||
|
||||
Use `!` prefix to execute bash commands and include output:
|
||||
|
||||
```markdown
|
||||
## Context
|
||||
- Current branch: !`git branch --show-current`
|
||||
- Status: !`git status --short`
|
||||
- Last commit: !`git log -1 --oneline`
|
||||
```
|
||||
|
||||
## File References
|
||||
|
||||
Use `@` to include file contents:
|
||||
|
||||
```markdown
|
||||
Review the implementation in @src/auth/login.ts
|
||||
|
||||
Compare @src/old.ts with @src/new.ts
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
### All Arguments
|
||||
```markdown
|
||||
# $ARGUMENTS captures all args
|
||||
Search for: $ARGUMENTS
|
||||
```
|
||||
|
||||
### Positional Arguments
|
||||
```markdown
|
||||
# $1, $2, $3 for specific positions
|
||||
Create $1 in $2 with $3 priority
|
||||
```
|
||||
|
||||
## Namespacing
|
||||
|
||||
Subdirectories create namespaced commands:
|
||||
|
||||
```
|
||||
.claude/commands/
|
||||
├── frontend/
|
||||
│ └── component.md # /component (project:frontend)
|
||||
├── backend/
|
||||
│ └── endpoint.md # /endpoint (project:backend)
|
||||
└── deploy.md # /deploy (project)
|
||||
```
|
||||
|
||||
## Extraction Patterns
|
||||
|
||||
When analyzing legacy code for commands:
|
||||
|
||||
1. **Identify common operations**
|
||||
- Build/test/deploy commands
|
||||
- Code generation patterns
|
||||
- Review procedures
|
||||
|
||||
2. **Find team workflows**
|
||||
- PR review process
|
||||
- Release procedures
|
||||
- Debugging steps
|
||||
|
||||
3. **Document shortcuts**
|
||||
- Frequently typed commands
|
||||
- Multi-step procedures
|
||||
- Environment setup
|
||||
@@ -0,0 +1,476 @@
|
||||
# Complete Examples
|
||||
|
||||
Real-world examples of AI-ready configurations for common project types.
|
||||
|
||||
## Table of Contents
|
||||
- [Next.js Web Application](#nextjs-web-application)
|
||||
- [Python FastAPI Backend](#python-fastapi-backend)
|
||||
- [Go Microservice](#go-microservice)
|
||||
- [React Component Library](#react-component-library)
|
||||
|
||||
---
|
||||
|
||||
## Next.js Web Application
|
||||
|
||||
### Generated CLAUDE.md
|
||||
|
||||
```markdown
|
||||
# MyApp - Next.js E-commerce Platform
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| `pnpm dev` | Start development server |
|
||||
| `pnpm build` | Production build |
|
||||
| `pnpm test` | Run tests |
|
||||
| `pnpm lint` | Run ESLint |
|
||||
| `pnpm format` | Format with Prettier |
|
||||
|
||||
## Code Style
|
||||
|
||||
### Naming
|
||||
- Components: PascalCase (`ProductCard.tsx`)
|
||||
- Hooks: camelCase with `use` prefix (`useCart.ts`)
|
||||
- Utils: camelCase (`formatPrice.ts`)
|
||||
- API routes: kebab-case (`/api/get-products`)
|
||||
|
||||
### Imports
|
||||
1. React/Next imports
|
||||
2. Third-party packages
|
||||
3. Internal modules (`@/`)
|
||||
4. Relative imports
|
||||
5. Type imports last
|
||||
|
||||
### Components
|
||||
- Prefer functional components with TypeScript
|
||||
- Use named exports
|
||||
- Props interface above component
|
||||
- Extract complex logic to custom hooks
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
src/
|
||||
├── app/ # Next.js App Router pages
|
||||
├── components/ # Reusable UI components
|
||||
├── hooks/ # Custom React hooks
|
||||
├── lib/ # Utilities and helpers
|
||||
├── services/ # API client functions
|
||||
└── types/ # TypeScript types
|
||||
```
|
||||
|
||||
### Data Flow
|
||||
- Server Components for data fetching
|
||||
- Client Components for interactivity
|
||||
- React Query for client-side data
|
||||
- Zustand for global client state
|
||||
|
||||
## Testing
|
||||
|
||||
- Unit tests: Vitest + React Testing Library
|
||||
- E2E: Playwright
|
||||
- Test files: `*.test.tsx` next to source
|
||||
|
||||
## Git Workflow
|
||||
|
||||
- Branch: `feature/[ticket]-description`
|
||||
- Commits: conventional commits (`feat:`, `fix:`, etc.)
|
||||
- PR: requires 1 approval + passing CI
|
||||
```
|
||||
|
||||
### Generated .claude/rules/api.md
|
||||
|
||||
```yaml
|
||||
---
|
||||
paths:
|
||||
- "src/app/api/**/*"
|
||||
---
|
||||
```
|
||||
|
||||
```markdown
|
||||
# API Route Rules
|
||||
|
||||
## Response Format
|
||||
Always use this structure:
|
||||
\`\`\`ts
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: result,
|
||||
error: null
|
||||
});
|
||||
\`\`\`
|
||||
|
||||
## Error Handling
|
||||
\`\`\`ts
|
||||
try {
|
||||
// logic
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ success: false, data: null, error: error.message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
## Validation
|
||||
Use Zod for all inputs:
|
||||
\`\`\`ts
|
||||
const schema = z.object({ ... });
|
||||
const result = schema.safeParse(body);
|
||||
if (!result.success) {
|
||||
return NextResponse.json({ error: result.error }, { status: 400 });
|
||||
}
|
||||
\`\`\`
|
||||
```
|
||||
|
||||
### Generated .claude/commands/commit.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
description: Create conventional commit
|
||||
allowed-tools: Bash(git:*)
|
||||
---
|
||||
|
||||
## Context
|
||||
- Status: !`git status --short`
|
||||
- Diff: !`git diff --stat`
|
||||
|
||||
## Instructions
|
||||
Create commit following conventional commits:
|
||||
- feat: new feature
|
||||
- fix: bug fix
|
||||
- docs: documentation
|
||||
- style: formatting
|
||||
- refactor: code restructure
|
||||
- test: adding tests
|
||||
- chore: maintenance
|
||||
|
||||
Format: `type(scope): description`
|
||||
```
|
||||
|
||||
### Generated .claude/settings.json
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "jq -r '.tool_input.file_path' | { read f; [[ \"$f\" =~ \\.(ts|tsx|js|jsx)$ ]] && npx prettier --write \"$f\" 2>/dev/null; exit 0; }"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Python FastAPI Backend
|
||||
|
||||
### Generated CLAUDE.md
|
||||
|
||||
```markdown
|
||||
# UserService - FastAPI Microservice
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| `uv run uvicorn main:app --reload` | Dev server |
|
||||
| `uv run pytest` | Run tests |
|
||||
| `uv run ruff check .` | Lint |
|
||||
| `uv run ruff format .` | Format |
|
||||
| `uv run mypy .` | Type check |
|
||||
|
||||
## Code Style
|
||||
|
||||
### Naming
|
||||
- Modules: snake_case (`user_service.py`)
|
||||
- Classes: PascalCase (`UserRepository`)
|
||||
- Functions: snake_case (`get_user_by_id`)
|
||||
- Constants: UPPER_SNAKE (`MAX_RETRIES`)
|
||||
|
||||
### Type Hints
|
||||
- Required for all public functions
|
||||
- Use `Optional[T]` explicitly
|
||||
- Prefer `list[T]` over `List[T]` (Python 3.9+)
|
||||
|
||||
### Docstrings
|
||||
Google style:
|
||||
\`\`\`python
|
||||
def get_user(user_id: int) -> User:
|
||||
"""Fetch user by ID.
|
||||
|
||||
Args:
|
||||
user_id: The unique user identifier.
|
||||
|
||||
Returns:
|
||||
User object if found.
|
||||
|
||||
Raises:
|
||||
NotFoundError: If user doesn't exist.
|
||||
"""
|
||||
\`\`\`
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
src/
|
||||
├── api/ # FastAPI routers
|
||||
├── models/ # Pydantic models
|
||||
├── services/ # Business logic
|
||||
├── repositories/ # Data access
|
||||
└── core/ # Config, dependencies
|
||||
```
|
||||
|
||||
### Dependency Injection
|
||||
Use FastAPI's `Depends()`:
|
||||
\`\`\`python
|
||||
@router.get("/users/{user_id}")
|
||||
async def get_user(
|
||||
user_id: int,
|
||||
service: UserService = Depends(get_user_service)
|
||||
):
|
||||
return await service.get(user_id)
|
||||
\`\`\`
|
||||
|
||||
## Database
|
||||
|
||||
- ORM: SQLAlchemy 2.0 with async
|
||||
- Migrations: Alembic
|
||||
- Always use transactions for writes
|
||||
|
||||
## Testing
|
||||
|
||||
- Framework: pytest + pytest-asyncio
|
||||
- Fixtures in `conftest.py`
|
||||
- Use factories for test data
|
||||
|
||||
## Environment
|
||||
|
||||
Required variables:
|
||||
- `DATABASE_URL`
|
||||
- `REDIS_URL`
|
||||
- `JWT_SECRET`
|
||||
```
|
||||
|
||||
### Generated .claude/skills/database/SKILL.md
|
||||
|
||||
```yaml
|
||||
---
|
||||
name: database-patterns
|
||||
description: SQLAlchemy patterns and migration workflow. Use when writing queries, creating models, or managing migrations.
|
||||
---
|
||||
```
|
||||
|
||||
```markdown
|
||||
# Database Patterns
|
||||
|
||||
## Model Definition
|
||||
\`\`\`python
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
email: Mapped[str] = mapped_column(unique=True, index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=func.now())
|
||||
\`\`\`
|
||||
|
||||
## Async Queries
|
||||
\`\`\`python
|
||||
async with async_session() as session:
|
||||
result = await session.execute(
|
||||
select(User).where(User.email == email)
|
||||
)
|
||||
user = result.scalar_one_or_none()
|
||||
\`\`\`
|
||||
|
||||
## Migrations
|
||||
|
||||
Create: `alembic revision --autogenerate -m "description"`
|
||||
Apply: `alembic upgrade head`
|
||||
Rollback: `alembic downgrade -1`
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Go Microservice
|
||||
|
||||
### Generated CLAUDE.md
|
||||
|
||||
```markdown
|
||||
# OrderService - Go gRPC Service
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| `make run` | Run service |
|
||||
| `make test` | Run tests |
|
||||
| `make lint` | Run golangci-lint |
|
||||
| `make proto` | Generate protobuf |
|
||||
| `make build` | Build binary |
|
||||
|
||||
## Code Style
|
||||
|
||||
### Naming
|
||||
- Packages: lowercase, single word (`user`, `order`)
|
||||
- Interfaces: `-er` suffix when possible (`Reader`, `UserStore`)
|
||||
- Exported: PascalCase
|
||||
- Unexported: camelCase
|
||||
|
||||
### Error Handling
|
||||
Always wrap errors with context:
|
||||
\`\`\`go
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get user %d: %w", userID, err)
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
### Interfaces
|
||||
Define at point of use, not implementation:
|
||||
\`\`\`go
|
||||
// In the consumer package
|
||||
type UserGetter interface {
|
||||
GetUser(ctx context.Context, id int64) (*User, error)
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
cmd/
|
||||
├── server/ # Main entry point
|
||||
internal/
|
||||
├── api/ # gRPC handlers
|
||||
├── domain/ # Business entities
|
||||
├── service/ # Business logic
|
||||
├── repository/ # Data access
|
||||
└── pkg/ # Shared utilities
|
||||
```
|
||||
|
||||
### Context Propagation
|
||||
Always pass context as first argument:
|
||||
\`\`\`go
|
||||
func (s *Service) Process(ctx context.Context, req *Request) error
|
||||
\`\`\`
|
||||
|
||||
## Testing
|
||||
|
||||
- Table-driven tests
|
||||
- Use testify for assertions
|
||||
- Mock interfaces with mockgen
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## React Component Library
|
||||
|
||||
### Generated CLAUDE.md
|
||||
|
||||
```markdown
|
||||
# UIKit - React Component Library
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| `pnpm dev` | Storybook dev |
|
||||
| `pnpm test` | Run tests |
|
||||
| `pnpm build` | Build library |
|
||||
| `pnpm lint` | ESLint + Stylelint |
|
||||
|
||||
## Code Style
|
||||
|
||||
### Component Structure
|
||||
\`\`\`tsx
|
||||
// Button.tsx
|
||||
export interface ButtonProps {
|
||||
variant?: 'primary' | 'secondary';
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ variant = 'primary', size = 'md', children, ...props }, ref) => {
|
||||
return (
|
||||
<button ref={ref} className={styles[variant]} {...props}>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
Button.displayName = 'Button';
|
||||
\`\`\`
|
||||
|
||||
### File Organization
|
||||
```
|
||||
src/components/Button/
|
||||
├── Button.tsx # Component
|
||||
├── Button.test.tsx # Tests
|
||||
├── Button.stories.tsx # Storybook
|
||||
├── Button.module.css # Styles
|
||||
└── index.ts # Export
|
||||
```
|
||||
|
||||
### Exports
|
||||
- Named exports only
|
||||
- Re-export from index.ts
|
||||
- Types exported separately
|
||||
|
||||
## Styling
|
||||
|
||||
- CSS Modules for component styles
|
||||
- Design tokens in CSS variables
|
||||
- No inline styles
|
||||
|
||||
## Testing
|
||||
|
||||
- React Testing Library
|
||||
- Test behavior, not implementation
|
||||
- Test accessibility with jest-axe
|
||||
|
||||
## Documentation
|
||||
|
||||
Every component needs:
|
||||
1. TypeScript types (self-documenting)
|
||||
2. Storybook stories (visual docs)
|
||||
3. JSDoc for complex props
|
||||
```
|
||||
|
||||
### Generated .claude/agents/accessibility-reviewer.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: accessibility-reviewer
|
||||
description: Review components for accessibility compliance. Use after creating or modifying UI components.
|
||||
tools: Read, Grep, Glob
|
||||
model: sonnet
|
||||
---
|
||||
|
||||
You are an accessibility expert reviewing React components.
|
||||
|
||||
## Review Checklist
|
||||
- Semantic HTML elements
|
||||
- ARIA attributes when needed
|
||||
- Keyboard navigation support
|
||||
- Focus management
|
||||
- Color contrast
|
||||
- Screen reader compatibility
|
||||
|
||||
## Output Format
|
||||
### Issues Found
|
||||
- [Issue with severity and fix]
|
||||
|
||||
### Recommendations
|
||||
- [Improvement suggestion]
|
||||
```
|
||||
@@ -0,0 +1,358 @@
|
||||
# Hooks Design Patterns Reference
|
||||
|
||||
## Purpose
|
||||
|
||||
Hooks are shell commands that execute at specific events in Claude Code's lifecycle. Use hooks for:
|
||||
- Automatic code formatting
|
||||
- Pre-commit validation
|
||||
- Custom notifications
|
||||
- Logging and compliance
|
||||
- File protection
|
||||
|
||||
## Configuration Location
|
||||
|
||||
```json
|
||||
// .claude/settings.json
|
||||
{
|
||||
"hooks": {
|
||||
"EventName": [
|
||||
{
|
||||
"matcher": "ToolPattern",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "your-command-here"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Hook Events
|
||||
|
||||
| Event | Trigger | Use Case |
|
||||
|-------|---------|----------|
|
||||
| `PreToolUse` | Before tool runs | Validation, blocking |
|
||||
| `PostToolUse` | After tool completes | Formatting, logging |
|
||||
| `PermissionRequest` | Permission dialog | Auto-allow/deny |
|
||||
| `UserPromptSubmit` | User submits prompt | Prompt validation |
|
||||
| `Notification` | Claude sends notification | Custom alerts |
|
||||
| `Stop` | Claude finishes | Cleanup, summary |
|
||||
| `SessionStart` | Session begins | Setup, initialization |
|
||||
| `SessionEnd` | Session ends | Cleanup |
|
||||
|
||||
## Matchers
|
||||
|
||||
| Pattern | Matches |
|
||||
|---------|---------|
|
||||
| `Write` | Exact match |
|
||||
| `Edit\|Write` | Either Edit or Write |
|
||||
| `Notebook.*` | Regex pattern |
|
||||
| `*` or `""` | All tools |
|
||||
|
||||
## Common Hook Patterns
|
||||
|
||||
### Code Formatting (PostToolUse)
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "jq -r '.tool_input.file_path' | { read f; [[ \"$f\" == *.ts ]] && npx prettier --write \"$f\"; }"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Python Formatting
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "jq -r '.tool_input.file_path' | { read f; [[ \"$f\" == *.py ]] && black \"$f\" && isort \"$f\"; }"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### File Protection (PreToolUse)
|
||||
|
||||
Block edits to sensitive files:
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 -c \"import json,sys; d=json.load(sys.stdin); p=d.get('tool_input',{}).get('file_path',''); sys.exit(2 if any(x in p for x in ['.env','.git/','secrets/']) else 0)\""
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Command Logging (PreToolUse)
|
||||
|
||||
Log all bash commands:
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "jq -r '.tool_input.command' >> ~/.claude/command-log.txt"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Custom Notifications
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"Notification": [
|
||||
{
|
||||
"matcher": "",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "osascript -e 'display notification \"Claude needs attention\" with title \"Claude Code\"'"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Session Initialization
|
||||
|
||||
Install dependencies on session start:
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"matcher": "startup",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "\"$CLAUDE_PROJECT_DIR\"/scripts/setup.sh"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Lint on Edit
|
||||
|
||||
Run linter after file modifications:
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "jq -r '.tool_input.file_path' | { read f; [[ -f \"$f\" ]] && npm run lint -- \"$f\"; }"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Exit Codes
|
||||
|
||||
| Exit Code | Behavior |
|
||||
|-----------|----------|
|
||||
| 0 | Success, continue |
|
||||
| 1 | Error, continue with warning |
|
||||
| 2 | Block the tool operation |
|
||||
|
||||
## Hook Input (stdin)
|
||||
|
||||
Hooks receive JSON input via stdin:
|
||||
|
||||
```json
|
||||
{
|
||||
"session_id": "abc123",
|
||||
"tool_name": "Edit",
|
||||
"tool_input": {
|
||||
"file_path": "/path/to/file.ts",
|
||||
"old_string": "...",
|
||||
"new_string": "..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
| Variable | Description |
|
||||
|----------|-------------|
|
||||
| `CLAUDE_PROJECT_DIR` | Project root directory |
|
||||
| `CLAUDE_SESSION_ID` | Current session ID |
|
||||
| `CLAUDE_ENV_FILE` | File for persisting env vars |
|
||||
|
||||
## Project-Specific Scripts
|
||||
|
||||
Reference scripts using `$CLAUDE_PROJECT_DIR`:
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format.sh"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Example script `.claude/hooks/format.sh`:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
INPUT=$(cat)
|
||||
FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path')
|
||||
|
||||
case "$FILE" in
|
||||
*.ts|*.tsx) npx prettier --write "$FILE" ;;
|
||||
*.py) black "$FILE" && isort "$FILE" ;;
|
||||
*.go) gofmt -w "$FILE" ;;
|
||||
*.rs) rustfmt "$FILE" ;;
|
||||
esac
|
||||
```
|
||||
|
||||
## Language-Specific Configurations
|
||||
|
||||
### TypeScript/JavaScript
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "jq -r '.tool_input.file_path' | { read f; [[ \"$f\" =~ \\.(ts|tsx|js|jsx)$ ]] && npx prettier --write \"$f\" && npx eslint --fix \"$f\"; }"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Python
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "jq -r '.tool_input.file_path' | { read f; [[ \"$f\" == *.py ]] && black \"$f\" && isort \"$f\" && ruff check --fix \"$f\"; }"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Go
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "jq -r '.tool_input.file_path' | { read f; [[ \"$f\" == *.go ]] && gofmt -w \"$f\" && goimports -w \"$f\"; }"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Extraction Patterns
|
||||
|
||||
When analyzing legacy code for hooks:
|
||||
|
||||
1. **Check existing tooling**
|
||||
- Pre-commit hooks
|
||||
- Git hooks
|
||||
- CI/CD formatting steps
|
||||
|
||||
2. **Identify formatting tools**
|
||||
- Prettier, ESLint (JS/TS)
|
||||
- Black, isort, ruff (Python)
|
||||
- gofmt, goimports (Go)
|
||||
|
||||
3. **Find validation rules**
|
||||
- Protected files/directories
|
||||
- Required checks before commit
|
||||
- Lint rules
|
||||
|
||||
4. **Note team practices**
|
||||
- Auto-formatting expectations
|
||||
- Logging requirements
|
||||
- Notification preferences
|
||||
@@ -0,0 +1,215 @@
|
||||
# MCP Servers Configuration Patterns
|
||||
|
||||
## Purpose
|
||||
|
||||
MCP (Model Context Protocol) servers connect Claude Code to external tools and data sources. Consider MCP servers when:
|
||||
- Project uses external APIs/services frequently
|
||||
- Team has internal tools that could benefit Claude
|
||||
- Database queries are common operations
|
||||
- External data sources need integration
|
||||
|
||||
## Configuration Location
|
||||
|
||||
MCP servers are configured in Claude Code settings:
|
||||
- User-level: `~/.claude/settings.json`
|
||||
- Project-level: `.claude/settings.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"server-name": {
|
||||
"command": "command-to-run",
|
||||
"args": ["arg1", "arg2"],
|
||||
"env": {
|
||||
"ENV_VAR": "value"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Common MCP Server Patterns
|
||||
|
||||
### Database Access
|
||||
|
||||
For projects with frequent database operations:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"postgres": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-postgres"],
|
||||
"env": {
|
||||
"POSTGRES_CONNECTION_STRING": "${POSTGRES_URL}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Filesystem Access
|
||||
|
||||
For projects needing broader file access:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"filesystem": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/dir"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### GitHub Integration
|
||||
|
||||
For GitHub-heavy workflows:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"github": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-github"],
|
||||
"env": {
|
||||
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Slack Integration
|
||||
|
||||
For team communication:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"slack": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-slack"],
|
||||
"env": {
|
||||
"SLACK_BOT_TOKEN": "${SLACK_TOKEN}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Memory/Knowledge Base
|
||||
|
||||
For persistent context across sessions:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"memory": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-memory"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## When to Add MCP Servers
|
||||
|
||||
| Project Pattern | Recommended MCP |
|
||||
|-----------------|-----------------|
|
||||
| Database-heavy backend | postgres/mysql server |
|
||||
| GitHub PR workflow | github server |
|
||||
| Documentation site | filesystem server |
|
||||
| Slack-integrated team | slack server |
|
||||
| Multi-repo monorepo | filesystem + github |
|
||||
|
||||
## Security Considerations
|
||||
|
||||
1. **Environment Variables** - Never hardcode secrets in settings
|
||||
2. **Minimal Permissions** - Only enable needed capabilities
|
||||
3. **Project vs User** - Project MCP configs are shared via git
|
||||
4. **Token Scoping** - Use minimal-scope tokens
|
||||
|
||||
## Environment Variable Pattern
|
||||
|
||||
Use `${VAR_NAME}` syntax for sensitive values:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"database": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-postgres"],
|
||||
"env": {
|
||||
"CONNECTION_STRING": "${DATABASE_URL}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Then set in `.env` or shell:
|
||||
```bash
|
||||
export DATABASE_URL="postgres://user:pass@host:5432/db"
|
||||
```
|
||||
|
||||
## Custom MCP Servers
|
||||
|
||||
For project-specific tools, create custom MCP servers:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"internal-api": {
|
||||
"command": "node",
|
||||
"args": [".claude/mcp/internal-api-server.js"],
|
||||
"env": {
|
||||
"API_KEY": "${INTERNAL_API_KEY}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## MCP Permission Rules
|
||||
|
||||
Control which MCP tools are allowed:
|
||||
|
||||
```json
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"mcp__github",
|
||||
"mcp__postgres__query"
|
||||
],
|
||||
"deny": [
|
||||
"mcp__postgres__execute"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Extraction Patterns
|
||||
|
||||
When analyzing legacy code for MCP needs:
|
||||
|
||||
1. **Check for API integrations**
|
||||
- REST API calls
|
||||
- GraphQL queries
|
||||
- Third-party services
|
||||
|
||||
2. **Identify data sources**
|
||||
- Database connections
|
||||
- External data files
|
||||
- Cloud storage
|
||||
|
||||
3. **Find team tools**
|
||||
- Internal dashboards
|
||||
- Deployment tools
|
||||
- Monitoring systems
|
||||
|
||||
4. **Note common operations**
|
||||
- Frequent queries
|
||||
- Repeated API calls
|
||||
- Data transformations
|
||||
@@ -0,0 +1,101 @@
|
||||
# Skills & MCP 资源检索源
|
||||
|
||||
为AI-ready项目推荐的资源发现渠道,帮助团队找到现成的skills和MCP servers。
|
||||
|
||||
## Skills 检索源
|
||||
|
||||
### 聚合市场 & 目录
|
||||
|
||||
| 名称 | Link | 类型 | 适合场景 |
|
||||
|------|------|------|----------|
|
||||
| **SkillsMP** | https://skillsmp.com/ | 超大marketplace | 71000+ skills,海量搜索、长尾挖掘 |
|
||||
| **SkillHub.club** | https://www.skillhub.club/ | 在线市场 | AI-evaluated标注,看评分/Stars挑技能 |
|
||||
| **agent-skills.md** | https://agent-skills.md/ | 在线目录 | 直接浏览+安装命令 |
|
||||
| **Claude Skills Hub** | https://claudeskills.info/ | 在线目录 | UI友好,适合"逛"发现 |
|
||||
| **MCP Market Skills区** | https://mcpmarket.com/ | 目录/市场 | skills + MCP工具一处看 |
|
||||
|
||||
### GitHub Awesome Lists
|
||||
|
||||
| 名称 | Link | 特点 |
|
||||
|------|------|------|
|
||||
| **Skillhub Awesome Skills** | https://github.com/keyuyuan/skillhub-awesome-skills | 精选技能清单,分类友好 |
|
||||
| **Awesome Claude Skills (VoltAgent)** | https://github.com/VoltAgent/awesome-claude-skills | 生态资源大全视角 |
|
||||
| **Awesome Claude Skills (travisvn)** | https://github.com/travisvn/awesome-claude-skills | 另一套curated清单 |
|
||||
| **Awesome Claude Skills (ComposioHQ)** | https://github.com/ComposioHQ/awesome-claude-skills | 量大,通用/工具化技能多 |
|
||||
| **AwesomeClaude 可视化** | https://awesomeclaude.ai/awesome-claude-skills | UI快速浏览ComposioHQ集合 |
|
||||
| **Awesome Agent Skills** | https://github.com/heilcheng/awesome-agent-skills | 覆盖Claude/Codex/Copilot等 |
|
||||
|
||||
### 成体系技能仓库(可直接搬用)
|
||||
|
||||
| 仓库 | Link | 特点 |
|
||||
|------|------|------|
|
||||
| **alirezarezvani/claude-skills** | https://github.com/alirezarezvani/claude-skills | Content Creator/Marketing等,适合直接落地 |
|
||||
| **gked2121/claude-skills** | https://github.com/gked2121/claude-skills | 偏workflow思维,含创作链路示例 |
|
||||
| **Microck/ordinary-claude-skills** | https://github.com/Microck/ordinary-claude-skills | 超大集合,适合当"技能矿" |
|
||||
| **sickn33/antigravity-awesome-skills** | https://github.com/sickn33/antigravity-awesome-skills | 结构化程度高,利于搬运 |
|
||||
| **synapz-org/marketing-ops-hub** | https://github.com/synapz-org/marketing-ops-hub | 营销/运营体系,内容增长相关 |
|
||||
| **m2ai-portfolio/claude-skills** | https://github.com/m2ai-portfolio/claude-skills | 创作者/增长向技能包 |
|
||||
|
||||
### 工具 & 文档
|
||||
|
||||
| 名称 | Link | 用途 |
|
||||
|------|------|------|
|
||||
| **SkillHub Desktop** | https://github.com/skillhub-club/skillhub-desktop | 跨工具管理/同步skills |
|
||||
| **SkillsMP Docs** | https://skillsmp.com/docs | skills vs MCP、安装方式、最佳实践 |
|
||||
| **Official Claude Skills Docs** | https://code.claude.com/docs/en/skills | 官方规范,写/改skills必看 |
|
||||
|
||||
---
|
||||
|
||||
## MCP 检索源
|
||||
|
||||
### 官方资源
|
||||
|
||||
| 名称 | Link | 用途 |
|
||||
|------|------|------|
|
||||
| **MCP 官方 Servers 仓库** | https://github.com/modelcontextprotocol/servers | 官方/参考实现 + 社区索引 |
|
||||
| **MCP 官方 Examples** | https://modelcontextprotocol.io/examples | 示例与官方集成入口 |
|
||||
| **MCP Registry (Repo)** | https://github.com/modelcontextprotocol/registry | 自建/对接registry服务 |
|
||||
| **MCP Registry (Web)** | https://registry.modelcontextprotocol.io/ | 浏览/查询registry条目 |
|
||||
|
||||
### 市场 & 目录
|
||||
|
||||
| 名称 | Link | 特点 |
|
||||
|------|------|------|
|
||||
| **Glama MCP Directory** | https://glama.ai/mcp/servers | 超大目录,按stars/downloads/更新排序 |
|
||||
| **MCP Market** | https://mcpmarket.com/ | MCP servers & clients市场 |
|
||||
| **Awesome MCP Servers (mcpservers.org)** | https://mcpservers.org/ | 按Official/Remote/Clients分类 |
|
||||
| **PulseMCP Servers** | https://www.pulsemcp.com/servers | 全量索引+每日更新 |
|
||||
| **MCP.so Servers** | https://mcp.so/servers | 中英混合,覆盖面广 |
|
||||
| **Smithery** | https://smithery.ai/ | Registry/分发,装机式体验 |
|
||||
|
||||
### GitHub Awesome Lists
|
||||
|
||||
| 名称 | Link |
|
||||
|------|------|
|
||||
| **punkpeye/awesome-mcp-servers** | https://github.com/punkpeye/awesome-mcp-servers |
|
||||
| **wong2/awesome-mcp-servers** | https://github.com/wong2/awesome-mcp-servers |
|
||||
|
||||
### 企业文档
|
||||
|
||||
| 名称 | Link | 用途 |
|
||||
|------|------|------|
|
||||
| **GitHub配置组织级MCP Registry** | https://docs.github.com/en/copilot/how-tos/administer-copilot/manage-mcp-usage/configure-mcp-registry | 团队治理与合规 |
|
||||
|
||||
---
|
||||
|
||||
## 推荐使用策略
|
||||
|
||||
### 对于新手团队
|
||||
1. 先从 **SkillHub.club** 或 **Claude Skills Hub** 发现评分高的skills
|
||||
2. 查看 **Official Claude Skills Docs** 理解结构
|
||||
3. 从 **GitHub成体系仓库** 直接复制相关skills
|
||||
|
||||
### 对于进阶团队
|
||||
1. 用 **SkillsMP** 做长尾挖掘
|
||||
2. 配置 **MCP servers** 连接外部工具
|
||||
3. 用 **skill-creator** 创建定制skills
|
||||
|
||||
### 对于企业团队
|
||||
1. 参考 **MCP Registry** 自建内部registry
|
||||
2. 用 **SkillHub Desktop** 统一管理
|
||||
3. 配置组织级MCP策略
|
||||
@@ -0,0 +1,300 @@
|
||||
# Rules Patterns Reference
|
||||
|
||||
## Purpose
|
||||
|
||||
`.claude/rules/` provides modular, path-specific instructions that supplement CLAUDE.md. Use rules for:
|
||||
- Language-specific guidelines
|
||||
- Module-specific conventions
|
||||
- Team-specific workflows
|
||||
- Conditional instructions
|
||||
|
||||
## Structure
|
||||
|
||||
```
|
||||
.claude/rules/
|
||||
├── code-style.md # General coding style
|
||||
├── testing.md # Testing conventions
|
||||
├── api-design.md # API patterns
|
||||
├── security.md # Security requirements
|
||||
├── frontend/
|
||||
│ ├── react.md # React-specific rules
|
||||
│ └── styles.md # CSS conventions
|
||||
└── backend/
|
||||
├── api.md # Backend API rules
|
||||
└── database.md # Database conventions
|
||||
```
|
||||
|
||||
## Rule File Template
|
||||
|
||||
### Unconditional Rule (applies to all files)
|
||||
|
||||
```markdown
|
||||
# Code Style Rules
|
||||
|
||||
## Naming Conventions
|
||||
- Use camelCase for variables and functions
|
||||
- Use PascalCase for classes and types
|
||||
- Use UPPER_SNAKE_CASE for constants
|
||||
|
||||
## Comments
|
||||
- Document public APIs with JSDoc
|
||||
- Avoid obvious comments
|
||||
- Explain "why" not "what"
|
||||
```
|
||||
|
||||
### Conditional Rule (applies to specific paths)
|
||||
|
||||
```yaml
|
||||
---
|
||||
paths:
|
||||
- "src/api/**/*.ts"
|
||||
---
|
||||
```
|
||||
|
||||
```markdown
|
||||
# API Development Rules
|
||||
|
||||
## Request Validation
|
||||
- Validate all input with Zod schemas
|
||||
- Return typed responses
|
||||
- Use standard error format
|
||||
|
||||
## Security
|
||||
- Authenticate all endpoints
|
||||
- Check authorization
|
||||
- Sanitize user input
|
||||
```
|
||||
|
||||
## Path Patterns
|
||||
|
||||
| Pattern | Matches |
|
||||
|---------|---------|
|
||||
| `**/*.ts` | All TypeScript files |
|
||||
| `src/**/*` | All files under src/ |
|
||||
| `*.md` | Markdown files in root |
|
||||
| `src/api/**/*.ts` | TS files in API directory |
|
||||
| `tests/**/*.test.ts` | Test files |
|
||||
|
||||
## Brace Expansion
|
||||
|
||||
```yaml
|
||||
---
|
||||
paths:
|
||||
- "src/**/*.{ts,tsx}"
|
||||
- "{src,lib}/**/*.ts"
|
||||
---
|
||||
```
|
||||
|
||||
## Common Rule Files
|
||||
|
||||
### Code Style (`code-style.md`)
|
||||
|
||||
```markdown
|
||||
# Code Style
|
||||
|
||||
## TypeScript
|
||||
- Enable strict mode
|
||||
- Prefer `const` over `let`
|
||||
- Use explicit return types for public functions
|
||||
- Avoid `any`, use `unknown` if needed
|
||||
|
||||
## Formatting
|
||||
- 2-space indentation
|
||||
- Single quotes for strings
|
||||
- Trailing commas in multiline
|
||||
- No semicolons (per project preference)
|
||||
|
||||
## Imports
|
||||
1. External packages (alphabetical)
|
||||
2. Internal modules (alphabetical)
|
||||
3. Relative imports (by distance)
|
||||
```
|
||||
|
||||
### Testing (`testing.md`)
|
||||
|
||||
```markdown
|
||||
# Testing Rules
|
||||
|
||||
## Test Organization
|
||||
- Unit tests: `*.test.ts` alongside source
|
||||
- Integration: `tests/integration/`
|
||||
- E2E: `tests/e2e/`
|
||||
|
||||
## Naming
|
||||
- Describe behavior: `should [expected behavior] when [condition]`
|
||||
- Group by function/component
|
||||
|
||||
## Coverage Requirements
|
||||
- Minimum 80% coverage for new code
|
||||
- Critical paths must have integration tests
|
||||
```
|
||||
|
||||
### API Design (`api-design.md`)
|
||||
|
||||
```yaml
|
||||
---
|
||||
paths:
|
||||
- "src/api/**/*"
|
||||
- "src/routes/**/*"
|
||||
---
|
||||
```
|
||||
|
||||
```markdown
|
||||
# API Design Rules
|
||||
|
||||
## Endpoint Structure
|
||||
- REST: `/api/v1/[resource]/[id]/[action]`
|
||||
- Use plural nouns for resources
|
||||
|
||||
## Response Format
|
||||
\`\`\`json
|
||||
{
|
||||
"success": boolean,
|
||||
"data": object | null,
|
||||
"error": { "code": string, "message": string } | null
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
## Status Codes
|
||||
- 200: Success
|
||||
- 201: Created
|
||||
- 400: Bad Request
|
||||
- 401: Unauthorized
|
||||
- 403: Forbidden
|
||||
- 404: Not Found
|
||||
- 500: Server Error
|
||||
|
||||
## Validation
|
||||
- Use Zod schemas for all inputs
|
||||
- Return detailed validation errors
|
||||
```
|
||||
|
||||
### Security (`security.md`)
|
||||
|
||||
```markdown
|
||||
# Security Rules
|
||||
|
||||
## Input Validation
|
||||
- Never trust user input
|
||||
- Validate and sanitize all inputs
|
||||
- Use parameterized queries
|
||||
|
||||
## Authentication
|
||||
- Use secure session management
|
||||
- Implement rate limiting
|
||||
- Log authentication events
|
||||
|
||||
## Secrets
|
||||
- Never commit secrets
|
||||
- Use environment variables
|
||||
- Rotate credentials regularly
|
||||
|
||||
## Dependencies
|
||||
- Keep dependencies updated
|
||||
- Review security advisories
|
||||
- Use lockfiles
|
||||
```
|
||||
|
||||
### React Components (`frontend/react.md`)
|
||||
|
||||
```yaml
|
||||
---
|
||||
paths:
|
||||
- "src/components/**/*.tsx"
|
||||
- "src/pages/**/*.tsx"
|
||||
---
|
||||
```
|
||||
|
||||
```markdown
|
||||
# React Rules
|
||||
|
||||
## Component Structure
|
||||
1. Imports
|
||||
2. Types/Interfaces
|
||||
3. Component function
|
||||
4. Styles (if co-located)
|
||||
|
||||
## Hooks
|
||||
- Custom hooks in `src/hooks/`
|
||||
- Prefix with `use`
|
||||
- Document dependencies
|
||||
|
||||
## State Management
|
||||
- Local state: useState
|
||||
- Server state: React Query
|
||||
- Global state: Context/Zustand
|
||||
|
||||
## Performance
|
||||
- Memoize expensive computations
|
||||
- Use `memo` for pure components
|
||||
- Lazy load routes
|
||||
```
|
||||
|
||||
### Database (`backend/database.md`)
|
||||
|
||||
```yaml
|
||||
---
|
||||
paths:
|
||||
- "src/db/**/*"
|
||||
- "src/models/**/*"
|
||||
- "prisma/**/*"
|
||||
---
|
||||
```
|
||||
|
||||
```markdown
|
||||
# Database Rules
|
||||
|
||||
## Queries
|
||||
- Use ORM for standard operations
|
||||
- Raw SQL for complex queries
|
||||
- Always use transactions for multi-step operations
|
||||
|
||||
## Migrations
|
||||
- One migration per change
|
||||
- Always write down migrations
|
||||
- Test migrations locally first
|
||||
|
||||
## Naming
|
||||
- Tables: snake_case, plural
|
||||
- Columns: snake_case
|
||||
- Foreign keys: `[table]_id`
|
||||
|
||||
## Indexes
|
||||
- Primary keys: automatic
|
||||
- Foreign keys: always index
|
||||
- Query patterns: create indexes
|
||||
```
|
||||
|
||||
## User-Level Rules
|
||||
|
||||
Personal rules in `~/.claude/rules/`:
|
||||
|
||||
```
|
||||
~/.claude/rules/
|
||||
├── preferences.md # Personal coding style
|
||||
└── workflows.md # Personal workflows
|
||||
```
|
||||
|
||||
## Extraction Patterns
|
||||
|
||||
When analyzing legacy code for rules:
|
||||
|
||||
1. **Check existing configs**
|
||||
- .eslintrc, .prettierrc
|
||||
- tsconfig.json strict settings
|
||||
- .editorconfig
|
||||
|
||||
2. **Analyze code patterns**
|
||||
- Common coding conventions
|
||||
- Import organization
|
||||
- Error handling patterns
|
||||
|
||||
3. **Identify module boundaries**
|
||||
- API vs frontend vs shared
|
||||
- Test organization
|
||||
- Module-specific conventions
|
||||
|
||||
4. **Document team standards**
|
||||
- Code review requirements
|
||||
- Merge criteria
|
||||
- Documentation expectations
|
||||
@@ -0,0 +1,226 @@
|
||||
# Skills Design Patterns Reference
|
||||
|
||||
## Purpose
|
||||
|
||||
Skills give Claude specialized knowledge for specific tasks. Create project-specific skills when:
|
||||
- There are complex domain-specific workflows
|
||||
- Certain tasks require consistent procedures
|
||||
- Team knowledge needs to be codified
|
||||
|
||||
## Skill Structure
|
||||
|
||||
```
|
||||
.claude/skills/
|
||||
└── skill-name/
|
||||
├── SKILL.md # Required: main instructions
|
||||
├── scripts/ # Optional: executable code
|
||||
├── references/ # Optional: detailed docs
|
||||
└── assets/ # Optional: templates/files
|
||||
```
|
||||
|
||||
## When to Create Skills
|
||||
|
||||
### Good Candidates
|
||||
1. **API Integration Patterns** - Custom API workflows
|
||||
2. **Database Operations** - Complex query patterns, migrations
|
||||
3. **Deployment Procedures** - Release workflows
|
||||
4. **Code Generation** - Project-specific generators
|
||||
5. **Testing Strategies** - Complex test scenarios
|
||||
6. **Documentation** - Doc generation patterns
|
||||
|
||||
### Not Suitable for Skills
|
||||
1. Simple, one-off tasks
|
||||
2. Generic coding knowledge
|
||||
3. Information that changes frequently
|
||||
|
||||
## SKILL.md Template
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: skill-name
|
||||
description: What this skill does and when to use it. Use when [specific triggers]. Handles [specific tasks].
|
||||
---
|
||||
|
||||
# Skill Name
|
||||
|
||||
## Quick Start
|
||||
[Minimal example to get started]
|
||||
|
||||
## Workflow
|
||||
1. [Step 1]
|
||||
2. [Step 2]
|
||||
3. [Step 3]
|
||||
|
||||
## Patterns
|
||||
|
||||
### Pattern 1: [Name]
|
||||
[Description and example]
|
||||
|
||||
### Pattern 2: [Name]
|
||||
[Description and example]
|
||||
|
||||
## Scripts
|
||||
- `scripts/script-name.py`: [What it does]
|
||||
|
||||
## References
|
||||
- [reference-name.md](references/reference-name.md): [When to read]
|
||||
```
|
||||
|
||||
## Common Project Skills
|
||||
|
||||
### API Skill
|
||||
```markdown
|
||||
---
|
||||
name: api-patterns
|
||||
description: Project API design patterns. Use when creating/modifying API endpoints, handling requests, or working with API responses.
|
||||
---
|
||||
|
||||
# API Patterns
|
||||
|
||||
## Endpoint Structure
|
||||
All endpoints follow: `/api/v1/[resource]/[action]`
|
||||
|
||||
## Request Validation
|
||||
Use Zod schemas in `src/schemas/`:
|
||||
\`\`\`typescript
|
||||
const CreateUserSchema = z.object({
|
||||
email: z.string().email(),
|
||||
name: z.string().min(1)
|
||||
});
|
||||
\`\`\`
|
||||
|
||||
## Response Format
|
||||
\`\`\`json
|
||||
{
|
||||
"success": true,
|
||||
"data": { ... },
|
||||
"error": null
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
## Error Handling
|
||||
Use `ApiError` class from `src/lib/errors`:
|
||||
\`\`\`typescript
|
||||
throw new ApiError(400, "VALIDATION_ERROR", "Invalid input");
|
||||
\`\`\`
|
||||
```
|
||||
|
||||
### Database Skill
|
||||
```markdown
|
||||
---
|
||||
name: database-patterns
|
||||
description: Database operations and query patterns. Use when writing queries, creating migrations, or working with data models.
|
||||
---
|
||||
|
||||
# Database Patterns
|
||||
|
||||
## Schema Reference
|
||||
See [references/schema.md](references/schema.md) for full schema.
|
||||
|
||||
## Common Queries
|
||||
### User lookup
|
||||
\`\`\`sql
|
||||
SELECT * FROM users WHERE id = $1 AND deleted_at IS NULL;
|
||||
\`\`\`
|
||||
|
||||
## Migration Pattern
|
||||
1. Create migration: `npm run migrate:create [name]`
|
||||
2. Write up/down functions
|
||||
3. Test locally: `npm run migrate:dev`
|
||||
4. Apply: `npm run migrate:prod`
|
||||
```
|
||||
|
||||
### Testing Skill
|
||||
```markdown
|
||||
---
|
||||
name: testing-patterns
|
||||
description: Testing strategies and patterns. Use when writing tests, setting up test data, or debugging test failures.
|
||||
---
|
||||
|
||||
# Testing Patterns
|
||||
|
||||
## Test Organization
|
||||
- Unit tests: `*.test.ts` next to source
|
||||
- Integration: `tests/integration/`
|
||||
- E2E: `tests/e2e/`
|
||||
|
||||
## Fixtures
|
||||
Use factories in `tests/factories/`:
|
||||
\`\`\`typescript
|
||||
import { createUser } from '@/tests/factories';
|
||||
const user = await createUser({ role: 'admin' });
|
||||
\`\`\`
|
||||
|
||||
## Mocking Patterns
|
||||
\`\`\`typescript
|
||||
vi.mock('@/lib/email', () => ({
|
||||
sendEmail: vi.fn().mockResolvedValue({ sent: true })
|
||||
}));
|
||||
\`\`\`
|
||||
```
|
||||
|
||||
### Deployment Skill
|
||||
```markdown
|
||||
---
|
||||
name: deployment-guide
|
||||
description: Deployment procedures and release workflow. Use when deploying, creating releases, or troubleshooting deployments.
|
||||
---
|
||||
|
||||
# Deployment Guide
|
||||
|
||||
## Pre-Deployment Checklist
|
||||
- [ ] All tests pass
|
||||
- [ ] Version bumped
|
||||
- [ ] Changelog updated
|
||||
- [ ] PR approved
|
||||
|
||||
## Deployment Steps
|
||||
1. Merge to main
|
||||
2. Tag release: `git tag v[version]`
|
||||
3. Push tag: `git push --tags`
|
||||
4. Monitor CI/CD pipeline
|
||||
5. Verify deployment
|
||||
|
||||
## Rollback
|
||||
\`\`\`bash
|
||||
./scripts/rollback.sh [previous-version]
|
||||
\`\`\`
|
||||
```
|
||||
|
||||
## Extraction Patterns
|
||||
|
||||
When analyzing legacy code for skills:
|
||||
|
||||
1. **Identify repeated patterns**
|
||||
- Common query patterns
|
||||
- API response handling
|
||||
- Error handling workflows
|
||||
|
||||
2. **Find domain knowledge**
|
||||
- Business logic rules
|
||||
- Data validation rules
|
||||
- Calculation formulas
|
||||
|
||||
3. **Document complex workflows**
|
||||
- Multi-step procedures
|
||||
- Decision trees
|
||||
- State machines
|
||||
|
||||
4. **Extract tool-specific knowledge**
|
||||
- Build tool configurations
|
||||
- Test framework patterns
|
||||
- Deployment procedures
|
||||
|
||||
## Progressive Disclosure
|
||||
|
||||
Keep SKILL.md concise (<500 lines). Split into references:
|
||||
|
||||
```markdown
|
||||
## Quick Start
|
||||
[Essential info here]
|
||||
|
||||
## Advanced Topics
|
||||
- **Complex Queries**: See [references/queries.md](references/queries.md)
|
||||
- **Error Codes**: See [references/errors.md](references/errors.md)
|
||||
- **Performance**: See [references/performance.md](references/performance.md)
|
||||
```
|
||||
@@ -0,0 +1,969 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Codebase Analyzer for Legacy-to-AI-Ready Skill
|
||||
|
||||
Analyzes a codebase to extract patterns, conventions, and structure
|
||||
for generating Claude Code configurations.
|
||||
|
||||
Usage:
|
||||
python analyze_codebase.py [path] [--output json|markdown]
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
# Directories to ignore
|
||||
IGNORE_DIRS = {
|
||||
'node_modules', '.git', '__pycache__', '.venv', 'venv', 'env',
|
||||
'dist', 'build', '.next', '.nuxt', 'coverage', '.pytest_cache',
|
||||
'.mypy_cache', '.tox', 'eggs', '*.egg-info', '.idea', '.vscode',
|
||||
'vendor', 'target', 'out', 'bin', 'obj'
|
||||
}
|
||||
|
||||
# File extensions by category
|
||||
EXTENSIONS = {
|
||||
'typescript': {'.ts', '.tsx'},
|
||||
'javascript': {'.js', '.jsx', '.mjs', '.cjs'},
|
||||
'python': {'.py', '.pyi'},
|
||||
'go': {'.go'},
|
||||
'rust': {'.rs'},
|
||||
'java': {'.java'},
|
||||
'ruby': {'.rb'},
|
||||
'php': {'.php'},
|
||||
'csharp': {'.cs'},
|
||||
'cpp': {'.cpp', '.cc', '.cxx', '.hpp', '.h'},
|
||||
'c': {'.c'},
|
||||
'swift': {'.swift'},
|
||||
'kotlin': {'.kt', '.kts'},
|
||||
'scala': {'.scala'},
|
||||
'markdown': {'.md', '.mdx'},
|
||||
'yaml': {'.yml', '.yaml'},
|
||||
'json': {'.json'},
|
||||
'css': {'.css', '.scss', '.sass', '.less'},
|
||||
'html': {'.html', '.htm'},
|
||||
'sql': {'.sql'},
|
||||
'shell': {'.sh', '.bash', '.zsh'},
|
||||
}
|
||||
|
||||
# Config files to detect
|
||||
CONFIG_FILES = {
|
||||
'package.json': 'nodejs',
|
||||
'pyproject.toml': 'python',
|
||||
'setup.py': 'python',
|
||||
'requirements.txt': 'python',
|
||||
'Cargo.toml': 'rust',
|
||||
'go.mod': 'go',
|
||||
'pom.xml': 'java',
|
||||
'build.gradle': 'java',
|
||||
'Gemfile': 'ruby',
|
||||
'composer.json': 'php',
|
||||
'.csproj': 'csharp',
|
||||
'Package.swift': 'swift',
|
||||
'Makefile': 'make',
|
||||
'CMakeLists.txt': 'cmake',
|
||||
}
|
||||
|
||||
# Formatter/linter configs
|
||||
TOOL_CONFIGS = {
|
||||
'.eslintrc': 'eslint',
|
||||
'.eslintrc.js': 'eslint',
|
||||
'.eslintrc.json': 'eslint',
|
||||
'.eslintrc.yml': 'eslint',
|
||||
'eslint.config.js': 'eslint',
|
||||
'.prettierrc': 'prettier',
|
||||
'.prettierrc.js': 'prettier',
|
||||
'.prettierrc.json': 'prettier',
|
||||
'prettier.config.js': 'prettier',
|
||||
'tsconfig.json': 'typescript',
|
||||
'.editorconfig': 'editorconfig',
|
||||
'pyproject.toml': 'python-tools',
|
||||
'.flake8': 'flake8',
|
||||
'.pylintrc': 'pylint',
|
||||
'setup.cfg': 'python-tools',
|
||||
'.rubocop.yml': 'rubocop',
|
||||
'rustfmt.toml': 'rustfmt',
|
||||
'.golangci.yml': 'golangci',
|
||||
}
|
||||
|
||||
|
||||
def should_ignore(path: Path) -> bool:
|
||||
"""Check if path should be ignored."""
|
||||
parts = path.parts
|
||||
return any(part in IGNORE_DIRS or part.startswith('.') for part in parts)
|
||||
|
||||
|
||||
def detect_language(ext: str) -> str:
|
||||
"""Detect language from extension."""
|
||||
for lang, exts in EXTENSIONS.items():
|
||||
if ext in exts:
|
||||
return lang
|
||||
return 'other'
|
||||
|
||||
|
||||
def analyze_directory_structure(root: Path) -> dict:
|
||||
"""Analyze the directory structure."""
|
||||
structure = {
|
||||
'root_dirs': [],
|
||||
'patterns': [],
|
||||
'depth': 0,
|
||||
}
|
||||
|
||||
try:
|
||||
for item in root.iterdir():
|
||||
if item.is_dir() and not should_ignore(item):
|
||||
structure['root_dirs'].append(item.name)
|
||||
except PermissionError:
|
||||
pass
|
||||
|
||||
# Detect common patterns
|
||||
common_patterns = {
|
||||
'src': 'source code',
|
||||
'lib': 'library code',
|
||||
'app': 'application code',
|
||||
'pages': 'page components (Next.js/Nuxt)',
|
||||
'components': 'UI components',
|
||||
'hooks': 'React hooks',
|
||||
'utils': 'utilities',
|
||||
'helpers': 'helper functions',
|
||||
'services': 'service layer',
|
||||
'api': 'API routes/handlers',
|
||||
'routes': 'routing',
|
||||
'controllers': 'MVC controllers',
|
||||
'models': 'data models',
|
||||
'views': 'view templates',
|
||||
'tests': 'test files',
|
||||
'test': 'test files',
|
||||
'__tests__': 'Jest tests',
|
||||
'spec': 'spec files',
|
||||
'docs': 'documentation',
|
||||
'scripts': 'build/utility scripts',
|
||||
'config': 'configuration',
|
||||
'public': 'static assets',
|
||||
'static': 'static assets',
|
||||
'assets': 'assets',
|
||||
}
|
||||
|
||||
for dir_name in structure['root_dirs']:
|
||||
if dir_name in common_patterns:
|
||||
structure['patterns'].append({
|
||||
'dir': dir_name,
|
||||
'purpose': common_patterns[dir_name]
|
||||
})
|
||||
|
||||
return structure
|
||||
|
||||
|
||||
def analyze_files(root: Path) -> dict:
|
||||
"""Analyze file distribution and patterns."""
|
||||
stats = {
|
||||
'total_files': 0,
|
||||
'by_language': Counter(),
|
||||
'by_extension': Counter(),
|
||||
'test_files': 0,
|
||||
'config_files': [],
|
||||
'tool_configs': [],
|
||||
}
|
||||
|
||||
for path in root.rglob('*'):
|
||||
if path.is_file() and not should_ignore(path.relative_to(root)):
|
||||
stats['total_files'] += 1
|
||||
ext = path.suffix.lower()
|
||||
stats['by_extension'][ext] += 1
|
||||
stats['by_language'][detect_language(ext)] += 1
|
||||
|
||||
# Detect test files
|
||||
name = path.name.lower()
|
||||
if 'test' in name or 'spec' in name or path.parent.name in ('tests', 'test', '__tests__', 'spec'):
|
||||
stats['test_files'] += 1
|
||||
|
||||
# Detect config files
|
||||
if path.name in CONFIG_FILES:
|
||||
stats['config_files'].append({
|
||||
'file': path.name,
|
||||
'type': CONFIG_FILES[path.name]
|
||||
})
|
||||
|
||||
# Detect tool configs
|
||||
if path.name in TOOL_CONFIGS:
|
||||
stats['tool_configs'].append({
|
||||
'file': path.name,
|
||||
'tool': TOOL_CONFIGS[path.name]
|
||||
})
|
||||
|
||||
# Convert counters to dicts for JSON serialization
|
||||
stats['by_language'] = dict(stats['by_language'].most_common())
|
||||
stats['by_extension'] = dict(stats['by_extension'].most_common(20))
|
||||
|
||||
return stats
|
||||
|
||||
|
||||
def analyze_package_json(root: Path) -> dict | None:
|
||||
"""Analyze package.json for Node.js projects."""
|
||||
pkg_path = root / 'package.json'
|
||||
if not pkg_path.exists():
|
||||
return None
|
||||
|
||||
try:
|
||||
with open(pkg_path) as f:
|
||||
pkg = json.load(f)
|
||||
except (json.JSONDecodeError, IOError):
|
||||
return None
|
||||
|
||||
analysis = {
|
||||
'name': pkg.get('name', 'unknown'),
|
||||
'scripts': {},
|
||||
'dependencies': [],
|
||||
'devDependencies': [],
|
||||
'frameworks': [],
|
||||
}
|
||||
|
||||
# Extract scripts
|
||||
scripts = pkg.get('scripts', {})
|
||||
important_scripts = ['build', 'test', 'lint', 'format', 'start', 'dev', 'deploy']
|
||||
for script in important_scripts:
|
||||
if script in scripts:
|
||||
analysis['scripts'][script] = scripts[script]
|
||||
|
||||
# Detect frameworks
|
||||
all_deps = {**pkg.get('dependencies', {}), **pkg.get('devDependencies', {})}
|
||||
|
||||
frameworks = {
|
||||
'react': 'React',
|
||||
'next': 'Next.js',
|
||||
'vue': 'Vue.js',
|
||||
'nuxt': 'Nuxt.js',
|
||||
'@angular/core': 'Angular',
|
||||
'svelte': 'Svelte',
|
||||
'express': 'Express.js',
|
||||
'fastify': 'Fastify',
|
||||
'nest': 'NestJS',
|
||||
'prisma': 'Prisma ORM',
|
||||
'drizzle-orm': 'Drizzle ORM',
|
||||
'typeorm': 'TypeORM',
|
||||
'jest': 'Jest',
|
||||
'vitest': 'Vitest',
|
||||
'mocha': 'Mocha',
|
||||
'cypress': 'Cypress',
|
||||
'playwright': 'Playwright',
|
||||
'tailwindcss': 'Tailwind CSS',
|
||||
'eslint': 'ESLint',
|
||||
'prettier': 'Prettier',
|
||||
'typescript': 'TypeScript',
|
||||
}
|
||||
|
||||
for dep, framework in frameworks.items():
|
||||
if dep in all_deps:
|
||||
analysis['frameworks'].append(framework)
|
||||
|
||||
return analysis
|
||||
|
||||
|
||||
def analyze_pyproject(root: Path) -> dict | None:
|
||||
"""Analyze pyproject.toml for Python projects."""
|
||||
pyproject_path = root / 'pyproject.toml'
|
||||
if not pyproject_path.exists():
|
||||
return None
|
||||
|
||||
try:
|
||||
import tomllib
|
||||
with open(pyproject_path, 'rb') as f:
|
||||
pyproject = tomllib.load(f)
|
||||
except ImportError:
|
||||
# Python < 3.11
|
||||
return {'note': 'pyproject.toml exists but tomllib not available'}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
analysis = {
|
||||
'name': pyproject.get('project', {}).get('name', 'unknown'),
|
||||
'tools': [],
|
||||
'frameworks': [],
|
||||
}
|
||||
|
||||
# Detect tools
|
||||
tool_section = pyproject.get('tool', {})
|
||||
if 'black' in tool_section:
|
||||
analysis['tools'].append('black')
|
||||
if 'isort' in tool_section:
|
||||
analysis['tools'].append('isort')
|
||||
if 'ruff' in tool_section:
|
||||
analysis['tools'].append('ruff')
|
||||
if 'pytest' in tool_section:
|
||||
analysis['tools'].append('pytest')
|
||||
if 'mypy' in tool_section:
|
||||
analysis['tools'].append('mypy')
|
||||
|
||||
# Detect frameworks from dependencies
|
||||
deps = pyproject.get('project', {}).get('dependencies', [])
|
||||
deps_str = ' '.join(deps) if isinstance(deps, list) else str(deps)
|
||||
|
||||
if 'django' in deps_str.lower():
|
||||
analysis['frameworks'].append('Django')
|
||||
if 'flask' in deps_str.lower():
|
||||
analysis['frameworks'].append('Flask')
|
||||
if 'fastapi' in deps_str.lower():
|
||||
analysis['frameworks'].append('FastAPI')
|
||||
if 'sqlalchemy' in deps_str.lower():
|
||||
analysis['frameworks'].append('SQLAlchemy')
|
||||
if 'pytest' in deps_str.lower():
|
||||
analysis['frameworks'].append('pytest')
|
||||
|
||||
return analysis
|
||||
|
||||
|
||||
def analyze_git(root: Path) -> dict | None:
|
||||
"""Analyze git configuration."""
|
||||
git_dir = root / '.git'
|
||||
if not git_dir.exists():
|
||||
return None
|
||||
|
||||
analysis = {
|
||||
'has_git': True,
|
||||
'hooks': [],
|
||||
'commit_patterns': [],
|
||||
'branch_pattern': None,
|
||||
}
|
||||
|
||||
# Check for git hooks
|
||||
hooks_dir = git_dir / 'hooks'
|
||||
if hooks_dir.exists():
|
||||
for hook in hooks_dir.iterdir():
|
||||
if hook.is_file() and not hook.name.endswith('.sample'):
|
||||
analysis['hooks'].append(hook.name)
|
||||
|
||||
# Check for husky
|
||||
husky_dir = root / '.husky'
|
||||
if husky_dir.exists():
|
||||
analysis['hooks'].append('husky (pre-commit hooks)')
|
||||
|
||||
# Analyze recent commit messages (via subprocess)
|
||||
try:
|
||||
import subprocess
|
||||
result = subprocess.run(
|
||||
['git', 'log', '--oneline', '-20', '--format=%s'],
|
||||
cwd=root, capture_output=True, text=True, timeout=5
|
||||
)
|
||||
if result.returncode == 0:
|
||||
commits = result.stdout.strip().split('\n')
|
||||
# Detect conventional commits pattern
|
||||
conventional = sum(1 for c in commits if re.match(r'^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?:', c))
|
||||
if conventional > len(commits) * 0.5:
|
||||
analysis['commit_patterns'].append('conventional-commits')
|
||||
# Detect other patterns
|
||||
if any('[' in c and ']' in c for c in commits):
|
||||
analysis['commit_patterns'].append('bracketed-prefix')
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return analysis
|
||||
|
||||
|
||||
def analyze_sensitive_files(root: Path) -> dict:
|
||||
"""Detect potentially sensitive files that should be protected."""
|
||||
sensitive = {
|
||||
'found': [],
|
||||
'patterns_detected': [],
|
||||
'claudeignore_suggestions': [],
|
||||
}
|
||||
|
||||
sensitive_patterns = [
|
||||
('.env', 'Environment variables'),
|
||||
('.env.local', 'Local environment'),
|
||||
('.env.production', 'Production secrets'),
|
||||
('credentials.json', 'Credentials file'),
|
||||
('service-account.json', 'Service account'),
|
||||
('*.pem', 'SSL certificate'),
|
||||
('*.key', 'Private key'),
|
||||
('kubeconfig', 'Kubernetes config'),
|
||||
('.aws/', 'AWS credentials'),
|
||||
('secrets/', 'Secrets directory'),
|
||||
]
|
||||
|
||||
for path in root.rglob('*'):
|
||||
if should_ignore(path.relative_to(root)):
|
||||
continue
|
||||
if not path.is_file():
|
||||
continue
|
||||
|
||||
name = path.name.lower()
|
||||
rel_path = str(path.relative_to(root))
|
||||
|
||||
# Check for sensitive patterns
|
||||
if name.startswith('.env'):
|
||||
sensitive['found'].append(rel_path)
|
||||
sensitive['patterns_detected'].append('env-files')
|
||||
elif 'secret' in name or 'credential' in name:
|
||||
sensitive['found'].append(rel_path)
|
||||
sensitive['patterns_detected'].append('secrets')
|
||||
elif name.endswith(('.pem', '.key', '.p12', '.keystore')):
|
||||
sensitive['found'].append(rel_path)
|
||||
sensitive['patterns_detected'].append('certificates')
|
||||
elif 'kubeconfig' in name:
|
||||
sensitive['found'].append(rel_path)
|
||||
sensitive['patterns_detected'].append('k8s-config')
|
||||
|
||||
# Generate .claudeignore suggestions
|
||||
sensitive['patterns_detected'] = list(set(sensitive['patterns_detected']))
|
||||
if sensitive['patterns_detected']:
|
||||
sensitive['claudeignore_suggestions'] = [
|
||||
'# Auto-detected sensitive patterns',
|
||||
'.env*',
|
||||
'*.pem',
|
||||
'*.key',
|
||||
'*secret*',
|
||||
'*credential*',
|
||||
]
|
||||
|
||||
return sensitive
|
||||
|
||||
|
||||
def analyze_gitignore(root: Path) -> dict:
|
||||
"""Analyze .gitignore for .claudeignore suggestions."""
|
||||
analysis = {
|
||||
'has_gitignore': False,
|
||||
'patterns': [],
|
||||
'claudeignore_additions': [],
|
||||
}
|
||||
|
||||
gitignore_path = root / '.gitignore'
|
||||
if not gitignore_path.exists():
|
||||
return analysis
|
||||
|
||||
analysis['has_gitignore'] = True
|
||||
|
||||
try:
|
||||
content = gitignore_path.read_text()
|
||||
lines = [l.strip() for l in content.split('\n') if l.strip() and not l.startswith('#')]
|
||||
analysis['patterns'] = lines[:20] # First 20 patterns
|
||||
|
||||
# Patterns that should also be in .claudeignore
|
||||
claude_additions = []
|
||||
for line in lines:
|
||||
# Large directories Claude shouldn't read
|
||||
if any(p in line for p in ['node_modules', 'dist', 'build', '.next', 'coverage']):
|
||||
continue # Already in default ignore
|
||||
# Binary/generated files
|
||||
if line.endswith(('.min.js', '.bundle.js', '.map', '.lock')):
|
||||
claude_additions.append(line)
|
||||
# Data files
|
||||
if line.endswith(('.sql', '.db', '.sqlite', '.dump')):
|
||||
claude_additions.append(line)
|
||||
|
||||
analysis['claudeignore_additions'] = claude_additions[:10]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return analysis
|
||||
|
||||
|
||||
def analyze_cicd(root: Path) -> dict:
|
||||
"""Detect CI/CD configuration."""
|
||||
cicd = {
|
||||
'detected': [],
|
||||
'files': [],
|
||||
}
|
||||
|
||||
ci_patterns = {
|
||||
'.github/workflows': 'GitHub Actions',
|
||||
'.gitlab-ci.yml': 'GitLab CI',
|
||||
'Jenkinsfile': 'Jenkins',
|
||||
'.circleci': 'CircleCI',
|
||||
'.travis.yml': 'Travis CI',
|
||||
'azure-pipelines.yml': 'Azure DevOps',
|
||||
'bitbucket-pipelines.yml': 'Bitbucket Pipelines',
|
||||
'.drone.yml': 'Drone CI',
|
||||
'cloudbuild.yaml': 'Google Cloud Build',
|
||||
'appveyor.yml': 'AppVeyor',
|
||||
}
|
||||
|
||||
for pattern, name in ci_patterns.items():
|
||||
check_path = root / pattern
|
||||
if check_path.exists():
|
||||
cicd['detected'].append(name)
|
||||
if check_path.is_file():
|
||||
cicd['files'].append(pattern)
|
||||
elif check_path.is_dir():
|
||||
# List workflow files
|
||||
for f in check_path.glob('*.yml'):
|
||||
cicd['files'].append(str(f.relative_to(root)))
|
||||
for f in check_path.glob('*.yaml'):
|
||||
cicd['files'].append(str(f.relative_to(root)))
|
||||
|
||||
return cicd
|
||||
|
||||
|
||||
def analyze_env_files(root: Path) -> dict:
|
||||
"""Analyze environment variable usage."""
|
||||
analysis = {
|
||||
'env_files': [],
|
||||
'env_vars': [],
|
||||
}
|
||||
|
||||
# Check for .env files
|
||||
env_patterns = ['.env', '.env.example', '.env.local', '.env.development', '.env.production']
|
||||
for pattern in env_patterns:
|
||||
env_file = root / pattern
|
||||
if env_file.exists():
|
||||
analysis['env_files'].append(pattern)
|
||||
# Extract variable names from .env.example if exists
|
||||
if pattern == '.env.example':
|
||||
try:
|
||||
content = env_file.read_text()
|
||||
vars_found = re.findall(r'^([A-Z][A-Z0-9_]+)=', content, re.MULTILINE)
|
||||
analysis['env_vars'] = vars_found[:20] # Limit to 20
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return analysis
|
||||
|
||||
|
||||
def analyze_code_samples(root: Path, language: str) -> dict:
|
||||
"""Extract representative code samples for style analysis."""
|
||||
samples = {
|
||||
'import_style': None,
|
||||
'comment_style': None,
|
||||
'sample_files': [],
|
||||
}
|
||||
|
||||
# Find representative files
|
||||
extensions = EXTENSIONS.get(language, set())
|
||||
if not extensions:
|
||||
return samples
|
||||
|
||||
sample_files = []
|
||||
for ext in extensions:
|
||||
for path in root.rglob(f'*{ext}'):
|
||||
if not should_ignore(path.relative_to(root)):
|
||||
sample_files.append(path)
|
||||
if len(sample_files) >= 5:
|
||||
break
|
||||
if len(sample_files) >= 5:
|
||||
break
|
||||
|
||||
if not sample_files:
|
||||
return samples
|
||||
|
||||
# Analyze first file for patterns
|
||||
try:
|
||||
content = sample_files[0].read_text(errors='ignore')[:5000]
|
||||
|
||||
# Detect import style
|
||||
if language in ('typescript', 'javascript'):
|
||||
if "import type" in content:
|
||||
samples['import_style'] = 'type-imports-separate'
|
||||
elif "from '" in content:
|
||||
samples['import_style'] = 'single-quotes'
|
||||
elif 'from "' in content:
|
||||
samples['import_style'] = 'double-quotes'
|
||||
elif language == 'python':
|
||||
if 'from __future__' in content:
|
||||
samples['import_style'] = 'future-imports'
|
||||
|
||||
# Detect comment style
|
||||
if language in ('typescript', 'javascript'):
|
||||
if '/**' in content and '@param' in content:
|
||||
samples['comment_style'] = 'jsdoc'
|
||||
elif '/**' in content:
|
||||
samples['comment_style'] = 'block-comments'
|
||||
elif language == 'python':
|
||||
if '"""' in content:
|
||||
if ':param' in content:
|
||||
samples['comment_style'] = 'sphinx-docstring'
|
||||
elif 'Args:' in content:
|
||||
samples['comment_style'] = 'google-docstring'
|
||||
else:
|
||||
samples['comment_style'] = 'docstring'
|
||||
|
||||
samples['sample_files'] = [str(f.relative_to(root)) for f in sample_files[:3]]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return samples
|
||||
|
||||
|
||||
def extract_naming_conventions(root: Path) -> dict:
|
||||
"""Extract naming conventions from the codebase."""
|
||||
conventions = {
|
||||
'files': {
|
||||
'patterns': [],
|
||||
'examples': []
|
||||
},
|
||||
'directories': {
|
||||
'patterns': [],
|
||||
'examples': []
|
||||
}
|
||||
}
|
||||
|
||||
file_names = []
|
||||
dir_names = set()
|
||||
|
||||
for path in root.rglob('*'):
|
||||
if should_ignore(path.relative_to(root)):
|
||||
continue
|
||||
if path.is_file():
|
||||
file_names.append(path.stem)
|
||||
elif path.is_dir():
|
||||
dir_names.add(path.name)
|
||||
|
||||
# Analyze file naming patterns
|
||||
patterns = {
|
||||
'kebab-case': re.compile(r'^[a-z]+(-[a-z]+)+$'),
|
||||
'camelCase': re.compile(r'^[a-z]+([A-Z][a-z]+)+$'),
|
||||
'PascalCase': re.compile(r'^[A-Z][a-z]+([A-Z][a-z]+)*$'),
|
||||
'snake_case': re.compile(r'^[a-z]+(_[a-z]+)+$'),
|
||||
}
|
||||
|
||||
pattern_counts = Counter()
|
||||
for name in file_names[:200]: # Sample first 200
|
||||
for pattern_name, regex in patterns.items():
|
||||
if regex.match(name):
|
||||
pattern_counts[pattern_name] += 1
|
||||
break
|
||||
|
||||
if pattern_counts:
|
||||
most_common = pattern_counts.most_common(2)
|
||||
conventions['files']['patterns'] = [p[0] for p in most_common]
|
||||
|
||||
return conventions
|
||||
|
||||
|
||||
def generate_report(root: Path) -> dict:
|
||||
"""Generate a complete analysis report."""
|
||||
report = {
|
||||
'path': str(root.absolute()),
|
||||
'structure': analyze_directory_structure(root),
|
||||
'files': analyze_files(root),
|
||||
'naming': extract_naming_conventions(root),
|
||||
'git': analyze_git(root),
|
||||
'env': analyze_env_files(root),
|
||||
'sensitive': analyze_sensitive_files(root),
|
||||
'gitignore': analyze_gitignore(root),
|
||||
'cicd': analyze_cicd(root),
|
||||
}
|
||||
|
||||
# Add language-specific analysis
|
||||
if (root / 'package.json').exists():
|
||||
report['nodejs'] = analyze_package_json(root)
|
||||
|
||||
if (root / 'pyproject.toml').exists():
|
||||
report['python'] = analyze_pyproject(root)
|
||||
|
||||
# Determine primary language and analyze code samples
|
||||
if report['files']['by_language']:
|
||||
primary = max(report['files']['by_language'].items(), key=lambda x: x[1])
|
||||
report['primary_language'] = primary[0]
|
||||
report['code_samples'] = analyze_code_samples(root, primary[0])
|
||||
|
||||
# Generate recommendations
|
||||
report['recommendations'] = generate_recommendations(report)
|
||||
|
||||
return report
|
||||
|
||||
|
||||
def generate_recommendations(report: dict) -> dict:
|
||||
"""Generate AI-ready configuration recommendations based on analysis."""
|
||||
recs = {
|
||||
'priority': [], # Must-have configs
|
||||
'suggested': [], # Nice-to-have configs
|
||||
'hooks': [], # Recommended hooks
|
||||
}
|
||||
|
||||
# Always recommend CLAUDE.md
|
||||
recs['priority'].append({
|
||||
'config': 'CLAUDE.md',
|
||||
'reason': 'Essential for project-wide coding standards'
|
||||
})
|
||||
|
||||
# Check if rules are needed
|
||||
langs = report['files'].get('by_language', {})
|
||||
if len([l for l in langs if langs[l] > 10 and l != 'other']) > 1:
|
||||
recs['priority'].append({
|
||||
'config': '.claude/rules/',
|
||||
'reason': 'Multi-language project needs language-specific rules'
|
||||
})
|
||||
|
||||
# Check if skills are needed based on frameworks
|
||||
frameworks = []
|
||||
if report.get('nodejs', {}).get('frameworks'):
|
||||
frameworks.extend(report['nodejs']['frameworks'])
|
||||
if report.get('python', {}).get('frameworks'):
|
||||
frameworks.extend(report['python']['frameworks'])
|
||||
|
||||
if any(fw in ['Prisma ORM', 'Drizzle ORM', 'TypeORM', 'SQLAlchemy'] for fw in frameworks):
|
||||
recs['suggested'].append({
|
||||
'config': '.claude/skills/database/',
|
||||
'reason': 'ORM detected - document query patterns and migrations'
|
||||
})
|
||||
|
||||
if any(fw in ['Express.js', 'Fastify', 'NestJS', 'FastAPI', 'Django', 'Flask'] for fw in frameworks):
|
||||
recs['suggested'].append({
|
||||
'config': '.claude/skills/api/',
|
||||
'reason': 'Web framework detected - document API patterns'
|
||||
})
|
||||
|
||||
# Check for test framework
|
||||
test_files = report['files'].get('test_files', 0)
|
||||
if test_files > 5:
|
||||
recs['suggested'].append({
|
||||
'config': '.claude/commands/test.md',
|
||||
'reason': f'{test_files} test files detected - create test command'
|
||||
})
|
||||
|
||||
# Recommend hooks based on tools
|
||||
tools = [c.get('tool') for c in report['files'].get('tool_configs', [])]
|
||||
if 'prettier' in tools or 'eslint' in tools:
|
||||
recs['hooks'].append({
|
||||
'hook': 'PostToolUse format',
|
||||
'reason': 'Auto-format on file edit'
|
||||
})
|
||||
if 'black' in tools or 'ruff' in tools:
|
||||
recs['hooks'].append({
|
||||
'hook': 'PostToolUse format',
|
||||
'reason': 'Python auto-format on file edit'
|
||||
})
|
||||
|
||||
# Git workflow recommendation
|
||||
if report.get('git', {}).get('commit_patterns'):
|
||||
patterns = report['git']['commit_patterns']
|
||||
if 'conventional-commits' in patterns:
|
||||
recs['suggested'].append({
|
||||
'config': '.claude/commands/commit.md',
|
||||
'reason': 'Conventional commits detected - enforce format'
|
||||
})
|
||||
|
||||
return recs
|
||||
|
||||
|
||||
def format_markdown(report: dict) -> str:
|
||||
"""Format report as markdown."""
|
||||
lines = [
|
||||
"# Codebase Analysis Report",
|
||||
"",
|
||||
f"**Path:** `{report['path']}`",
|
||||
"",
|
||||
"## Summary",
|
||||
"",
|
||||
f"- **Total Files:** {report['files']['total_files']}",
|
||||
f"- **Test Files:** {report['files']['test_files']}",
|
||||
f"- **Primary Language:** {report.get('primary_language', 'unknown')}",
|
||||
"",
|
||||
"## Languages",
|
||||
"",
|
||||
]
|
||||
|
||||
for lang, count in report['files']['by_language'].items():
|
||||
lines.append(f"- {lang}: {count} files")
|
||||
|
||||
lines.extend([
|
||||
"",
|
||||
"## Directory Structure",
|
||||
"",
|
||||
"### Root Directories",
|
||||
"",
|
||||
])
|
||||
|
||||
for dir_name in report['structure']['root_dirs']:
|
||||
lines.append(f"- `{dir_name}/`")
|
||||
|
||||
if report['structure']['patterns']:
|
||||
lines.extend([
|
||||
"",
|
||||
"### Detected Patterns",
|
||||
"",
|
||||
])
|
||||
for pattern in report['structure']['patterns']:
|
||||
lines.append(f"- `{pattern['dir']}/` - {pattern['purpose']}")
|
||||
|
||||
if report['files']['tool_configs']:
|
||||
lines.extend([
|
||||
"",
|
||||
"## Development Tools",
|
||||
"",
|
||||
])
|
||||
for config in report['files']['tool_configs']:
|
||||
lines.append(f"- {config['tool']} (`{config['file']}`)")
|
||||
|
||||
if report.get('nodejs'):
|
||||
lines.extend([
|
||||
"",
|
||||
"## Node.js Project",
|
||||
"",
|
||||
f"**Name:** {report['nodejs']['name']}",
|
||||
"",
|
||||
"### Scripts",
|
||||
"",
|
||||
])
|
||||
for script, cmd in report['nodejs']['scripts'].items():
|
||||
lines.append(f"- `{script}`: `{cmd}`")
|
||||
|
||||
if report['nodejs']['frameworks']:
|
||||
lines.extend([
|
||||
"",
|
||||
"### Frameworks & Libraries",
|
||||
"",
|
||||
])
|
||||
for fw in report['nodejs']['frameworks']:
|
||||
lines.append(f"- {fw}")
|
||||
|
||||
if report.get('python'):
|
||||
lines.extend([
|
||||
"",
|
||||
"## Python Project",
|
||||
"",
|
||||
])
|
||||
if report['python'].get('tools'):
|
||||
lines.append("### Tools")
|
||||
for tool in report['python']['tools']:
|
||||
lines.append(f"- {tool}")
|
||||
if report['python'].get('frameworks'):
|
||||
lines.append("")
|
||||
lines.append("### Frameworks")
|
||||
for fw in report['python']['frameworks']:
|
||||
lines.append(f"- {fw}")
|
||||
|
||||
if report.get('git'):
|
||||
lines.extend([
|
||||
"",
|
||||
"## Git Configuration",
|
||||
"",
|
||||
])
|
||||
if report['git'].get('hooks'):
|
||||
lines.append("### Hooks")
|
||||
for hook in report['git']['hooks']:
|
||||
lines.append(f"- {hook}")
|
||||
if report['git'].get('commit_patterns'):
|
||||
lines.append("")
|
||||
lines.append("### Commit Patterns Detected")
|
||||
for pattern in report['git']['commit_patterns']:
|
||||
lines.append(f"- {pattern}")
|
||||
|
||||
if report.get('env', {}).get('env_files'):
|
||||
lines.extend([
|
||||
"",
|
||||
"## Environment Files",
|
||||
"",
|
||||
])
|
||||
for env_file in report['env']['env_files']:
|
||||
lines.append(f"- `{env_file}`")
|
||||
if report['env'].get('env_vars'):
|
||||
lines.append("")
|
||||
lines.append("### Environment Variables")
|
||||
for var in report['env']['env_vars'][:10]:
|
||||
lines.append(f"- `{var}`")
|
||||
|
||||
if report.get('code_samples'):
|
||||
samples = report['code_samples']
|
||||
if samples.get('import_style') or samples.get('comment_style'):
|
||||
lines.extend([
|
||||
"",
|
||||
"## Code Style Detected",
|
||||
"",
|
||||
])
|
||||
if samples.get('import_style'):
|
||||
lines.append(f"- **Import style:** {samples['import_style']}")
|
||||
if samples.get('comment_style'):
|
||||
lines.append(f"- **Comment style:** {samples['comment_style']}")
|
||||
if samples.get('sample_files'):
|
||||
lines.append("")
|
||||
lines.append("**Sample files for reference:**")
|
||||
for f in samples['sample_files']:
|
||||
lines.append(f"- `{f}`")
|
||||
|
||||
# CI/CD section
|
||||
if report.get('cicd', {}).get('detected'):
|
||||
lines.extend([
|
||||
"",
|
||||
"## CI/CD",
|
||||
"",
|
||||
])
|
||||
for ci in report['cicd']['detected']:
|
||||
lines.append(f"- {ci}")
|
||||
if report['cicd'].get('files'):
|
||||
lines.append("")
|
||||
lines.append("**Config files:**")
|
||||
for f in report['cicd']['files'][:5]:
|
||||
lines.append(f"- `{f}`")
|
||||
|
||||
# Security section
|
||||
if report.get('sensitive', {}).get('found'):
|
||||
lines.extend([
|
||||
"",
|
||||
"## Security Warning",
|
||||
"",
|
||||
"**Sensitive files detected** - Add to .claudeignore:",
|
||||
"",
|
||||
])
|
||||
for f in report['sensitive']['found'][:10]:
|
||||
lines.append(f"- `{f}`")
|
||||
|
||||
if report['sensitive'].get('claudeignore_suggestions'):
|
||||
lines.extend([
|
||||
"",
|
||||
"**Suggested .claudeignore:**",
|
||||
"```",
|
||||
])
|
||||
for pattern in report['sensitive']['claudeignore_suggestions']:
|
||||
lines.append(pattern)
|
||||
lines.append("```")
|
||||
|
||||
# Recommendations section
|
||||
if report.get('recommendations'):
|
||||
recs = report['recommendations']
|
||||
lines.extend([
|
||||
"",
|
||||
"---",
|
||||
"",
|
||||
"## AI-Ready Configuration Recommendations",
|
||||
"",
|
||||
])
|
||||
|
||||
if recs.get('priority'):
|
||||
lines.append("### Priority (Required)")
|
||||
for rec in recs['priority']:
|
||||
lines.append(f"- **{rec['config']}** - {rec['reason']}")
|
||||
lines.append("")
|
||||
|
||||
if recs.get('suggested'):
|
||||
lines.append("### Suggested")
|
||||
for rec in recs['suggested']:
|
||||
lines.append(f"- **{rec['config']}** - {rec['reason']}")
|
||||
lines.append("")
|
||||
|
||||
if recs.get('hooks'):
|
||||
lines.append("### Hooks to Configure")
|
||||
for rec in recs['hooks']:
|
||||
lines.append(f"- **{rec['hook']}** - {rec['reason']}")
|
||||
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Analyze a codebase for AI-ready conversion')
|
||||
parser.add_argument('path', nargs='?', default='.', help='Path to analyze (default: current directory)')
|
||||
parser.add_argument('--output', '-o', choices=['json', 'markdown'], default='markdown',
|
||||
help='Output format (default: markdown)')
|
||||
|
||||
args = parser.parse_args()
|
||||
root = Path(args.path).resolve()
|
||||
|
||||
if not root.exists():
|
||||
print(f"Error: Path does not exist: {root}")
|
||||
return 1
|
||||
|
||||
report = generate_report(root)
|
||||
|
||||
if args.output == 'json':
|
||||
print(json.dumps(report, indent=2))
|
||||
else:
|
||||
print(format_markdown(report))
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
exit(main())
|
||||
@@ -0,0 +1,165 @@
|
||||
---
|
||||
name: resource-scout
|
||||
description: Search and discover Claude Code skills and MCP servers from marketplaces, GitHub repositories, and registries. Use when (1) user asks to find skills for a specific task, (2) looking for MCP servers to connect external tools, (3) user mentions "find skill", "search MCP", "discover tools", or "what skills exist for X", (4) before creating a custom skill to check if one already exists.
|
||||
---
|
||||
|
||||
# Resource Scout
|
||||
|
||||
Search and discover existing Claude Code skills and MCP servers before building custom solutions.
|
||||
|
||||
## Quick Search Strategy
|
||||
|
||||
**For Skills:**
|
||||
1. WebSearch: `site:skillsmp.com [topic]` or `claude skill [topic]`
|
||||
2. Check GitHub: `awesome-claude-skills [topic]`
|
||||
3. Browse: skillhub.club, claudeskills.info
|
||||
|
||||
**For MCP:**
|
||||
1. WebSearch: `MCP server [tool/service name]`
|
||||
2. Check: glama.ai/mcp/servers, mcpmarket.com
|
||||
3. Official: github.com/modelcontextprotocol/servers
|
||||
|
||||
## Skill Search Workflow
|
||||
|
||||
### Step 1: Define Need
|
||||
|
||||
Before searching, clarify:
|
||||
- What task needs to be accomplished?
|
||||
- What tools/services are involved?
|
||||
- Is it a common pattern (git, testing, API) or domain-specific?
|
||||
|
||||
### Step 2: Search Marketplaces
|
||||
|
||||
**Primary sources (largest catalogs):**
|
||||
|
||||
| Source | URL | Best For |
|
||||
|--------|-----|----------|
|
||||
| SkillsMP | skillsmp.com | 71000+ skills, long-tail search |
|
||||
| SkillHub.club | skillhub.club | AI-evaluated, quality filter |
|
||||
| Claude Skills Hub | claudeskills.info | UI-friendly browsing |
|
||||
|
||||
**Search patterns:**
|
||||
```
|
||||
# On SkillsMP
|
||||
[domain] skill → "marketing skill", "database skill"
|
||||
[framework] claude → "react claude", "fastapi claude"
|
||||
[task] automation → "deployment automation"
|
||||
```
|
||||
|
||||
### Step 3: Search GitHub
|
||||
|
||||
**Curated lists:**
|
||||
- `github.com/keyuyuan/skillhub-awesome-skills` - 精选清单
|
||||
- `github.com/VoltAgent/awesome-claude-skills` - 生态大全
|
||||
- `github.com/ComposioHQ/awesome-claude-skills` - 大量通用技能
|
||||
|
||||
**Ready-to-use repositories:**
|
||||
- `github.com/alirezarezvani/claude-skills` - Content/Marketing
|
||||
- `github.com/gked2121/claude-skills` - Workflow思维
|
||||
- `github.com/Microck/ordinary-claude-skills` - 超大集合
|
||||
- `github.com/sickn33/antigravity-awesome-skills` - 结构化
|
||||
|
||||
**Search command:**
|
||||
```bash
|
||||
# Use WebSearch tool
|
||||
site:github.com "claude skill" [topic]
|
||||
site:github.com "SKILL.md" [topic]
|
||||
```
|
||||
|
||||
### Step 4: Evaluate & Install
|
||||
|
||||
When skill found:
|
||||
1. Check last update date (prefer recent)
|
||||
2. Review SKILL.md for quality
|
||||
3. Check if has scripts/references
|
||||
4. Install with skill-downloader or manual copy
|
||||
|
||||
## MCP Server Search Workflow
|
||||
|
||||
### Step 1: Identify Integration Need
|
||||
|
||||
Common patterns:
|
||||
- Database access → postgres, mysql, sqlite MCP
|
||||
- GitHub workflow → github MCP
|
||||
- Cloud services → AWS, GCP, Azure MCPs
|
||||
- Communication → slack, discord MCPs
|
||||
- File systems → filesystem MCP
|
||||
|
||||
### Step 2: Search Official Sources
|
||||
|
||||
**Primary:**
|
||||
- Official registry: `registry.modelcontextprotocol.io`
|
||||
- Official repo: `github.com/modelcontextprotocol/servers`
|
||||
|
||||
**Directories:**
|
||||
| Source | URL | Features |
|
||||
|--------|-----|----------|
|
||||
| Glama | glama.ai/mcp/servers | Stars, downloads, updates |
|
||||
| MCP Market | mcpmarket.com | Skills + MCP combined |
|
||||
| mcpservers.org | mcpservers.org | Categorized |
|
||||
| PulseMCP | pulsemcp.com/servers | Daily updates |
|
||||
| Smithery | smithery.ai | Registry/distribution |
|
||||
|
||||
### Step 3: Search GitHub
|
||||
|
||||
```bash
|
||||
# Use WebSearch tool
|
||||
site:github.com "mcp server" [service]
|
||||
site:github.com "@modelcontextprotocol" [service]
|
||||
```
|
||||
|
||||
**Awesome lists:**
|
||||
- `github.com/punkpeye/awesome-mcp-servers`
|
||||
- `github.com/wong2/awesome-mcp-servers`
|
||||
|
||||
### Step 4: Verify & Configure
|
||||
|
||||
When MCP found:
|
||||
1. Check compatibility (stdio vs HTTP)
|
||||
2. Review required environment variables
|
||||
3. Test connection locally
|
||||
4. Add to `.claude/settings.json`
|
||||
|
||||
## Search by Category
|
||||
|
||||
### Development Tools
|
||||
```
|
||||
Skills: "code review skill", "git commit skill", "testing skill"
|
||||
MCP: "github mcp", "gitlab mcp", "jira mcp"
|
||||
```
|
||||
|
||||
### Databases
|
||||
```
|
||||
Skills: "database skill", "sql skill", "migration skill"
|
||||
MCP: "postgres mcp", "mysql mcp", "mongodb mcp"
|
||||
```
|
||||
|
||||
### Content & Marketing
|
||||
```
|
||||
Skills: "content creator skill", "seo skill", "social media skill"
|
||||
MCP: "wordpress mcp", "notion mcp"
|
||||
```
|
||||
|
||||
### Cloud & DevOps
|
||||
```
|
||||
Skills: "deployment skill", "kubernetes skill", "terraform skill"
|
||||
MCP: "aws mcp", "gcp mcp", "azure mcp"
|
||||
```
|
||||
|
||||
### AI & Data
|
||||
```
|
||||
Skills: "data analysis skill", "ml skill"
|
||||
MCP: "openai mcp", "huggingface mcp"
|
||||
```
|
||||
|
||||
## Complete Source Reference
|
||||
|
||||
See [references/sources.md](references/sources.md) for full directory of all skill and MCP sources with detailed descriptions.
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Search before build** - Always check existing resources first
|
||||
2. **Prefer maintained** - Choose skills with recent updates
|
||||
3. **Check quality** - Review SKILL.md structure and content
|
||||
4. **Consider combining** - Multiple simple skills > one complex custom
|
||||
5. **Verify security** - Review MCP permissions and token scopes
|
||||
@@ -0,0 +1,250 @@
|
||||
# Complete Resource Directory
|
||||
|
||||
Full directory of all skill and MCP discovery sources.
|
||||
|
||||
## Table of Contents
|
||||
- [Skills: Marketplaces & Directories](#skills-marketplaces--directories)
|
||||
- [Skills: GitHub Awesome Lists](#skills-github-awesome-lists)
|
||||
- [Skills: Ready-to-Use Repositories](#skills-ready-to-use-repositories)
|
||||
- [Skills: Tools & Documentation](#skills-tools--documentation)
|
||||
- [MCP: Official Resources](#mcp-official-resources)
|
||||
- [MCP: Marketplaces & Directories](#mcp-marketplaces--directories)
|
||||
- [MCP: GitHub Lists](#mcp-github-lists)
|
||||
|
||||
---
|
||||
|
||||
## Skills: Marketplaces & Directories
|
||||
|
||||
### SkillsMP
|
||||
- **URL**: https://skillsmp.com/
|
||||
- **Type**: Large marketplace
|
||||
- **Size**: 71,000+ skills
|
||||
- **Features**: Search by author, popularity, category
|
||||
- **Best for**: Long-tail search, discovering niche skills
|
||||
- **Docs**: https://skillsmp.com/docs
|
||||
|
||||
### SkillHub.club
|
||||
- **URL**: https://www.skillhub.club/
|
||||
- **Type**: Curated marketplace
|
||||
- **Features**: AI-evaluated quality, stars/ratings
|
||||
- **Best for**: Finding verified, quality skills
|
||||
|
||||
### agent-skills.md
|
||||
- **URL**: https://agent-skills.md/
|
||||
- **Type**: Online directory
|
||||
- **Features**: Direct install commands, file structure preview
|
||||
- **Best for**: Quick browse and install
|
||||
|
||||
### Claude Skills Hub
|
||||
- **URL**: https://claudeskills.info/
|
||||
- **Type**: Online directory
|
||||
- **Features**: User-friendly UI, category browsing
|
||||
- **Best for**: Discovery, "window shopping"
|
||||
|
||||
### MCP Market (Skills Section)
|
||||
- **URL**: https://mcpmarket.com/
|
||||
- **Type**: Combined marketplace
|
||||
- **Features**: Skills + MCP servers in one place
|
||||
- **Best for**: Finding both skills and related MCPs
|
||||
|
||||
### AwesomeClaude Visual Directory
|
||||
- **URL**: https://awesomeclaude.ai/awesome-claude-skills
|
||||
- **Type**: Visual browser
|
||||
- **Features**: UI for ComposioHQ collection
|
||||
- **Best for**: Non-technical users, visual browsing
|
||||
|
||||
---
|
||||
|
||||
## Skills: GitHub Awesome Lists
|
||||
|
||||
### Skillhub Awesome Skills
|
||||
- **URL**: https://github.com/keyuyuan/skillhub-awesome-skills
|
||||
- **Type**: Curated list
|
||||
- **Features**: Categorized, verified skills
|
||||
- **Best for**: Quick discovery of proven skills
|
||||
|
||||
### Awesome Claude Skills (VoltAgent)
|
||||
- **URL**: https://github.com/VoltAgent/awesome-claude-skills
|
||||
- **Type**: Ecosystem overview
|
||||
- **Features**: Broad coverage, resource compilation
|
||||
- **Best for**: Understanding the ecosystem
|
||||
|
||||
### Awesome Claude Skills (travisvn)
|
||||
- **URL**: https://github.com/travisvn/awesome-claude-skills
|
||||
- **Type**: Curated list
|
||||
- **Features**: Alternative curation perspective
|
||||
- **Best for**: Cross-reference validation
|
||||
|
||||
### Awesome Claude Skills (ComposioHQ)
|
||||
- **URL**: https://github.com/ComposioHQ/awesome-claude-skills
|
||||
- **Type**: Large collection
|
||||
- **Features**: High volume, general/utility skills
|
||||
- **Best for**: Finding common utilities
|
||||
|
||||
### Awesome Agent Skills (heilcheng)
|
||||
- **URL**: https://github.com/heilcheng/awesome-agent-skills
|
||||
- **Type**: Multi-platform list
|
||||
- **Features**: Covers Claude, Codex, Copilot
|
||||
- **Best for**: Cross-platform skill discovery
|
||||
|
||||
---
|
||||
|
||||
## Skills: Ready-to-Use Repositories
|
||||
|
||||
### alirezarezvani/claude-skills
|
||||
- **URL**: https://github.com/alirezarezvani/claude-skills
|
||||
- **Focus**: Content Creator, Marketing
|
||||
- **Quality**: Production-ready
|
||||
- **Best for**: Direct workflow integration
|
||||
|
||||
### gked2121/claude-skills
|
||||
- **URL**: https://github.com/gked2121/claude-skills
|
||||
- **Focus**: Workflow-oriented, creation pipelines
|
||||
- **Quality**: Well-structured
|
||||
- **Best for**: Understanding workflow patterns
|
||||
|
||||
### Microck/ordinary-claude-skills
|
||||
- **URL**: https://github.com/Microck/ordinary-claude-skills
|
||||
- **Focus**: Large general collection
|
||||
- **Quality**: Variable
|
||||
- **Best for**: Mining for specific needs
|
||||
|
||||
### sickn33/antigravity-awesome-skills
|
||||
- **URL**: https://github.com/sickn33/antigravity-awesome-skills
|
||||
- **Focus**: Registry-style organization
|
||||
- **Quality**: Highly structured
|
||||
- **Best for**: Easy browsing and copying
|
||||
|
||||
### synapz-org/marketing-ops-hub
|
||||
- **URL**: https://github.com/synapz-org/marketing-ops-hub
|
||||
- **Focus**: Marketing, operations, growth
|
||||
- **Quality**: Domain-specific
|
||||
- **Best for**: Marketing automation workflows
|
||||
|
||||
### m2ai-portfolio/claude-skills
|
||||
- **URL**: https://github.com/m2ai-portfolio/claude-skills
|
||||
- **Focus**: Creator, growth, writing
|
||||
- **Quality**: Platform-oriented
|
||||
- **Best for**: Content creation workflows
|
||||
|
||||
---
|
||||
|
||||
## Skills: Tools & Documentation
|
||||
|
||||
### SkillHub Desktop
|
||||
- **URL**: https://github.com/skillhub-club/skillhub-desktop
|
||||
- **Type**: Desktop manager
|
||||
- **Features**: Cross-tool sync (Claude/Cursor)
|
||||
- **Best for**: Team skill management
|
||||
|
||||
### Official Claude Skills Docs
|
||||
- **URL**: https://code.claude.com/docs/en/skills
|
||||
- **Type**: Official documentation
|
||||
- **Content**: Structure, rules, best practices
|
||||
- **Best for**: Creating/modifying skills
|
||||
|
||||
### Official OpenAI Codex Skills Docs
|
||||
- **URL**: https://developers.openai.com/codex/skills/
|
||||
- **Type**: Official documentation
|
||||
- **Content**: Codex/ChatGPT skill usage
|
||||
- **Best for**: Cross-platform compatibility
|
||||
|
||||
---
|
||||
|
||||
## MCP: Official Resources
|
||||
|
||||
### MCP Official Servers Repository
|
||||
- **URL**: https://github.com/modelcontextprotocol/servers
|
||||
- **Type**: Official reference
|
||||
- **Content**: Reference implementations, community index
|
||||
- **Best for**: Starting point, official servers
|
||||
|
||||
### MCP Official Examples
|
||||
- **URL**: https://modelcontextprotocol.io/examples
|
||||
- **Type**: Official examples
|
||||
- **Content**: Integration examples, tutorials
|
||||
- **Best for**: Learning MCP patterns
|
||||
|
||||
### MCP Registry (Repository)
|
||||
- **URL**: https://github.com/modelcontextprotocol/registry
|
||||
- **Type**: Registry service code
|
||||
- **Content**: Self-hosted registry implementation
|
||||
- **Best for**: Enterprise internal distribution
|
||||
|
||||
### MCP Registry (Web)
|
||||
- **URL**: https://registry.modelcontextprotocol.io/
|
||||
- **Type**: Official registry
|
||||
- **Content**: Browse registered MCPs
|
||||
- **Best for**: Finding official/verified MCPs
|
||||
|
||||
---
|
||||
|
||||
## MCP: Marketplaces & Directories
|
||||
|
||||
### Glama MCP Directory
|
||||
- **URL**: https://glama.ai/mcp/servers
|
||||
- **Type**: Large directory
|
||||
- **Features**: Stars, downloads, last updated
|
||||
- **Best for**: Finding popular, maintained servers
|
||||
|
||||
### Glama MCP Entry
|
||||
- **URL**: https://glama.ai/mcp
|
||||
- **Type**: Portal
|
||||
- **Features**: Servers, clients, tools navigation
|
||||
- **Best for**: Team unified entry point
|
||||
|
||||
### MCP Market
|
||||
- **URL**: https://mcpmarket.com/
|
||||
- **Type**: Marketplace
|
||||
- **Features**: MCP servers + clients
|
||||
- **Best for**: Combined skill/MCP discovery
|
||||
|
||||
### Awesome MCP Servers (mcpservers.org)
|
||||
- **URL**: https://mcpservers.org/
|
||||
- **Type**: Categorized directory
|
||||
- **Features**: Official/Remote/Clients categories
|
||||
- **Best for**: Structured browsing
|
||||
|
||||
### PulseMCP Servers
|
||||
- **URL**: https://www.pulsemcp.com/servers
|
||||
- **Type**: Index
|
||||
- **Features**: Full index, daily updates
|
||||
- **Best for**: Tracking new arrivals
|
||||
|
||||
### MCP.so Servers
|
||||
- **URL**: https://mcp.so/servers
|
||||
- **Type**: Directory
|
||||
- **Features**: Multi-language (CN/EN)
|
||||
- **Best for**: Wide coverage
|
||||
|
||||
### Smithery
|
||||
- **URL**: https://smithery.ai/
|
||||
- **Type**: Registry/distribution
|
||||
- **Features**: Publish, discover, install
|
||||
- **Best for**: "App store" experience
|
||||
|
||||
---
|
||||
|
||||
## MCP: GitHub Lists
|
||||
|
||||
### punkpeye/awesome-mcp-servers
|
||||
- **URL**: https://github.com/punkpeye/awesome-mcp-servers
|
||||
- **Type**: Awesome list
|
||||
- **Features**: Domain categorization
|
||||
- **Best for**: Classic curated list
|
||||
|
||||
### wong2/awesome-mcp-servers
|
||||
- **URL**: https://github.com/wong2/awesome-mcp-servers
|
||||
- **Type**: Awesome list
|
||||
- **Features**: Alternative curation
|
||||
- **Best for**: Additional discoveries
|
||||
|
||||
---
|
||||
|
||||
## Enterprise Resources
|
||||
|
||||
### GitHub MCP Registry Configuration
|
||||
- **URL**: https://docs.github.com/en/copilot/how-tos/administer-copilot/manage-mcp-usage/configure-mcp-registry
|
||||
- **Type**: Documentation
|
||||
- **Content**: Organization-level MCP registry setup
|
||||
- **Best for**: Enterprise governance, compliance
|
||||
@@ -11,7 +11,7 @@
|
||||
# W = workflow name (e.g., content-creator, marketing-pro)
|
||||
# S = skill name (e.g., docx, canvas-design)
|
||||
|
||||
.PHONY: help list update-skill update-workflow update-all dry-run clean validate validate-fast
|
||||
.PHONY: help list update-skill update-workflow update-all dry-run clean validate validate-fast crawl-claude-docs merge-claude-docs
|
||||
|
||||
PYTHON := python3
|
||||
SCRIPTS_DIR := scripts
|
||||
@@ -134,3 +134,30 @@ validate-json:
|
||||
clean:
|
||||
@find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
|
||||
@echo "Cleaned __pycache__ directories"
|
||||
|
||||
# Crawl Claude Code documentation
|
||||
crawl-claude-docs:
|
||||
@echo "Crawling Claude Code documentation..."
|
||||
@cd claude-code-docs && uv run --with requests --with beautifulsoup4 --with markdownify python crawl_docs.py
|
||||
|
||||
# Merge Claude Code docs into single file for LLMs
|
||||
merge-claude-docs:
|
||||
@echo "Merging Claude Code documentation..."
|
||||
@cd claude-code-docs && { \
|
||||
echo "# Claude Code Documentation"; \
|
||||
echo ""; \
|
||||
echo "Source: https://code.claude.com/docs"; \
|
||||
echo "Generated: $$(date -u +%Y-%m-%dT%H:%M:%SZ)"; \
|
||||
echo ""; \
|
||||
echo "---"; \
|
||||
echo ""; \
|
||||
for f in docs/*.md; do \
|
||||
[ -f "$$f" ] && [ "$$(basename $$f)" != "INDEX.md" ] && { \
|
||||
cat "$$f"; \
|
||||
echo ""; \
|
||||
echo "---"; \
|
||||
echo ""; \
|
||||
}; \
|
||||
done; \
|
||||
} > claude-code-llms.txt
|
||||
@echo "Created claude-code-docs/claude-code-llms.txt"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,312 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Claude Code 文档爬虫脚本
|
||||
将 https://code.claude.com/docs 的文档爬取并转换为 Markdown 文件
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import requests
|
||||
from urllib.parse import urljoin, urlparse
|
||||
from bs4 import BeautifulSoup
|
||||
from markdownify import markdownify as md
|
||||
|
||||
# 配置
|
||||
BASE_URL = "https://code.claude.com/docs"
|
||||
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
OUTPUT_DIR = os.path.join(SCRIPT_DIR, "docs")
|
||||
LANGUAGE = "en" # 爬取英文文档
|
||||
|
||||
# 文档页面列表
|
||||
DOC_PAGES = [
|
||||
# Getting started
|
||||
"overview",
|
||||
"quickstart",
|
||||
"common-workflows",
|
||||
"changelog",
|
||||
# Outside of the terminal
|
||||
"claude-code-on-the-web",
|
||||
"desktop",
|
||||
"chrome",
|
||||
"vs-code",
|
||||
"jetbrains",
|
||||
"github-actions",
|
||||
"gitlab-ci-cd",
|
||||
"slack",
|
||||
# Build with Claude Code
|
||||
"sub-agents",
|
||||
"plugins",
|
||||
"discover-plugins",
|
||||
"skills",
|
||||
"output-styles",
|
||||
"hooks-guide",
|
||||
"headless",
|
||||
"mcp",
|
||||
"troubleshooting",
|
||||
# Deployment
|
||||
"third-party-integrations",
|
||||
"amazon-bedrock",
|
||||
"google-vertex-ai",
|
||||
"microsoft-foundry",
|
||||
"network-config",
|
||||
"llm-gateway",
|
||||
"devcontainer",
|
||||
"sandboxing",
|
||||
# Administration
|
||||
"setup",
|
||||
"iam",
|
||||
"security",
|
||||
"data-usage",
|
||||
"monitoring-usage",
|
||||
"costs",
|
||||
"analytics",
|
||||
"plugin-marketplaces",
|
||||
# Configuration
|
||||
"settings",
|
||||
"terminal-config",
|
||||
"model-config",
|
||||
"memory",
|
||||
"statusline",
|
||||
# Reference
|
||||
"cli-reference",
|
||||
"interactive-mode",
|
||||
"slash-commands",
|
||||
"checkpointing",
|
||||
"hooks",
|
||||
"plugins-reference",
|
||||
# Resources
|
||||
"legal-and-compliance",
|
||||
]
|
||||
|
||||
# HTTP 请求头
|
||||
HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
|
||||
"Accept-Language": "en-US,en;q=0.5",
|
||||
}
|
||||
|
||||
|
||||
def fetch_page(url: str) -> str | None:
|
||||
"""获取页面 HTML 内容"""
|
||||
try:
|
||||
response = requests.get(url, headers=HEADERS, timeout=30)
|
||||
response.raise_for_status()
|
||||
return response.text
|
||||
except requests.RequestException as e:
|
||||
print(f" ❌ 获取失败: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def extract_main_content(html: str) -> tuple[str, str]:
|
||||
"""从 HTML 中提取主要内容区域,返回 (title, content_html)"""
|
||||
soup = BeautifulSoup(html, "html.parser")
|
||||
|
||||
# 提取标题
|
||||
title = ""
|
||||
title_tag = soup.find("h1")
|
||||
if title_tag:
|
||||
title = title_tag.get_text(strip=True)
|
||||
|
||||
# 尝试找到主内容区域 - 通常在 article 或 main 标签中
|
||||
main_content = None
|
||||
|
||||
# 尝试不同的选择器
|
||||
selectors = [
|
||||
"article",
|
||||
"main",
|
||||
"[role='main']",
|
||||
".docs-content",
|
||||
".content",
|
||||
"#content",
|
||||
".markdown-body",
|
||||
]
|
||||
|
||||
for selector in selectors:
|
||||
main_content = soup.select_one(selector)
|
||||
if main_content:
|
||||
break
|
||||
|
||||
# 如果没找到,使用 body
|
||||
if not main_content:
|
||||
main_content = soup.find("body")
|
||||
|
||||
if main_content:
|
||||
# 移除不需要的元素
|
||||
for element in main_content.select("nav, header, footer, script, style, .sidebar, .toc, .navigation"):
|
||||
element.decompose()
|
||||
|
||||
return title, str(main_content)
|
||||
|
||||
return title, ""
|
||||
|
||||
|
||||
def html_to_markdown(html: str, base_url: str) -> str:
|
||||
"""将 HTML 转换为 Markdown"""
|
||||
# 先用 BeautifulSoup 清理 HTML
|
||||
soup = BeautifulSoup(html, "html.parser")
|
||||
|
||||
# 移除按钮和交互元素
|
||||
for btn in soup.select("button, .copy-button, [data-copy], .ask-ai"):
|
||||
btn.decompose()
|
||||
|
||||
# 移除 "Copy" 和 "Ask AI" 文本节点
|
||||
for text_node in soup.find_all(string=re.compile(r"^(Copy|Ask AI)$")):
|
||||
if text_node.parent and text_node.parent.name not in ["code", "pre"]:
|
||||
text_node.extract()
|
||||
|
||||
# 修复代码块语言
|
||||
for code in soup.select("code"):
|
||||
classes = code.get("class", [])
|
||||
for cls in classes:
|
||||
if "language-shiki" in cls or cls == "shiki":
|
||||
# 尝试从父元素或 data 属性获取真实语言
|
||||
code["class"] = [c.replace("shiki", "bash") for c in classes]
|
||||
|
||||
html = str(soup)
|
||||
|
||||
# 使用 markdownify 转换
|
||||
markdown = md(
|
||||
html,
|
||||
heading_style="ATX",
|
||||
bullets="-",
|
||||
code_language_callback=lambda el: el.get("class", [""])[0].replace("language-", "") if el.get("class") else "",
|
||||
)
|
||||
|
||||
# 清理 shiki 语言标记
|
||||
markdown = re.sub(r"```shiki\b", "```bash", markdown)
|
||||
markdown = re.sub(r"```language-shiki\b", "```bash", markdown)
|
||||
|
||||
# 移除残留的 "Copy" 和 "Ask AI"
|
||||
markdown = re.sub(r"\nCopy\n", "\n", markdown)
|
||||
markdown = re.sub(r"\nAsk AI\n", "\n", markdown)
|
||||
markdown = re.sub(r"^Copy$", "", markdown, flags=re.MULTILINE)
|
||||
markdown = re.sub(r"^Ask AI$", "", markdown, flags=re.MULTILINE)
|
||||
|
||||
# 清理多余的空行
|
||||
markdown = re.sub(r"\n{3,}", "\n\n", markdown)
|
||||
|
||||
# 清理行首行尾空白
|
||||
lines = [line.rstrip() for line in markdown.split("\n")]
|
||||
markdown = "\n".join(lines)
|
||||
|
||||
return markdown.strip()
|
||||
|
||||
|
||||
def save_markdown(content: str, filename: str):
|
||||
"""保存 Markdown 文件"""
|
||||
filepath = os.path.join(OUTPUT_DIR, filename)
|
||||
with open(filepath, "w", encoding="utf-8") as f:
|
||||
f.write(content)
|
||||
print(f" ✅ 已保存: {filename}")
|
||||
|
||||
|
||||
def crawl_page(page_slug: str) -> bool:
|
||||
"""爬取单个页面"""
|
||||
url = f"{BASE_URL}/{LANGUAGE}/{page_slug}"
|
||||
print(f"\n📄 正在爬取: {page_slug}")
|
||||
print(f" URL: {url}")
|
||||
|
||||
html = fetch_page(url)
|
||||
if not html:
|
||||
return False
|
||||
|
||||
title, content_html = extract_main_content(html)
|
||||
if not content_html:
|
||||
print(" ⚠️ 未找到内容")
|
||||
return False
|
||||
|
||||
markdown = html_to_markdown(content_html, url)
|
||||
|
||||
# 添加文档头信息
|
||||
header = f"""---
|
||||
source: {url}
|
||||
title: {title}
|
||||
---
|
||||
|
||||
"""
|
||||
|
||||
full_content = header + markdown
|
||||
|
||||
# 保存文件
|
||||
filename = f"{page_slug}.md"
|
||||
save_markdown(full_content, filename)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def create_index(successful_pages: list[str]):
|
||||
"""创建索引文件"""
|
||||
index_content = """---
|
||||
title: Claude Code Documentation Index
|
||||
---
|
||||
|
||||
# Claude Code 文档索引
|
||||
|
||||
此文件夹包含从 https://code.claude.com/docs 爬取的文档。
|
||||
|
||||
## 文档列表
|
||||
|
||||
"""
|
||||
|
||||
categories = {
|
||||
"Getting Started": ["overview", "quickstart", "common-workflows", "changelog"],
|
||||
"Outside of the Terminal": ["claude-code-on-the-web", "desktop", "chrome", "vs-code", "jetbrains", "github-actions", "gitlab-ci-cd", "slack"],
|
||||
"Build with Claude Code": ["sub-agents", "plugins", "discover-plugins", "skills", "output-styles", "hooks-guide", "headless", "mcp", "troubleshooting"],
|
||||
"Deployment": ["third-party-integrations", "amazon-bedrock", "google-vertex-ai", "microsoft-foundry", "network-config", "llm-gateway", "devcontainer", "sandboxing"],
|
||||
"Administration": ["setup", "iam", "security", "data-usage", "monitoring-usage", "costs", "analytics", "plugin-marketplaces"],
|
||||
"Configuration": ["settings", "terminal-config", "model-config", "memory", "statusline"],
|
||||
"Reference": ["cli-reference", "interactive-mode", "slash-commands", "checkpointing", "hooks", "plugins-reference"],
|
||||
"Resources": ["legal-and-compliance"],
|
||||
}
|
||||
|
||||
for category, pages in categories.items():
|
||||
index_content += f"### {category}\n\n"
|
||||
for page in pages:
|
||||
if page in successful_pages:
|
||||
index_content += f"- [{page}](./{page}.md)\n"
|
||||
index_content += "\n"
|
||||
|
||||
save_markdown(index_content, "INDEX.md")
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
# 确保输出目录存在
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
|
||||
print("=" * 60)
|
||||
print("Claude Code 文档爬虫")
|
||||
print("=" * 60)
|
||||
print(f"输出目录: {OUTPUT_DIR}")
|
||||
print(f"文档数量: {len(DOC_PAGES)}")
|
||||
|
||||
successful = []
|
||||
failed = []
|
||||
|
||||
for page_slug in DOC_PAGES:
|
||||
if crawl_page(page_slug):
|
||||
successful.append(page_slug)
|
||||
else:
|
||||
failed.append(page_slug)
|
||||
|
||||
# 礼貌性延迟,避免请求过快
|
||||
time.sleep(0.5)
|
||||
|
||||
# 创建索引
|
||||
print("\n📑 创建索引文件...")
|
||||
create_index(successful)
|
||||
|
||||
# 打印统计
|
||||
print("\n" + "=" * 60)
|
||||
print("爬取完成!")
|
||||
print(f"成功: {len(successful)}/{len(DOC_PAGES)}")
|
||||
|
||||
if failed:
|
||||
print(f"失败: {failed}")
|
||||
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,83 @@
|
||||
---
|
||||
title: Claude Code Documentation Index
|
||||
---
|
||||
|
||||
# Claude Code 文档索引
|
||||
|
||||
此文件夹包含从 https://code.claude.com/docs 爬取的文档。
|
||||
|
||||
## 文档列表
|
||||
|
||||
### Getting Started
|
||||
|
||||
- [overview](./overview.md)
|
||||
- [quickstart](./quickstart.md)
|
||||
- [common-workflows](./common-workflows.md)
|
||||
- [changelog](./changelog.md)
|
||||
|
||||
### Outside of the Terminal
|
||||
|
||||
- [claude-code-on-the-web](./claude-code-on-the-web.md)
|
||||
- [desktop](./desktop.md)
|
||||
- [chrome](./chrome.md)
|
||||
- [vs-code](./vs-code.md)
|
||||
- [jetbrains](./jetbrains.md)
|
||||
- [github-actions](./github-actions.md)
|
||||
- [gitlab-ci-cd](./gitlab-ci-cd.md)
|
||||
- [slack](./slack.md)
|
||||
|
||||
### Build with Claude Code
|
||||
|
||||
- [sub-agents](./sub-agents.md)
|
||||
- [plugins](./plugins.md)
|
||||
- [discover-plugins](./discover-plugins.md)
|
||||
- [skills](./skills.md)
|
||||
- [output-styles](./output-styles.md)
|
||||
- [hooks-guide](./hooks-guide.md)
|
||||
- [headless](./headless.md)
|
||||
- [mcp](./mcp.md)
|
||||
- [troubleshooting](./troubleshooting.md)
|
||||
|
||||
### Deployment
|
||||
|
||||
- [third-party-integrations](./third-party-integrations.md)
|
||||
- [amazon-bedrock](./amazon-bedrock.md)
|
||||
- [google-vertex-ai](./google-vertex-ai.md)
|
||||
- [microsoft-foundry](./microsoft-foundry.md)
|
||||
- [network-config](./network-config.md)
|
||||
- [llm-gateway](./llm-gateway.md)
|
||||
- [devcontainer](./devcontainer.md)
|
||||
- [sandboxing](./sandboxing.md)
|
||||
|
||||
### Administration
|
||||
|
||||
- [setup](./setup.md)
|
||||
- [iam](./iam.md)
|
||||
- [security](./security.md)
|
||||
- [data-usage](./data-usage.md)
|
||||
- [monitoring-usage](./monitoring-usage.md)
|
||||
- [costs](./costs.md)
|
||||
- [analytics](./analytics.md)
|
||||
- [plugin-marketplaces](./plugin-marketplaces.md)
|
||||
|
||||
### Configuration
|
||||
|
||||
- [settings](./settings.md)
|
||||
- [terminal-config](./terminal-config.md)
|
||||
- [model-config](./model-config.md)
|
||||
- [memory](./memory.md)
|
||||
- [statusline](./statusline.md)
|
||||
|
||||
### Reference
|
||||
|
||||
- [cli-reference](./cli-reference.md)
|
||||
- [interactive-mode](./interactive-mode.md)
|
||||
- [slash-commands](./slash-commands.md)
|
||||
- [checkpointing](./checkpointing.md)
|
||||
- [hooks](./hooks.md)
|
||||
- [plugins-reference](./plugins-reference.md)
|
||||
|
||||
### Resources
|
||||
|
||||
- [legal-and-compliance](./legal-and-compliance.md)
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/amazon-bedrock
|
||||
title: Claude Code on Amazon Bedrock
|
||||
---
|
||||
|
||||
## [](#prerequisites) Prerequisites
|
||||
|
||||
Before configuring Claude Code with Bedrock, ensure you have:
|
||||
|
||||
- An AWS account with Bedrock access enabled
|
||||
- Access to desired Claude models (for example, Claude Sonnet 4.5) in Bedrock
|
||||
- AWS CLI installed and configured (optional - only needed if you don’t have another mechanism for getting credentials)
|
||||
- Appropriate IAM permissions
|
||||
|
||||
## [](#setup) Setup
|
||||
|
||||
### [](#1-submit-use-case-details) 1. Submit use case details
|
||||
|
||||
First-time users of Anthropic models are required to submit use case details before invoking a model. This is done once per account.
|
||||
|
||||
1. Ensure you have the right IAM permissions (see more on that below)
|
||||
2. Navigate to the [Amazon Bedrock console](https://console.aws.amazon.com/bedrock/)
|
||||
3. Select **Chat/Text playground**
|
||||
4. Choose any Anthropic model and you will be prompted to fill out the use case form
|
||||
|
||||
### [](#2-configure-aws-credentials) 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
|
||||
aws configure
|
||||
```
|
||||
|
||||
**Option B: Environment variables (access key)**
|
||||
|
||||
```bash
|
||||
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
|
||||
aws sso login --profile=<your-profile-name>
|
||||
|
||||
export AWS_PROFILE=your-profile-name
|
||||
```
|
||||
|
||||
**Option D: AWS Management Console credentials**
|
||||
|
||||
```bash
|
||||
aws login
|
||||
```
|
||||
|
||||
[Learn more](https://docs.aws.amazon.com/signin/latest/userguide/command-line-sign-in.html) about `aws login`.
|
||||
**Option E: Bedrock API keys**
|
||||
|
||||
```bash
|
||||
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) 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](/docs/en/settings) for file locations).
|
||||
When Claude Code detects that your AWS credentials are expired (either locally based on their timestamp or when Bedrock returns a credential error), it will automatically run your configured `awsAuthRefresh` and/or `awsCredentialExport` commands to obtain new credentials before retrying the request.
|
||||
|
||||
##### Example configuration
|
||||
|
||||
```bash
|
||||
{
|
||||
"awsAuthRefresh": "aws sso login --profile myprofile",
|
||||
"env": {
|
||||
"AWS_PROFILE": "myprofile"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
##### Configuration settings explained
|
||||
|
||||
**`awsAuthRefresh`**: Use this for commands that modify the `.aws` directory, such as updating credentials, SSO cache, or config files. The command’s output is displayed to the user, but interactive input isn’t supported. This works well for browser-based SSO flows where the CLI displays a URL or code and you complete authentication in the browser.
|
||||
**`awsCredentialExport`**: Only use this if you can’t modify `.aws` and must directly return credentials. Output is captured silently and not shown to the user. The command must output JSON in this format:
|
||||
|
||||
```bash
|
||||
{
|
||||
"Credentials": {
|
||||
"AccessKeyId": "value",
|
||||
"SecretAccessKey": "value",
|
||||
"SessionToken": "value"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### [](#3-configure-claude-code) 3. Configure Claude Code
|
||||
|
||||
Set the following environment variables to enable Bedrock:
|
||||
|
||||
```bash
|
||||
# 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](/docs/en/settings) for more information.
|
||||
|
||||
### [](#4-model-configuration) 4. Model configuration
|
||||
|
||||
Claude Code uses these default models for Bedrock:
|
||||
|
||||
| Model type | Default value |
|
||||
| --- | --- |
|
||||
| Primary model | `global.anthropic.claude-sonnet-4-5-20250929-v1:0` |
|
||||
| Small/fast model | `us.anthropic.claude-haiku-4-5-20251001-v1:0` |
|
||||
|
||||
For Bedrock users, Claude Code won’t automatically upgrade from Haiku 3.5 to Haiku 4.5. To manually switch to a newer Haiku model, set the `ANTHROPIC_DEFAULT_HAIKU_MODEL` environment variable to the full model name (for example, `us.anthropic.claude-haiku-4-5-20251001-v1:0`).
|
||||
|
||||
To customize models, use one of these methods:
|
||||
|
||||
```bash
|
||||
# Using inference profile ID
|
||||
export ANTHROPIC_MODEL='global.anthropic.claude-sonnet-4-5-20250929-v1:0'
|
||||
export ANTHROPIC_SMALL_FAST_MODEL='us.anthropic.claude-haiku-4-5-20251001-v1:0'
|
||||
|
||||
# Using application inference profile ARN
|
||||
export ANTHROPIC_MODEL='arn:aws:bedrock:us-east-2:your-account-id:application-inference-profile/your-model-id'
|
||||
|
||||
# Optional: Disable prompt caching if needed
|
||||
export DISABLE_PROMPT_CACHING=1
|
||||
```
|
||||
|
||||
[Prompt caching](https://docs.claude.com/en/docs/build-with-claude/prompt-caching) may not be available in all regions.
|
||||
|
||||
### [](#5-output-token-configuration) 5. Output token configuration
|
||||
|
||||
These are the recommended token settings for Claude Code with Amazon Bedrock:
|
||||
|
||||
```bash
|
||||
# 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) IAM configuration
|
||||
|
||||
Create an IAM policy with the required permissions for Claude Code:
|
||||
|
||||
```bash
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "AllowModelAndInferenceProfileAccess",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"bedrock:InvokeModel",
|
||||
"bedrock:InvokeModelWithResponseStream",
|
||||
"bedrock:ListInferenceProfiles"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:bedrock:*:*:inference-profile/*",
|
||||
"arn:aws:bedrock:*:*:application-inference-profile/*",
|
||||
"arn:aws:bedrock:*:*:foundation-model/*"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Sid": "AllowMarketplaceSubscription",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"aws-marketplace:ViewSubscriptions",
|
||||
"aws-marketplace:Subscribe"
|
||||
],
|
||||
"Resource": "*",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"aws:CalledViaLast": "bedrock.amazonaws.com"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
For more restrictive permissions, you can limit the Resource to specific inference profile ARNs.
|
||||
For details, see [Bedrock IAM documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam.html).
|
||||
|
||||
We recommend creating a dedicated AWS account for Claude Code to simplify cost tracking and access control.
|
||||
|
||||
## [](#troubleshooting) Troubleshooting
|
||||
|
||||
If you encounter region issues:
|
||||
|
||||
- Check model availability: `aws bedrock list-inference-profiles --region your-region`
|
||||
- Switch to a supported region: `export AWS_REGION=us-east-1`
|
||||
- Consider using inference profiles for cross-region access
|
||||
|
||||
If you receive an error “on-demand throughput isn’t supported”:
|
||||
|
||||
- Specify the model as an [inference profile](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html) ID
|
||||
|
||||
Claude Code uses the Bedrock [Invoke API](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html) and does not support the Converse API.
|
||||
|
||||
## [](#additional-resources) 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)
|
||||
@@ -0,0 +1,81 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/analytics
|
||||
title: Analytics
|
||||
---
|
||||
|
||||
Claude Code provides an analytics dashboard that helps organizations understand developer usage patterns, track productivity metrics, and optimize their Claude Code adoption.
|
||||
|
||||
Analytics are currently available only for organizations using Claude Code with the Claude API through the Claude Console.
|
||||
|
||||
## [](#access-analytics) Access analytics
|
||||
|
||||
Navigate to the analytics dashboard at [console.anthropic.com/claude-code](https://console.anthropic.com/claude-code).
|
||||
|
||||
### [](#required-roles) Required roles
|
||||
|
||||
- **Primary Owner**
|
||||
- **Owner**
|
||||
- **Billing**
|
||||
- **Admin**
|
||||
- **Developer**
|
||||
|
||||
Users with **User**, **Claude Code User** or **Membership Admin** roles cannot access analytics.
|
||||
|
||||
## [](#available-metrics) Available metrics
|
||||
|
||||
### [](#lines-of-code-accepted) 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) Suggestion accept rate
|
||||
|
||||
Percentage of times users accept code editing tool usage, including:
|
||||
|
||||
- Edit
|
||||
- Write
|
||||
- NotebookEdit
|
||||
|
||||
### [](#activity) 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) 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) 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) Using analytics effectively
|
||||
|
||||
### [](#monitor-adoption) Monitor adoption
|
||||
|
||||
Track team member status to identify:
|
||||
|
||||
- Active users who can share best practices
|
||||
- Overall adoption trends across your organization
|
||||
|
||||
### [](#measure-productivity) 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) Related resources
|
||||
|
||||
- [Monitoring usage with OpenTelemetry](/docs/en/monitoring-usage) for custom metrics and alerting
|
||||
- [Identity and access management](/docs/en/iam) for role configuration
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/changelog
|
||||
title: Search code, repositories, users, issues, pull requests...
|
||||
---
|
||||
|
||||
[anthropics](/anthropics)
|
||||
/
|
||||
**[claude-code](/anthropics/claude-code)**
|
||||
Public
|
||||
|
||||
- [Notifications](/login?return_to=%2Fanthropics%2Fclaude-code) You must be signed in to change notification settings
|
||||
- [Fork
|
||||
4.3k](/login?return_to=%2Fanthropics%2Fclaude-code)
|
||||
- [Star
|
||||
58.4k](/login?return_to=%2Fanthropics%2Fclaude-code)
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/checkpointing
|
||||
title: Checkpointing
|
||||
---
|
||||
|
||||
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) 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) 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) 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) 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) Limitations
|
||||
|
||||
### [](#bash-command-changes-not-tracked) Bash command changes not tracked
|
||||
|
||||
Checkpointing does not track files modified by bash commands. For example, if Claude Code runs:
|
||||
|
||||
```bash
|
||||
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) 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) 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) See also
|
||||
|
||||
- [Interactive mode](/docs/en/interactive-mode) - Keyboard shortcuts and session controls
|
||||
- [Slash commands](/docs/en/slash-commands) - Accessing checkpoints using `/rewind`
|
||||
- [CLI reference](/docs/en/cli-reference) - Command-line options
|
||||
@@ -0,0 +1,210 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/chrome
|
||||
title: Use Claude Code with Chrome (beta)
|
||||
---
|
||||
|
||||
Chrome integration is in beta and currently works with Google Chrome only. It is not yet supported on Brave, Arc, or other Chromium-based browsers. WSL (Windows Subsystem for Linux) is also not supported.
|
||||
|
||||
Claude Code integrates with the Claude in Chrome browser extension to give you browser automation capabilities directly from your terminal. Build in your terminal, then test and debug in your browser without switching contexts.
|
||||
|
||||
## [](#what-the-integration-enables) What the integration enables
|
||||
|
||||
With Chrome connected, you can chain browser actions with terminal commands in a single workflow. For example: scrape documentation from a website, analyze it, generate code based on what you learned, and commit the result.
|
||||
Key capabilities include:
|
||||
|
||||
- **Live debugging**: Claude reads console errors and DOM state directly, then fixes the code that caused them
|
||||
- **Design verification**: Build a UI from a Figma mock, then have Claude open it in the browser and verify it matches
|
||||
- **Web app testing**: Test form validation, check for visual regressions, or verify user flows work correctly
|
||||
- **Authenticated web apps**: Interact with Google Docs, Gmail, Notion, or any app you’re logged into without needing API connectors
|
||||
- **Data extraction**: Pull structured information from web pages and save it locally
|
||||
- **Task automation**: Automate repetitive browser tasks like data entry, form filling, or multi-site workflows
|
||||
- **Session recording**: Record browser interactions as GIFs to document or share what happened
|
||||
|
||||
## [](#prerequisites) Prerequisites
|
||||
|
||||
Before using Claude Code with Chrome, you need:
|
||||
|
||||
- [Google Chrome](https://www.google.com/chrome/) browser
|
||||
- [Claude in Chrome extension](https://chromewebstore.google.com/detail/claude/fcoeoabgfenejglbffodgkkbkcdhcgfn) version 1.0.36 or higher
|
||||
- [Claude Code CLI](/docs/en/quickstart#step-1:-install-claude-code) version 2.0.73 or higher
|
||||
- A paid Claude plan (Pro, Team, or Enterprise)
|
||||
|
||||
## [](#how-the-integration-works) How the integration works
|
||||
|
||||
Claude Code communicates with Chrome through the Claude in Chrome browser extension. The extension uses Chrome’s [Native Messaging API](https://developer.chrome.com/docs/extensions/develop/concepts/native-messaging) to receive commands from Claude Code and execute them in your browser. This architecture lets Claude Code control browser tabs, read page content, and perform actions while you continue working in your terminal.
|
||||
When Claude encounters a login page, CAPTCHA, or other blocker, it pauses and asks you to handle it. You can provide credentials for Claude to enter, or log in manually in the browser. Once you’re past the blocker, tell Claude to continue and it picks up where it left off.
|
||||
Claude opens new tabs for browser tasks rather than taking over existing ones. However, it shares your browser’s login state, so if you’re already signed into a site in Chrome, Claude can access it without re-authenticating.
|
||||
|
||||
The Chrome integration requires a visible browser window. When Claude performs browser actions, you’ll see Chrome open and navigate in real time. There’s no headless mode since the integration relies on your actual browser session with its login state.
|
||||
|
||||
## [](#set-up-the-integration) Set up the integration
|
||||
|
||||
1
|
||||
|
||||
Update Claude Code
|
||||
|
||||
Chrome integration requires a recent version of Claude Code. If you installed using the [native installer](/docs/en/quickstart#step-1:-install-claude-code), updates happen automatically. Otherwise, run:
|
||||
|
||||
```bash
|
||||
claude update
|
||||
```
|
||||
|
||||
2
|
||||
|
||||
Start Claude Code with Chrome enabled
|
||||
|
||||
Launch Claude Code with the `--chrome` flag:
|
||||
|
||||
```bash
|
||||
claude --chrome
|
||||
```
|
||||
|
||||
3
|
||||
|
||||
Verify the connection
|
||||
|
||||
Run `/chrome` to check the connection status and manage settings. If the extension isn’t detected, you’ll see a warning with a link to install it.
|
||||
|
||||
You can also enable Chrome integration from within an existing session using the `/chrome` slash command.
|
||||
|
||||
## [](#try-it-out) Try it out
|
||||
|
||||
Once connected, type this into Claude to see the integration in action:
|
||||
|
||||
```bash
|
||||
Go to code.claude.com/docs, click on the search box,
|
||||
type "hooks", and tell me what results appear
|
||||
```
|
||||
|
||||
Claude opens the page, clicks into the search field, types the query, and reports the autocomplete results. This shows navigation, clicking, and typing in a single workflow.
|
||||
|
||||
## [](#example-workflows) Example workflows
|
||||
|
||||
Claude can navigate pages, click and type, fill forms, scroll, read console logs and network requests, manage tabs, resize windows, and record GIFs. Run `/mcp` and click into `claude-in-chrome` to see the full list of available tools.
|
||||
The following examples show common patterns for browser automation.
|
||||
|
||||
### [](#test-a-local-web-application) Test a local web application
|
||||
|
||||
When developing a web app, ask Claude to verify your changes work correctly:
|
||||
|
||||
```bash
|
||||
I just updated the login form validation. Can you open localhost:3000,
|
||||
try submitting the form with invalid data, and check if the error
|
||||
messages appear correctly?
|
||||
```
|
||||
|
||||
Claude navigates to your local server, interacts with the form, and reports what it observes.
|
||||
|
||||
### [](#debug-with-console-logs) Debug with console logs
|
||||
|
||||
If your app has issues, Claude can read console output to help diagnose problems:
|
||||
|
||||
```bash
|
||||
Open the dashboard page and check the console for any errors when
|
||||
the page loads.
|
||||
```
|
||||
|
||||
Claude reads the console messages and can filter for specific patterns or error types.
|
||||
|
||||
### [](#automate-form-filling) Automate form filling
|
||||
|
||||
Speed up repetitive data entry tasks:
|
||||
|
||||
```bash
|
||||
I have a spreadsheet of customer contacts in contacts.csv. For each row,
|
||||
go to our CRM at crm.example.com, click "Add Contact", and fill in the
|
||||
name, email, and phone fields.
|
||||
```
|
||||
|
||||
Claude reads your local file, navigates the web interface, and enters the data for each record.
|
||||
|
||||
### [](#draft-content-in-google-docs) Draft content in Google Docs
|
||||
|
||||
Use Claude to write directly in your documents without API setup:
|
||||
|
||||
```bash
|
||||
Draft a project update based on our recent commits and add it to my
|
||||
Google Doc at docs.google.com/document/d/abc123
|
||||
```
|
||||
|
||||
Claude opens the document, clicks into the editor, and types the content. This works with any web app you’re logged into: Gmail, Notion, Sheets, and more.
|
||||
|
||||
### [](#extract-data-from-web-pages) Extract data from web pages
|
||||
|
||||
Pull structured information from websites:
|
||||
|
||||
```bash
|
||||
Go to the product listings page and extract the name, price, and
|
||||
availability for each item. Save the results as a CSV file.
|
||||
```
|
||||
|
||||
Claude navigates to the page, reads the content, and compiles the data into a structured format.
|
||||
|
||||
### [](#run-multi-site-workflows) Run multi-site workflows
|
||||
|
||||
Coordinate tasks across multiple websites:
|
||||
|
||||
```bash
|
||||
Check my calendar for meetings tomorrow, then for each meeting with
|
||||
an external attendee, look up their company on LinkedIn and add a
|
||||
note about what they do.
|
||||
```
|
||||
|
||||
Claude works across tabs to gather information and complete the workflow.
|
||||
|
||||
### [](#record-a-demo-gif) Record a demo GIF
|
||||
|
||||
Create shareable recordings of browser interactions:
|
||||
|
||||
```bash
|
||||
Record a GIF showing how to complete the checkout flow, from adding
|
||||
an item to the cart through to the confirmation page.
|
||||
```
|
||||
|
||||
Claude records the interaction sequence and saves it as a GIF file.
|
||||
|
||||
## [](#best-practices) Best practices
|
||||
|
||||
When using browser automation, keep these guidelines in mind:
|
||||
|
||||
- **Modal dialogs can interrupt the flow**: JavaScript alerts, confirms, and prompts block browser events and prevent Claude from receiving commands. If a dialog appears, dismiss it manually and tell Claude to continue.
|
||||
- **Use fresh tabs**: Claude creates new tabs for each session. If a tab becomes unresponsive, ask Claude to create a new one.
|
||||
- **Filter console output**: Console logs can be verbose. When debugging, tell Claude what patterns to look for rather than asking for all console output.
|
||||
|
||||
## [](#troubleshooting) Troubleshooting
|
||||
|
||||
### [](#extension-not-detected) Extension not detected
|
||||
|
||||
If Claude Code shows “Chrome extension not detected”:
|
||||
|
||||
1. Verify the Chrome extension (version 1.0.36 or higher) is installed
|
||||
2. Verify Claude Code is version 2.0.73 or higher by running `claude --version`
|
||||
3. Check that Chrome is running
|
||||
4. Run `/chrome` and select “Reconnect extension” to re-establish the connection
|
||||
5. If the issue persists, restart both Claude Code and Chrome
|
||||
|
||||
### [](#browser-not-responding) Browser not responding
|
||||
|
||||
If Claude’s browser commands stop working:
|
||||
|
||||
1. Check if a modal dialog (alert, confirm, prompt) is blocking the page
|
||||
2. Ask Claude to create a new tab and try again
|
||||
3. Restart the Chrome extension by disabling and re-enabling it
|
||||
|
||||
### [](#first-time-setup) First-time setup
|
||||
|
||||
The first time you use the integration, Claude Code installs a native messaging host that allows communication between the CLI and Chrome. If you encounter permission errors, you may need to restart Chrome for the installation to take effect.
|
||||
|
||||
## [](#enable-by-default) Enable by default
|
||||
|
||||
Chrome integration requires the `--chrome` flag each time you start Claude Code. To enable it by default, run `/chrome` and select “Enabled by default”.
|
||||
|
||||
Enabling Chrome by default increases context usage since browser tools are always loaded. If you notice increased context consumption, disable this setting and use `--chrome` only when needed.
|
||||
|
||||
Site-level permissions are inherited from the Chrome extension. Manage permissions in the Chrome extension settings to control which sites Claude can browse, click, and type on. Run `/chrome` to see current permission settings.
|
||||
|
||||
## [](#see-also) See also
|
||||
|
||||
- [CLI reference](/docs/en/cli-reference) - Command-line flags including `--chrome`
|
||||
- [Common workflows](/docs/en/common-workflows) - More ways to use Claude Code
|
||||
- [Getting started with Claude for Chrome](https://support.anthropic.com/en/articles/12012173-getting-started-with-claude-for-chrome) - Full documentation for the Chrome extension, including shortcuts, scheduling, and permissions
|
||||
@@ -0,0 +1,527 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/claude-code-on-the-web
|
||||
title: Claude Code on the web
|
||||
---
|
||||
|
||||
Claude Code on the web is currently in research preview.
|
||||
|
||||
## [](#what-is-claude-code-on-the-web) What is Claude Code on the web?
|
||||
|
||||
Claude Code on the web lets developers kick off Claude Code from the Claude app. This is perfect for:
|
||||
|
||||
- **Answering questions**: Ask about code architecture and how features are implemented
|
||||
- **Bug fixes and routine tasks**: Well-defined tasks that don’t require frequent steering
|
||||
- **Parallel work**: Tackle multiple bug fixes in parallel
|
||||
- **Repositories not on your local machine**: Work on code you don’t have checked out locally
|
||||
- **Backend changes**: Where Claude Code can write tests and then write code to pass those tests
|
||||
|
||||
Claude Code is also available on the Claude iOS app for kicking off tasks on the go and monitoring work in progress.
|
||||
You can move between local and remote development: [send tasks from your terminal to run on the web](#from-terminal-to-web) with the `&` prefix, or [teleport web sessions back to your terminal](#from-web-to-terminal) to continue locally.
|
||||
|
||||
## [](#who-can-use-claude-code-on-the-web) Who can use Claude Code on the web?
|
||||
|
||||
Claude Code on the web is available in research preview to:
|
||||
|
||||
- **Pro users**
|
||||
- **Max users**
|
||||
- **Team premium seat users**
|
||||
- **Enterprise premium seat users**
|
||||
|
||||
## [](#getting-started) Getting started
|
||||
|
||||
1. Visit [claude.ai/code](https://claude.ai/code)
|
||||
2. Connect your GitHub account
|
||||
3. Install the Claude GitHub app in your repositories
|
||||
4. Select your default environment
|
||||
5. Submit your coding task
|
||||
6. Review changes and create a pull request in GitHub
|
||||
|
||||
## [](#how-it-works) How it works
|
||||
|
||||
When you start a task on Claude Code on the web:
|
||||
|
||||
1. **Repository cloning**: Your repository is cloned to an Anthropic-managed virtual machine
|
||||
2. **Environment setup**: Claude prepares a secure cloud environment with your code
|
||||
3. **Network configuration**: Internet access is configured based on your settings
|
||||
4. **Task execution**: Claude analyzes code, makes changes, runs tests, and checks its work
|
||||
5. **Completion**: You’re notified when finished and can create a PR with the changes
|
||||
6. **Results**: Changes are pushed to a branch, ready for pull request creation
|
||||
|
||||
## [](#moving-tasks-between-web-and-terminal) Moving tasks between web and terminal
|
||||
|
||||
You can start tasks on the web and continue them in your terminal, or send tasks from your terminal to run on the web. Web sessions persist even if you close your laptop, and you can monitor them from anywhere including the Claude iOS app.
|
||||
|
||||
Session handoff is one-way: you can pull web sessions into your terminal, but you can’t push an existing terminal session to the web. The [`&` prefix](#from-terminal-to-web) creates a *new* web session with your current conversation context.
|
||||
|
||||
### [](#from-terminal-to-web) From terminal to web
|
||||
|
||||
Start a message with `&` inside Claude Code to send a task to run on the web:
|
||||
|
||||
```bash
|
||||
& Fix the authentication bug in src/auth/login.ts
|
||||
```
|
||||
|
||||
This creates a new web session on claude.ai with your current conversation context. The task runs in the cloud while you continue working locally. Use `/tasks` to check progress, or open the session on claude.ai or the Claude iOS app to interact directly. From there you can steer Claude, provide feedback, or answer questions just like any other conversation.
|
||||
You can also start a web session directly from the command line:
|
||||
|
||||
```bash
|
||||
claude --remote "Fix the authentication bug in src/auth/login.ts"
|
||||
```
|
||||
|
||||
#### [](#tips-for-background-tasks) Tips for background tasks
|
||||
|
||||
**Plan locally, execute remotely**: For complex tasks, start Claude in plan mode to collaborate on the approach before sending work to the web:
|
||||
|
||||
```bash
|
||||
claude --permission-mode plan
|
||||
```
|
||||
|
||||
In plan mode, Claude can only read files and explore the codebase. Once you’re satisfied with the plan, send it to the web for autonomous execution:
|
||||
|
||||
```bash
|
||||
& Execute the migration plan we discussed
|
||||
```
|
||||
|
||||
This pattern gives you control over the strategy while letting Claude execute autonomously in the cloud.
|
||||
**Run tasks in parallel**: Each `&` command creates its own web session that runs independently. You can kick off multiple tasks and they’ll all run simultaneously in separate sessions:
|
||||
|
||||
```bash
|
||||
& Fix the flaky test in auth.spec.ts
|
||||
& Update the API documentation
|
||||
& Refactor the logger to use structured output
|
||||
```
|
||||
|
||||
Monitor all sessions with `/tasks`. When a session completes, you can create a PR from the web interface or [teleport](#from-web-to-terminal) the session to your terminal to continue working.
|
||||
|
||||
### [](#from-web-to-terminal) From web to terminal
|
||||
|
||||
There are several ways to pull a web session into your terminal:
|
||||
|
||||
- **Using `/teleport`**: From within Claude Code, run `/teleport` (or `/tp`) to see an interactive picker of your web sessions. If you have uncommitted changes, you’ll be prompted to stash them first.
|
||||
- **Using `--teleport`**: From the command line, run `claude --teleport` for an interactive session picker, or `claude --teleport <session-id>` to resume a specific session directly.
|
||||
- **From `/tasks`**: Run `/tasks` to see your background sessions, then press `t` to teleport into one
|
||||
- **From the web interface**: Click “Open in CLI” to copy a command you can paste into your terminal
|
||||
|
||||
When you teleport a session, Claude verifies you’re in the correct repository, fetches and checks out the branch from the remote session, and loads the full conversation history into your terminal.
|
||||
|
||||
#### [](#requirements-for-teleporting) Requirements for teleporting
|
||||
|
||||
Teleport checks these requirements before resuming a session. If any requirement isn’t met, you’ll see an error or be prompted to resolve the issue.
|
||||
|
||||
| Requirement | Details |
|
||||
| --- | --- |
|
||||
| Clean git state | Your working directory must have no uncommitted changes. Teleport prompts you to stash changes if needed. |
|
||||
| Correct repository | You must run `--teleport` from a checkout of the same repository, not a fork. |
|
||||
| Branch available | The branch from the web session must have been pushed to the remote. Teleport automatically fetches and checks it out. |
|
||||
| Same account | You must be authenticated to the same Claude.ai account used in the web session. |
|
||||
|
||||
## [](#cloud-environment) Cloud environment
|
||||
|
||||
### [](#default-image) Default image
|
||||
|
||||
We build and maintain a universal image with common toolchains and language ecosystems pre-installed. This image includes:
|
||||
|
||||
- Popular programming languages and runtimes
|
||||
- Common build tools and package managers
|
||||
- Testing frameworks and linters
|
||||
|
||||
#### [](#checking-available-tools) Checking available tools
|
||||
|
||||
To see what’s pre-installed in your environment, ask Claude Code to run:
|
||||
|
||||
```bash
|
||||
check-tools
|
||||
```
|
||||
|
||||
This command displays:
|
||||
|
||||
- Programming languages and their versions
|
||||
- Available package managers
|
||||
- Installed development tools
|
||||
|
||||
#### [](#language-specific-setups) Language-specific setups
|
||||
|
||||
The universal image includes pre-configured environments for:
|
||||
|
||||
- **Python**: Python 3.x with pip, poetry, and common scientific libraries
|
||||
- **Node.js**: Latest LTS versions with npm, yarn, pnpm, and bun
|
||||
- **Ruby**: Versions 3.1.6, 3.2.6, 3.3.6 (default: 3.3.6) with gem, bundler, and rbenv for version management
|
||||
- **PHP**: Version 8.4.14
|
||||
- **Java**: OpenJDK with Maven and Gradle
|
||||
- **Go**: Latest stable version with module support
|
||||
- **Rust**: Rust toolchain with cargo
|
||||
- **C++**: GCC and Clang compilers
|
||||
|
||||
#### [](#databases) Databases
|
||||
|
||||
The universal image includes the following databases:
|
||||
|
||||
- **PostgreSQL**: Version 16
|
||||
- **Redis**: Version 7.0
|
||||
|
||||
### [](#environment-configuration) Environment configuration
|
||||
|
||||
When you start a session in Claude Code on the web, here’s what happens under the hood:
|
||||
|
||||
1. **Environment preparation**: We clone your repository and run any configured Claude hooks for initialization. The repo will be cloned with the default branch on your GitHub repo. If you would like to check out a specific branch, you can specify that in the prompt.
|
||||
2. **Network configuration**: We configure internet access for the agent. Internet access is limited by default, but you can configure the environment to have no internet or full internet access based on your needs.
|
||||
3. **Claude Code execution**: Claude Code runs to complete your task, writing code, running tests, and checking its work. You can guide and steer Claude throughout the session via the web interface. Claude respects context you’ve defined in your `CLAUDE.md`.
|
||||
4. **Outcome**: When Claude completes its work, it will push the branch to remote. You will be able to create a PR for the branch.
|
||||
|
||||
Claude operates entirely through the terminal and CLI tools available in the environment. It uses the pre-installed tools in the universal image and any additional tools you install through hooks or dependency management.
|
||||
|
||||
**To add a new environment:** Select the current environment to open the environment selector, and then select “Add environment”. This will open a dialog where you can specify the environment name, network access level, and any environment variables you want to set.
|
||||
**To update an existing environment:** Select the current environment, to the right of the environment name, and select the settings button. This will open a dialog where you can update the environment name, network access, and environment variables.
|
||||
**To select your default environment from the terminal:** If you have multiple environments configured, run `/remote-env` to choose which one to use when starting web sessions from your terminal with `&` or `--remote`. With a single environment, this command shows your current configuration.
|
||||
|
||||
Environment variables must be specified as key-value pairs, in [`.env` format](https://www.dotenv.org/). For example:
|
||||
|
||||
```bash
|
||||
API_KEY=your_api_key
|
||||
DEBUG=true
|
||||
```
|
||||
|
||||
### [](#dependency-management) Dependency management
|
||||
|
||||
Configure automatic dependency installation using [SessionStart hooks](/docs/en/hooks#sessionstart). This can be configured in your repository’s `.claude/settings.json` file:
|
||||
|
||||
```bash
|
||||
{
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"matcher": "startup",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "\"$CLAUDE_PROJECT_DIR\"/scripts/install_pkgs.sh"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Create the corresponding script at `scripts/install_pkgs.sh`:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
npm install
|
||||
pip install -r requirements.txt
|
||||
exit 0
|
||||
```
|
||||
|
||||
Make it executable: `chmod +x scripts/install_pkgs.sh`
|
||||
|
||||
#### [](#local-vs-remote-execution) Local vs remote execution
|
||||
|
||||
By default, all hooks execute both locally and in remote (web) environments. To run a hook only in one environment, check the `CLAUDE_CODE_REMOTE` environment variable in your hook script.
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
|
||||
# Example: Only run in remote environments
|
||||
if [ "$CLAUDE_CODE_REMOTE" != "true" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
npm install
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
#### [](#persisting-environment-variables) Persisting environment variables
|
||||
|
||||
SessionStart hooks can persist environment variables for subsequent bash commands by writing to the file specified in the `CLAUDE_ENV_FILE` environment variable. For details, see [SessionStart hooks](/docs/en/hooks#sessionstart) in the hooks reference.
|
||||
|
||||
## [](#network-access-and-security) Network access and security
|
||||
|
||||
### [](#network-policy) Network policy
|
||||
|
||||
#### [](#github-proxy) GitHub proxy
|
||||
|
||||
For security, all GitHub operations go through a dedicated proxy service that transparently handles all git interactions. Inside the sandbox, the git client authenticates using a custom-built scoped credential. This proxy:
|
||||
|
||||
- Manages GitHub authentication securely - the git client uses a scoped credential inside the sandbox, which the proxy verifies and translates to your actual GitHub authentication token
|
||||
- Restricts git push operations to the current working branch for safety
|
||||
- Enables seamless cloning, fetching, and PR operations while maintaining security boundaries
|
||||
|
||||
#### [](#security-proxy) Security proxy
|
||||
|
||||
Environments run behind an HTTP/HTTPS network proxy for security and abuse prevention purposes. All outbound internet traffic passes through this proxy, which provides:
|
||||
|
||||
- Protection against malicious requests
|
||||
- Rate limiting and abuse prevention
|
||||
- Content filtering for enhanced security
|
||||
|
||||
### [](#access-levels) Access levels
|
||||
|
||||
By default, network access is limited to [allowlisted domains](#default-allowed-domains).
|
||||
You can configure custom network access, including disabling network access.
|
||||
|
||||
### [](#default-allowed-domains) Default allowed domains
|
||||
|
||||
When using “Limited” network access, the following domains are allowed by default:
|
||||
|
||||
#### [](#anthropic-services) Anthropic Services
|
||||
|
||||
- api.anthropic.com
|
||||
- statsig.anthropic.com
|
||||
- claude.ai
|
||||
|
||||
#### [](#version-control) Version Control
|
||||
|
||||
- github.com
|
||||
- [www.github.com](http://www.github.com)
|
||||
- api.github.com
|
||||
- raw.githubusercontent.com
|
||||
- objects.githubusercontent.com
|
||||
- codeload.github.com
|
||||
- avatars.githubusercontent.com
|
||||
- camo.githubusercontent.com
|
||||
- gist.github.com
|
||||
- gitlab.com
|
||||
- [www.gitlab.com](http://www.gitlab.com)
|
||||
- registry.gitlab.com
|
||||
- bitbucket.org
|
||||
- [www.bitbucket.org](http://www.bitbucket.org)
|
||||
- api.bitbucket.org
|
||||
|
||||
#### [](#container-registries) Container Registries
|
||||
|
||||
- registry-1.docker.io
|
||||
- auth.docker.io
|
||||
- index.docker.io
|
||||
- hub.docker.com
|
||||
- [www.docker.com](http://www.docker.com)
|
||||
- production.cloudflare.docker.com
|
||||
- download.docker.com
|
||||
- \*.gcr.io
|
||||
- ghcr.io
|
||||
- mcr.microsoft.com
|
||||
- \*.data.mcr.microsoft.com
|
||||
- public.ecr.aws
|
||||
|
||||
#### [](#cloud-platforms) Cloud Platforms
|
||||
|
||||
- cloud.google.com
|
||||
- accounts.google.com
|
||||
- gcloud.google.com
|
||||
- \*.googleapis.com
|
||||
- storage.googleapis.com
|
||||
- compute.googleapis.com
|
||||
- container.googleapis.com
|
||||
- azure.com
|
||||
- portal.azure.com
|
||||
- microsoft.com
|
||||
- [www.microsoft.com](http://www.microsoft.com)
|
||||
- \*.microsoftonline.com
|
||||
- packages.microsoft.com
|
||||
- dotnet.microsoft.com
|
||||
- dot.net
|
||||
- visualstudio.com
|
||||
- dev.azure.com
|
||||
- \*.amazonaws.com
|
||||
- \*.api.aws
|
||||
- oracle.com
|
||||
- [www.oracle.com](http://www.oracle.com)
|
||||
- java.com
|
||||
- [www.java.com](http://www.java.com)
|
||||
- java.net
|
||||
- [www.java.net](http://www.java.net)
|
||||
- download.oracle.com
|
||||
- yum.oracle.com
|
||||
|
||||
#### [](#package-managers-javascript/node) Package Managers - JavaScript/Node
|
||||
|
||||
- registry.npmjs.org
|
||||
- [www.npmjs.com](http://www.npmjs.com)
|
||||
- [www.npmjs.org](http://www.npmjs.org)
|
||||
- npmjs.com
|
||||
- npmjs.org
|
||||
- yarnpkg.com
|
||||
- registry.yarnpkg.com
|
||||
|
||||
#### [](#package-managers-python) Package Managers - Python
|
||||
|
||||
- pypi.org
|
||||
- [www.pypi.org](http://www.pypi.org)
|
||||
- files.pythonhosted.org
|
||||
- pythonhosted.org
|
||||
- test.pypi.org
|
||||
- pypi.python.org
|
||||
- pypa.io
|
||||
- [www.pypa.io](http://www.pypa.io)
|
||||
|
||||
#### [](#package-managers-ruby) Package Managers - Ruby
|
||||
|
||||
- rubygems.org
|
||||
- [www.rubygems.org](http://www.rubygems.org)
|
||||
- api.rubygems.org
|
||||
- index.rubygems.org
|
||||
- ruby-lang.org
|
||||
- [www.ruby-lang.org](http://www.ruby-lang.org)
|
||||
- rubyforge.org
|
||||
- [www.rubyforge.org](http://www.rubyforge.org)
|
||||
- rubyonrails.org
|
||||
- [www.rubyonrails.org](http://www.rubyonrails.org)
|
||||
- rvm.io
|
||||
- get.rvm.io
|
||||
|
||||
#### [](#package-managers-rust) Package Managers - Rust
|
||||
|
||||
- crates.io
|
||||
- [www.crates.io](http://www.crates.io)
|
||||
- static.crates.io
|
||||
- rustup.rs
|
||||
- static.rust-lang.org
|
||||
- [www.rust-lang.org](http://www.rust-lang.org)
|
||||
|
||||
#### [](#package-managers-go) Package Managers - Go
|
||||
|
||||
- proxy.golang.org
|
||||
- sum.golang.org
|
||||
- index.golang.org
|
||||
- golang.org
|
||||
- [www.golang.org](http://www.golang.org)
|
||||
- goproxy.io
|
||||
- pkg.go.dev
|
||||
|
||||
#### [](#package-managers-jvm) Package Managers - JVM
|
||||
|
||||
- maven.org
|
||||
- repo.maven.org
|
||||
- central.maven.org
|
||||
- repo1.maven.org
|
||||
- jcenter.bintray.com
|
||||
- gradle.org
|
||||
- [www.gradle.org](http://www.gradle.org)
|
||||
- services.gradle.org
|
||||
- spring.io
|
||||
- repo.spring.io
|
||||
|
||||
#### [](#package-managers-other-languages) Package Managers - Other Languages
|
||||
|
||||
- packagist.org (PHP Composer)
|
||||
- [www.packagist.org](http://www.packagist.org)
|
||||
- repo.packagist.org
|
||||
- nuget.org (.NET NuGet)
|
||||
- [www.nuget.org](http://www.nuget.org)
|
||||
- api.nuget.org
|
||||
- pub.dev (Dart/Flutter)
|
||||
- api.pub.dev
|
||||
- hex.pm (Elixir/Erlang)
|
||||
- [www.hex.pm](http://www.hex.pm)
|
||||
- cpan.org (Perl CPAN)
|
||||
- [www.cpan.org](http://www.cpan.org)
|
||||
- metacpan.org
|
||||
- [www.metacpan.org](http://www.metacpan.org)
|
||||
- api.metacpan.org
|
||||
- cocoapods.org (iOS/macOS)
|
||||
- [www.cocoapods.org](http://www.cocoapods.org)
|
||||
- cdn.cocoapods.org
|
||||
- haskell.org
|
||||
- [www.haskell.org](http://www.haskell.org)
|
||||
- hackage.haskell.org
|
||||
- swift.org
|
||||
- [www.swift.org](http://www.swift.org)
|
||||
|
||||
#### [](#linux-distributions) Linux Distributions
|
||||
|
||||
- archive.ubuntu.com
|
||||
- security.ubuntu.com
|
||||
- ubuntu.com
|
||||
- [www.ubuntu.com](http://www.ubuntu.com)
|
||||
- \*.ubuntu.com
|
||||
- ppa.launchpad.net
|
||||
- launchpad.net
|
||||
- [www.launchpad.net](http://www.launchpad.net)
|
||||
|
||||
#### [](#development-tools-&-platforms) Development Tools & Platforms
|
||||
|
||||
- dl.k8s.io (Kubernetes)
|
||||
- pkgs.k8s.io
|
||||
- k8s.io
|
||||
- [www.k8s.io](http://www.k8s.io)
|
||||
- releases.hashicorp.com (HashiCorp)
|
||||
- apt.releases.hashicorp.com
|
||||
- rpm.releases.hashicorp.com
|
||||
- archive.releases.hashicorp.com
|
||||
- hashicorp.com
|
||||
- [www.hashicorp.com](http://www.hashicorp.com)
|
||||
- repo.anaconda.com (Anaconda/Conda)
|
||||
- conda.anaconda.org
|
||||
- anaconda.org
|
||||
- [www.anaconda.com](http://www.anaconda.com)
|
||||
- anaconda.com
|
||||
- continuum.io
|
||||
- apache.org (Apache)
|
||||
- [www.apache.org](http://www.apache.org)
|
||||
- archive.apache.org
|
||||
- downloads.apache.org
|
||||
- eclipse.org (Eclipse)
|
||||
- [www.eclipse.org](http://www.eclipse.org)
|
||||
- download.eclipse.org
|
||||
- nodejs.org (Node.js)
|
||||
- [www.nodejs.org](http://www.nodejs.org)
|
||||
|
||||
#### [](#cloud-services-&-monitoring) Cloud Services & Monitoring
|
||||
|
||||
- statsig.com
|
||||
- [www.statsig.com](http://www.statsig.com)
|
||||
- api.statsig.com
|
||||
- \*.sentry.io
|
||||
|
||||
#### [](#content-delivery-&-mirrors) Content Delivery & Mirrors
|
||||
|
||||
- \*.sourceforge.net
|
||||
- packagecloud.io
|
||||
- \*.packagecloud.io
|
||||
|
||||
#### [](#schema-&-configuration) Schema & Configuration
|
||||
|
||||
- json-schema.org
|
||||
- [www.json-schema.org](http://www.json-schema.org)
|
||||
- json.schemastore.org
|
||||
- [www.schemastore.org](http://www.schemastore.org)
|
||||
|
||||
Domains marked with `*` indicate wildcard subdomain matching. For example, `*.gcr.io` allows access to any subdomain of `gcr.io`.
|
||||
|
||||
### [](#security-best-practices-for-customized-network-access) Security best practices for customized network access
|
||||
|
||||
1. **Principle of least privilege**: Only enable the minimum network access required
|
||||
2. **Audit regularly**: Review allowed domains periodically
|
||||
3. **Use HTTPS**: Always prefer HTTPS endpoints over HTTP
|
||||
|
||||
## [](#security-and-isolation) Security and isolation
|
||||
|
||||
Claude Code on the web provides strong security guarantees:
|
||||
|
||||
- **Isolated virtual machines**: Each session runs in an isolated, Anthropic-managed VM
|
||||
- **Network access controls**: Network access is limited by default, and can be disabled
|
||||
|
||||
When running with network access disabled, Claude Code is allowed to communicate with the Anthropic API which may still allow data to exit the isolated Claude Code VM.
|
||||
|
||||
- **Credential protection**: Sensitive credentials (such as git credentials or signing keys) are never inside the sandbox with Claude Code. Authentication is handled through a secure proxy using scoped credentials
|
||||
- **Secure analysis**: Code is analyzed and modified within isolated VMs before creating PRs
|
||||
|
||||
## [](#pricing-and-rate-limits) Pricing and rate limits
|
||||
|
||||
Claude Code on the web shares rate limits with all other Claude and Claude Code usage within your account. Running multiple tasks in parallel will consume more rate limits proportionately.
|
||||
|
||||
## [](#limitations) Limitations
|
||||
|
||||
- **Repository authentication**: You can only move sessions from web to local when you are authenticated to the same account
|
||||
- **Platform restrictions**: Claude Code on the web only works with code hosted in GitHub. GitLab and other non-GitHub repositories cannot be used with cloud sessions
|
||||
|
||||
## [](#best-practices) Best practices
|
||||
|
||||
1. **Use Claude Code hooks**: Configure [SessionStart hooks](/docs/en/hooks#sessionstart) to automate environment setup and dependency installation.
|
||||
2. **Document requirements**: Clearly specify dependencies and commands in your `CLAUDE.md` file. If you have an `AGENTS.md` file, you can source it in your `CLAUDE.md` using `@AGENTS.md` to maintain a single source of truth.
|
||||
|
||||
## [](#related-resources) Related resources
|
||||
|
||||
- [Hooks configuration](/docs/en/hooks)
|
||||
- [Settings reference](/docs/en/settings)
|
||||
- [Security](/docs/en/security)
|
||||
- [Data usage](/docs/en/data-usage)
|
||||
@@ -0,0 +1,148 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/cli-reference
|
||||
title: CLI reference
|
||||
---
|
||||
|
||||
## [](#cli-commands) CLI commands
|
||||
|
||||
| Command | Description | Example |
|
||||
| --- | --- | --- |
|
||||
| `claude` | Start interactive REPL | `claude` |
|
||||
| `claude "query"` | Start REPL with initial prompt | `claude "explain this project"` |
|
||||
| `claude -p "query"` | Query via SDK, then exit | `claude -p "explain this function"` |
|
||||
| `cat file | claude -p "query"` | Process piped content | `cat logs.txt | claude -p "explain"` |
|
||||
| `claude -c` | Continue most recent conversation in current directory | `claude -c` |
|
||||
| `claude -c -p "query"` | Continue via SDK | `claude -c -p "Check for type errors"` |
|
||||
| `claude -r "<session>" "query"` | Resume session by ID or name | `claude -r "auth-refactor" "Finish this PR"` |
|
||||
| `claude update` | Update to latest version | `claude update` |
|
||||
| `claude mcp` | Configure Model Context Protocol (MCP) servers | See the [Claude Code MCP documentation](/docs/en/mcp). |
|
||||
|
||||
## [](#cli-flags) CLI flags
|
||||
|
||||
Customize Claude Code’s behavior with these command-line flags:
|
||||
|
||||
| Flag | Description | Example |
|
||||
| --- | --- | --- |
|
||||
| `--add-dir` | Add additional working directories for Claude to access (validates each path exists as a directory) | `claude --add-dir ../apps ../lib` |
|
||||
| `--agent` | Specify an agent for the current session (overrides the `agent` setting) | `claude --agent my-custom-agent` |
|
||||
| `--agents` | Define custom [subagents](/docs/en/sub-agents) dynamically via JSON (see below for format) | `claude --agents '{"reviewer":{"description":"Reviews code","prompt":"You are a code reviewer"}}'` |
|
||||
| `--allow-dangerously-skip-permissions` | Enable permission bypassing as an option without immediately activating it. Allows composing with `--permission-mode` (use with caution) | `claude --permission-mode plan --allow-dangerously-skip-permissions` |
|
||||
| `--allowedTools` | Tools that execute without prompting for permission. See [permission rule syntax](/docs/en/settings#permission-rule-syntax) for pattern matching. To restrict which tools are available, use `--tools` instead | `"Bash(git log:*)" "Bash(git diff:*)" "Read"` |
|
||||
| `--append-system-prompt` | Append custom text to the end of the default system prompt (works in both interactive and print modes) | `claude --append-system-prompt "Always use TypeScript"` |
|
||||
| `--append-system-prompt-file` | Load additional system prompt text from a file and append to the default prompt (print mode only) | `claude -p --append-system-prompt-file ./extra-rules.txt "query"` |
|
||||
| `--betas` | Beta headers to include in API requests (API key users only) | `claude --betas interleaved-thinking` |
|
||||
| `--chrome` | Enable [Chrome browser integration](/docs/en/chrome) for web automation and testing | `claude --chrome` |
|
||||
| `--continue`, `-c` | Load the most recent conversation in the current directory | `claude --continue` |
|
||||
| `--dangerously-skip-permissions` | Skip all permission prompts (use with caution) | `claude --dangerously-skip-permissions` |
|
||||
| `--debug` | Enable debug mode with optional category filtering (for example, `"api,hooks"` or `"!statsig,!file"`) | `claude --debug "api,mcp"` |
|
||||
| `--disable-slash-commands` | Disable all skills and slash commands for this session | `claude --disable-slash-commands` |
|
||||
| `--disallowedTools` | Tools that are removed from the model’s context and cannot be used | `"Bash(git log:*)" "Bash(git diff:*)" "Edit"` |
|
||||
| `--fallback-model` | Enable automatic fallback to specified model when default model is overloaded (print mode only) | `claude -p --fallback-model sonnet "query"` |
|
||||
| `--fork-session` | When resuming, create a new session ID instead of reusing the original (use with `--resume` or `--continue`) | `claude --resume abc123 --fork-session` |
|
||||
| `--ide` | Automatically connect to IDE on startup if exactly one valid IDE is available | `claude --ide` |
|
||||
| `--include-partial-messages` | Include partial streaming events in output (requires `--print` and `--output-format=stream-json`) | `claude -p --output-format stream-json --include-partial-messages "query"` |
|
||||
| `--input-format` | Specify input format for print mode (options: `text`, `stream-json`) | `claude -p --output-format json --input-format stream-json` |
|
||||
| `--json-schema` | Get validated JSON output matching a JSON Schema after agent completes its workflow (print mode only, see [Agent SDK Structured Outputs](https://docs.claude.com/en/docs/agent-sdk/structured-outputs)) | `claude -p --json-schema '{"type":"object","properties":{...}}' "query"` |
|
||||
| `--max-budget-usd` | Maximum dollar amount to spend on API calls before stopping (print mode only) | `claude -p --max-budget-usd 5.00 "query"` |
|
||||
| `--max-turns` | Limit the number of agentic turns (print mode only). Exits with an error when the limit is reached. No limit by default | `claude -p --max-turns 3 "query"` |
|
||||
| `--mcp-config` | Load MCP servers from JSON files or strings (space-separated) | `claude --mcp-config ./mcp.json` |
|
||||
| `--model` | Sets the model for the current session with an alias for the latest model (`sonnet` or `opus`) or a model’s full name | `claude --model claude-sonnet-4-5-20250929` |
|
||||
| `--no-chrome` | Disable [Chrome browser integration](/docs/en/chrome) for this session | `claude --no-chrome` |
|
||||
| `--no-session-persistence` | Disable session persistence so sessions are not saved to disk and cannot be resumed (print mode only) | `claude -p --no-session-persistence "query"` |
|
||||
| `--output-format` | Specify output format for print mode (options: `text`, `json`, `stream-json`) | `claude -p "query" --output-format json` |
|
||||
| `--permission-mode` | Begin in a specified [permission mode](/docs/en/iam#permission-modes) | `claude --permission-mode plan` |
|
||||
| `--permission-prompt-tool` | Specify an MCP tool to handle permission prompts in non-interactive mode | `claude -p --permission-prompt-tool mcp_auth_tool "query"` |
|
||||
| `--plugin-dir` | Load plugins from directories for this session only (repeatable) | `claude --plugin-dir ./my-plugins` |
|
||||
| `--print`, `-p` | Print response without interactive mode (see [SDK documentation](https://docs.claude.com/en/docs/agent-sdk) for programmatic usage details) | `claude -p "query"` |
|
||||
| `--remote` | Create a new [web session](/docs/en/claude-code-on-the-web) on claude.ai with the provided task description | `claude --remote "Fix the login bug"` |
|
||||
| `--resume`, `-r` | Resume a specific session by ID or name, or show an interactive picker to choose a session | `claude --resume auth-refactor` |
|
||||
| `--session-id` | Use a specific session ID for the conversation (must be a valid UUID) | `claude --session-id "550e8400-e29b-41d4-a716-446655440000"` |
|
||||
| `--setting-sources` | Comma-separated list of setting sources to load (`user`, `project`, `local`) | `claude --setting-sources user,project` |
|
||||
| `--settings` | Path to a settings JSON file or a JSON string to load additional settings from | `claude --settings ./settings.json` |
|
||||
| `--strict-mcp-config` | Only use MCP servers from `--mcp-config`, ignoring all other MCP configurations | `claude --strict-mcp-config --mcp-config ./mcp.json` |
|
||||
| `--system-prompt` | Replace the entire system prompt with custom text (works in both interactive and print modes) | `claude --system-prompt "You are a Python expert"` |
|
||||
| `--system-prompt-file` | Load system prompt from a file, replacing the default prompt (print mode only) | `claude -p --system-prompt-file ./custom-prompt.txt "query"` |
|
||||
| `--teleport` | Resume a [web session](/docs/en/claude-code-on-the-web) in your local terminal | `claude --teleport` |
|
||||
| `--tools` | Restrict which built-in tools Claude can use (works in both interactive and print modes). Use `""` to disable all, `"default"` for all, or tool names like `"Bash,Edit,Read"` | `claude --tools "Bash,Edit,Read"` |
|
||||
| `--verbose` | Enable verbose logging, shows full turn-by-turn output (helpful for debugging in both print and interactive modes) | `claude --verbose` |
|
||||
| `--version`, `-v` | Output the version number | `claude -v` |
|
||||
|
||||
The `--output-format json` flag is particularly useful for scripting and
|
||||
automation, allowing you to parse Claude’s responses programmatically.
|
||||
|
||||
### [](#agents-flag-format) Agents flag format
|
||||
|
||||
The `--agents` flag accepts a JSON object that defines one or more custom subagents. Each subagent requires a unique name (as the key) and a definition object with the following fields:
|
||||
|
||||
| Field | Required | Description |
|
||||
| --- | --- | --- |
|
||||
| `description` | Yes | Natural language description of when the subagent should be invoked |
|
||||
| `prompt` | Yes | The system prompt that guides the subagent’s behavior |
|
||||
| `tools` | No | Array of specific tools the subagent can use (for example, `["Read", "Edit", "Bash"]`). If omitted, inherits all tools |
|
||||
| `model` | No | Model alias to use: `sonnet`, `opus`, or `haiku`. If omitted, uses the default subagent model |
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
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](/docs/en/sub-agents).
|
||||
|
||||
### [](#system-prompt-flags) System prompt flags
|
||||
|
||||
Claude Code provides four flags for customizing the system prompt, each serving a different purpose:
|
||||
|
||||
| Flag | Behavior | Modes | Use Case |
|
||||
| --- | --- | --- | --- |
|
||||
| `--system-prompt` | **Replaces** entire default prompt | Interactive + Print | Complete control over Claude’s behavior and instructions |
|
||||
| `--system-prompt-file` | **Replaces** with file contents | Print only | Load prompts from files for reproducibility and version control |
|
||||
| `--append-system-prompt` | **Appends** to default prompt | Interactive + Print | Add specific instructions while keeping default Claude Code behavior |
|
||||
| `--append-system-prompt-file` | **Appends** file contents to default prompt | Print only | Load additional instructions from files while keeping defaults |
|
||||
|
||||
**When to use each:**
|
||||
|
||||
- **`--system-prompt`**: Use when you need complete control over Claude’s system prompt. This removes all default Claude Code instructions, giving you a blank slate.
|
||||
|
||||
```bash
|
||||
claude --system-prompt "You are a Python expert who only writes type-annotated code"
|
||||
```
|
||||
- **`--system-prompt-file`**: Use when you want to load a custom prompt from a file, useful for team consistency or version-controlled prompt templates.
|
||||
|
||||
```bash
|
||||
claude -p --system-prompt-file ./prompts/code-review.txt "Review this PR"
|
||||
```
|
||||
- **`--append-system-prompt`**: Use when you want to add specific instructions while keeping Claude Code’s default capabilities intact. This is the safest option for most use cases.
|
||||
|
||||
```bash
|
||||
claude --append-system-prompt "Always use TypeScript and include JSDoc comments"
|
||||
```
|
||||
- **`--append-system-prompt-file`**: Use when you want to append instructions from a file while keeping Claude Code’s defaults. Useful for version-controlled additions.
|
||||
|
||||
```bash
|
||||
claude -p --append-system-prompt-file ./prompts/style-rules.txt "Review this PR"
|
||||
```
|
||||
|
||||
`--system-prompt` and `--system-prompt-file` are mutually exclusive. The append flags can be used together with either replacement flag.
|
||||
For most use cases, `--append-system-prompt` or `--append-system-prompt-file` is recommended as they preserve Claude Code’s built-in capabilities while adding your custom requirements. Use `--system-prompt` or `--system-prompt-file` only when you need complete control over the system prompt.
|
||||
|
||||
## [](#see-also) See also
|
||||
|
||||
- [Chrome extension](/docs/en/chrome) - Browser automation and web testing
|
||||
- [Interactive mode](/docs/en/interactive-mode) - Shortcuts, input modes, and interactive features
|
||||
- [Slash commands](/docs/en/slash-commands) - Interactive session commands
|
||||
- [Quickstart guide](/docs/en/quickstart) - Getting started with Claude Code
|
||||
- [Common workflows](/docs/en/common-workflows) - Advanced workflows and patterns
|
||||
- [Settings](/docs/en/settings) - Configuration options
|
||||
- [SDK documentation](https://docs.claude.com/en/docs/agent-sdk) - Programmatic usage and integrations
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,117 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/costs
|
||||
title: Manage costs effectively
|
||||
---
|
||||
|
||||
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) Track your costs
|
||||
|
||||
### [](#using-the-/cost-command) Using the `/cost` command
|
||||
|
||||
The `/cost` command is not intended for Claude Max and Pro subscribers.
|
||||
|
||||
The `/cost` command provides detailed token usage statistics for your current session:
|
||||
|
||||
```bash
|
||||
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) 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).
|
||||
|
||||
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.
|
||||
|
||||
## [](#managing-costs-for-teams) 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](/docs/en/third-party-integrations#litellm), which is an open-source tool that helps companies [track spend by key](https://docs.litellm.ai/docs/proxy/virtual_keys#tracking-spend). This project is unaffiliated with Anthropic and we have not audited its security.
|
||||
|
||||
### [](#rate-limit-recommendations) Rate limit recommendations
|
||||
|
||||
When setting up Claude Code for teams, consider these Token Per Minute (TPM) and Request Per Minute (RPM) per-user recommendations based on your organization size:
|
||||
|
||||
| Team size | TPM per user | RPM per user |
|
||||
| --- | --- | --- |
|
||||
| 1-5 users | 200k-300k | 5-7 |
|
||||
| 5-20 users | 100k-150k | 2.5-3.5 |
|
||||
| 20-50 users | 50k-75k | 1.25-1.75 |
|
||||
| 50-100 users | 25k-35k | 0.62-0.87 |
|
||||
| 100-500 users | 15k-20k | 0.37-0.47 |
|
||||
| 500+ users | 10k-15k | 0.25-0.35 |
|
||||
|
||||
For example, if you have 200 users, you might request 20k TPM for each user, or 4 million total TPM (200\*20,000 = 4 million).
|
||||
The TPM per user decreases as team size grows because we expect fewer users to use Claude Code concurrently in larger organizations. These rate limits apply at the organization level, not per individual user, which means individual users can temporarily consume more than their calculated share when others aren’t actively using the service.
|
||||
|
||||
If you anticipate scenarios with unusually high concurrent usage (such as live training sessions with large groups), you may need higher TPM allocations per user.
|
||||
|
||||
## [](#reduce-token-usage) Reduce token usage
|
||||
|
||||
- **Compact conversations:**
|
||||
- Claude uses auto-compact by default when context reaches approximately 95% capacity. To trigger compaction earlier, set [`CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`](/docs/en/settings#environment-variables) to a lower percentage (for example, `50`)
|
||||
- Toggle auto-compact: Run `/config` and navigate to “Auto-compact enabled”
|
||||
- Use `/compact` manually when context gets large
|
||||
- Add custom instructions: `/compact Focus on code samples and API usage`
|
||||
- Customize compaction by adding to CLAUDE.md:
|
||||
|
||||
```bash
|
||||
# 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) 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) Tracking version changes and updates
|
||||
|
||||
### [](#current-version-information) Current version information
|
||||
|
||||
To check your current Claude Code version and installation details:
|
||||
|
||||
```bash
|
||||
claude doctor
|
||||
```
|
||||
|
||||
This command shows your version, installation type, and system information.
|
||||
|
||||
### [](#understanding-changes-in-claude-code-behavior) 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) 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
|
||||
|
||||
For team deployments, we recommend starting with a small pilot group to
|
||||
establish usage patterns before wider rollout.
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/data-usage
|
||||
title: Data usage
|
||||
---
|
||||
|
||||
## [](#data-policies) Data policies
|
||||
|
||||
### [](#data-training-policy) Data training policy
|
||||
|
||||
**Consumer users (Free, Pro, and Max plans)**:
|
||||
We give you the choice to allow your data to be used to improve future Claude models. We will train new models using data from Free, Pro, and Max accounts when this setting is on (including when you use Claude Code from these accounts).
|
||||
**Commercial users**: (Team and Enterprise plans, API, 3rd-party platforms, and Claude Gov) maintain existing policies: Anthropic does not train generative models using code or prompts sent to Claude Code under commercial terms, unless the customer has chosen to provide their data to us for model improvement (for example, the [Developer Partner Program](https://support.claude.com/en/articles/11174108-about-the-development-partner-program)).
|
||||
|
||||
### [](#development-partner-program) 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) Feedback using the `/bug` command
|
||||
|
||||
If you choose to send us feedback about Claude Code using the `/bug` command, we may use your feedback to improve our products and services. Transcripts shared via `/bug` are retained for 5 years.
|
||||
|
||||
### [](#session-quality-surveys) Session quality surveys
|
||||
|
||||
When you see the “How is Claude doing this session?” prompt in Claude Code, responding to this survey (including selecting “Dismiss”), only your numeric rating (1, 2, 3, or dismiss) is recorded. We do not collect or store any conversation transcripts, inputs, outputs, or other session data as part of this survey. Unlike thumbs up/down feedback or `/bug` reports, this session quality survey is a simple product satisfaction metric. Your responses to this survey do not impact your data training preferences and cannot be used to train our AI models.
|
||||
|
||||
### [](#data-retention) Data retention
|
||||
|
||||
Anthropic retains Claude Code data based on your account type and preferences.
|
||||
**Consumer users (Free, Pro, and Max plans)**:
|
||||
|
||||
- Users who allow data use for model improvement: 5-year retention period to support model development and safety improvements
|
||||
- Users who don’t allow data use for model improvement: 30-day retention period
|
||||
- Privacy settings can be changed at any time at [claude.ai/settings/data-privacy-controls](https://claude.ai/settings/data-privacy-controls).
|
||||
|
||||
**Commercial users (Team, Enterprise, and API)**:
|
||||
|
||||
- Standard: 30-day retention period
|
||||
- Zero data retention: Available with appropriately configured API keys - Claude Code will not retain chat transcripts on servers
|
||||
- Local caching: Claude Code clients may store sessions locally for up to 30 days to enable session resumption (configurable)
|
||||
|
||||
Learn more about data retention practices in our [Privacy Center](https://privacy.anthropic.com/).
|
||||
For full details, please review our [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms) (for Team, Enterprise, and API users) or [Consumer Terms](https://www.anthropic.com/legal/consumer-terms) (for Free, Pro, and Max users) and [Privacy Policy](https://www.anthropic.com/legal/privacy).
|
||||
|
||||
## [](#data-access) Data access
|
||||
|
||||
For all first party users, you can learn more about what data is logged for [local Claude Code](#local-claude-code-data-flow-and-dependencies) and [remote Claude Code](#cloud-execution-data-flow-and-dependencies). Note for remote Claude Code, Claude accesses the repository where you initiate your Claude Code session. Claude does not access repositories that you have connected but have not started a session in.
|
||||
|
||||
## [](#local-claude-code:-data-flow-and-dependencies) Local Claude Code: Data flow and dependencies
|
||||
|
||||
The diagram below shows how Claude Code connects to external services during installation and normal operation. Solid lines indicate required connections, while dashed lines represent optional or user-initiated data flows.
|
||||

|
||||
Claude Code is installed from [NPM](https://www.npmjs.com/package/@anthropic-ai/claude-code). Claude Code runs locally. In order to interact with the LLM, Claude Code sends data over the network. This data includes all user prompts and model outputs. The data is encrypted in transit via TLS and is not encrypted at rest. Claude Code is compatible with most popular VPNs and LLM proxies.
|
||||
Claude Code is built on Anthropic’s APIs. For details regarding our API’s security controls, including our API logging procedures, please refer to compliance artifacts offered in the [Anthropic Trust Center](https://trust.anthropic.com).
|
||||
|
||||
### [](#cloud-execution:-data-flow-and-dependencies) Cloud execution: Data flow and dependencies
|
||||
|
||||
When using [Claude Code on the web](/docs/en/claude-code-on-the-web), sessions run in Anthropic-managed virtual machines instead of locally. In cloud environments:
|
||||
|
||||
- **Code and data storage:** Your repository is cloned to an isolated VM. Code and session data are subject to the retention and usage policies for your account type (see Data retention section above)
|
||||
- **Credentials:** GitHub authentication is handled through a secure proxy; your GitHub credentials never enter the sandbox
|
||||
- **Network traffic:** All outbound traffic goes through a security proxy for audit logging and abuse prevention
|
||||
- **Session data:** Prompts, code changes, and outputs follow the same data policies as local Claude Code usage
|
||||
|
||||
For security details about cloud execution, see [Security](/docs/en/security#cloud-execution-security).
|
||||
|
||||
## [](#telemetry-services) 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) 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. `DISABLE_TELEMETRY=1` to disable. | Default off. `CLAUDE_CODE_USE_VERTEX` must be 1. | Default off. `CLAUDE_CODE_USE_BEDROCK` must be 1. |
|
||||
| **Sentry (Errors)** | Default on. `DISABLE_ERROR_REPORTING=1` to disable. | Default off. `CLAUDE_CODE_USE_VERTEX` must be 1. | Default off. `CLAUDE_CODE_USE_BEDROCK` must be 1. |
|
||||
| **Claude API (`/bug` reports)** | Default on. `DISABLE_BUG_COMMAND=1` to disable. | Default off. `CLAUDE_CODE_USE_VERTEX` must be 1. | Default off. `CLAUDE_CODE_USE_BEDROCK` must be 1. |
|
||||
|
||||
All environment variables can be checked into `settings.json` ([read more](/docs/en/settings)).
|
||||
@@ -0,0 +1,98 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/desktop
|
||||
title: Claude Code on desktop
|
||||
---
|
||||
|
||||

|
||||
|
||||
## [](#claude-code-on-desktop-preview) Claude Code on desktop (Preview)
|
||||
|
||||
The Claude desktop app provides a native interface for running multiple Claude Code sessions on your local machine and seamless integration with Claude Code on the web.
|
||||
|
||||
## [](#installation) Installation
|
||||
|
||||
Download the Claude desktop app for your platform:
|
||||
|
||||
[## macOS
|
||||
|
||||
Universal build for Intel and Apple Silicon](https://claude.ai/api/desktop/darwin/universal/dmg/latest/redirect?utm_source=claude_code&utm_medium=docs)[## Windows
|
||||
|
||||
For x64 processors](https://claude.ai/api/desktop/win32/x64/exe/latest/redirect?utm_source=claude_code&utm_medium=docs)
|
||||
|
||||
For Windows ARM64, [download here](https://claude.ai/api/desktop/win32/arm64/exe/latest/redirect?utm_source=claude_code&utm_medium=docs).
|
||||
|
||||
Local sessions are not available on Windows ARM64.
|
||||
|
||||
## [](#features) Features
|
||||
|
||||
Claude Code on desktop provides:
|
||||
|
||||
- **Parallel local sessions with `git` worktrees**: Run multiple Claude Code sessions simultaneously in the same repository, each with its own isolated `git` worktree
|
||||
- **Include files listed in your `.gitignore` in your worktrees**: Automatically copy files in your `.gitignore`, like `.env`, to new worktrees using `.worktreeinclude`
|
||||
- **Launch Claude Code on the web**: Kick off secure cloud sessions directly from the desktop app
|
||||
|
||||
## [](#using-git-worktrees) Using Git worktrees
|
||||
|
||||
Claude Code on desktop enables running multiple Claude Code sessions in the same repository using Git worktrees. Each session gets its own isolated worktree, allowing Claude to work on different tasks without conflicts. The default location for worktrees is `~/.claude-worktrees` but this can be configured in your settings on the Claude desktop app.
|
||||
|
||||
If you start a local session in a folder that does not have Git initialized, the desktop app will not create a new worktree.
|
||||
|
||||
### [](#copying-files-ignored-with-gitignore) Copying files ignored with `.gitignore`
|
||||
|
||||
When Claude Code creates a worktree, files ignored via `.gitignore` aren’t automatically available. Including a `.worktreeinclude` file solves this by specifying which ignored files should be copied to new worktrees.
|
||||
Create a `.worktreeinclude` file in your repository root:
|
||||
|
||||
```bash
|
||||
.env
|
||||
.env.local
|
||||
.env.*
|
||||
**/.claude/settings.local.json
|
||||
```
|
||||
|
||||
The file uses `.gitignore`-style patterns. When a worktree is created, files matching these patterns that are also in your `.gitignore` will be copied from your main repository to the worktree.
|
||||
|
||||
Only files that are both matched by `.worktreeinclude` AND listed in `.gitignore` are copied. This prevents accidentally duplicating tracked files.
|
||||
|
||||
### [](#launch-claude-code-on-the-web) Launch Claude Code on the web
|
||||
|
||||
From the desktop app, you can kick off Claude Code sessions that run on Anthropic’s secure cloud infrastructure.
|
||||
To start a web session from desktop, select a remote environment when creating a new session.
|
||||
For more details, see [Claude Code on the web](/docs/en/claude-code-on-the-web).
|
||||
|
||||
## [](#bundled-claude-code-version) Bundled Claude Code version
|
||||
|
||||
Claude Code on desktop includes a bundled, stable version of Claude Code to ensure a consistent experience for all desktop users. The bundled version is required and downloaded on first launch even if a version of Claude Code exists on the computer. Desktop automatically manages version updates and cleans up old versions.
|
||||
|
||||
The bundled Claude Code version in Desktop may differ from the latest CLI version. Desktop prioritizes stability while the CLI may have newer features.
|
||||
|
||||
## [](#environment-configuration) Environment configuration
|
||||
|
||||
For local environments, Claude Code on desktop automatically extracts your `$PATH` environment variable from your shell configuration. This allows local sessions to access development tools like `yarn`, `npm`, `node`, and other commands available in your terminal without additional setup.
|
||||
|
||||
### [](#custom-environment-variables) Custom environment variables
|
||||
|
||||
Select “Local” environment, then to the right, select the settings button. This will open a dialog where you can update local environment variables. This is useful for setting project-specific variables or API keys that your development workflows require. Environment variable values are masked in the UI for security reasons.
|
||||
|
||||
Environment variables must be specified as key-value pairs, in [`.env` format](https://www.dotenv.org/). For example:
|
||||
|
||||
```bash
|
||||
API_KEY=your_api_key
|
||||
DEBUG=true
|
||||
|
||||
# Multiline values - wrap in quotes
|
||||
CERT="-----BEGIN CERT-----
|
||||
MIIE...
|
||||
-----END CERT-----"
|
||||
```
|
||||
|
||||
## [](#enterprise-configuration) Enterprise configuration
|
||||
|
||||
Organizations can disable local Claude Code use in the desktop application with the `isClaudeCodeForDesktopEnabled` [enterprise policy option](https://support.claude.com/en/articles/12622667-enterprise-configuration#h_003283c7cb). Additionally, Claude Code on the web can be disabled in your [admin settings](https://claude.ai/admin-settings/claude-code).
|
||||
|
||||
## [](#related-resources) Related resources
|
||||
|
||||
- [Claude Code on the web](/docs/en/claude-code-on-the-web)
|
||||
- [Claude Desktop support articles](https://support.claude.com/en/collections/16163169-claude-desktop)
|
||||
- [Enterprise Configuration](https://support.claude.com/en/articles/12622667-enterprise-configuration)
|
||||
- [Common workflows](/docs/en/common-workflows)
|
||||
- [Settings reference](/docs/en/settings)
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/devcontainer
|
||||
title: Development containers
|
||||
---
|
||||
|
||||
The reference [devcontainer setup](https://github.com/anthropics/claude-code/tree/main/.devcontainer) and associated [Dockerfile](https://github.com/anthropics/claude-code/blob/main/.devcontainer/Dockerfile) offer a preconfigured development container that you can use as is, or customize for your needs. This devcontainer works with the Visual Studio Code [Dev Containers extension](https://code.visualstudio.com/docs/devcontainers/containers) and similar tools.
|
||||
The container’s enhanced security measures (isolation and firewall rules) allow you to run `claude --dangerously-skip-permissions` to bypass permission prompts for unattended operation.
|
||||
|
||||
While the devcontainer provides substantial protections, no system is completely immune to all attacks.
|
||||
When executed with `--dangerously-skip-permissions`, devcontainers don’t prevent a malicious project from exfiltrating anything accessible in the devcontainer including Claude Code credentials.
|
||||
We recommend only using devcontainers when developing with trusted repositories.
|
||||
Always maintain good security practices and monitor Claude’s activities.
|
||||
|
||||
## [](#key-features) 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) 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) 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) 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) 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) Example use cases
|
||||
|
||||
### [](#secure-client-work) Secure client work
|
||||
|
||||
Use devcontainers to isolate different client projects, ensuring code and credentials never mix between environments.
|
||||
|
||||
### [](#team-onboarding) 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) Consistent CI/CD environments
|
||||
|
||||
Mirror your devcontainer configuration in CI/CD pipelines to ensure development and production environments match.
|
||||
|
||||
## [](#related-resources) Related resources
|
||||
|
||||
- [VS Code devcontainers documentation](https://code.visualstudio.com/docs/devcontainers/containers)
|
||||
- [Claude Code security best practices](/docs/en/security)
|
||||
- [Enterprise network configuration](/docs/en/network-config)
|
||||
@@ -0,0 +1,351 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/discover-plugins
|
||||
title: Discover and install prebuilt plugins through marketplaces
|
||||
---
|
||||
|
||||
Plugins extend Claude Code with custom commands, agents, hooks, and MCP servers. Plugin marketplaces are catalogs that help you discover and install these extensions without building them yourself.
|
||||
Looking to create and distribute your own marketplace? See [Create and distribute a plugin marketplace](/docs/en/plugin-marketplaces).
|
||||
|
||||
## [](#how-marketplaces-work) How marketplaces work
|
||||
|
||||
A marketplace is a catalog of plugins that someone else has created and shared. Using a marketplace is a two-step process:
|
||||
|
||||
1
|
||||
|
||||
Add the marketplace
|
||||
|
||||
This registers the catalog with Claude Code so you can browse what’s available. No plugins are installed yet.
|
||||
|
||||
2
|
||||
|
||||
Install individual plugins
|
||||
|
||||
Browse the catalog and install the plugins you want.
|
||||
|
||||
Think of it like adding an app store: adding the store gives you access to browse its collection, but you still choose which apps to download individually.
|
||||
|
||||
## [](#official-anthropic-marketplace) Official Anthropic marketplace
|
||||
|
||||
The official Anthropic marketplace (`claude-plugins-official`) is automatically available when you start Claude Code. Run `/plugin` and go to the **Discover** tab to browse what’s available.
|
||||
To install a plugin from the official marketplace:
|
||||
|
||||
```bash
|
||||
/plugin install plugin-name@claude-plugins-official
|
||||
```
|
||||
|
||||
The official marketplace is maintained by Anthropic. To distribute your own plugins, [create your own marketplace](/docs/en/plugin-marketplaces) and share it with users.
|
||||
|
||||
The official marketplace includes several categories of plugins:
|
||||
|
||||
### [](#code-intelligence) Code intelligence
|
||||
|
||||
Code intelligence plugins help Claude understand your codebase more deeply. With these plugins installed, Claude can jump to definitions, find references, and see type errors immediately after edits. These plugins use the [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) (LSP), the same technology that powers VS Code’s code intelligence.
|
||||
These plugins require the language server binary to be installed on your system. If you already have a language server installed, Claude may prompt you to install the corresponding plugin when you open a project.
|
||||
|
||||
| Language | Plugin | Binary required |
|
||||
| --- | --- | --- |
|
||||
| C/C++ | `clangd-lsp` | `clangd` |
|
||||
| C# | `csharp-lsp` | `csharp-ls` |
|
||||
| Go | `gopls-lsp` | `gopls` |
|
||||
| Java | `jdtls-lsp` | `jdtls` |
|
||||
| Lua | `lua-lsp` | `lua-language-server` |
|
||||
| PHP | `php-lsp` | `intelephense` |
|
||||
| Python | `pyright-lsp` | `pyright-langserver` |
|
||||
| Rust | `rust-analyzer-lsp` | `rust-analyzer` |
|
||||
| Swift | `swift-lsp` | `sourcekit-lsp` |
|
||||
| TypeScript | `typescript-lsp` | `typescript-language-server` |
|
||||
|
||||
You can also [create your own LSP plugin](/docs/en/plugins-reference#lsp-servers) for other languages.
|
||||
|
||||
If you see `Executable not found in $PATH` in the `/plugin` Errors tab after installing a plugin, install the required binary from the table above.
|
||||
|
||||
### [](#external-integrations) External integrations
|
||||
|
||||
These plugins bundle pre-configured [MCP servers](/docs/en/mcp) so you can connect Claude to external services without manual setup:
|
||||
|
||||
- **Source control**: `github`, `gitlab`
|
||||
- **Project management**: `atlassian` (Jira/Confluence), `asana`, `linear`, `notion`
|
||||
- **Design**: `figma`
|
||||
- **Infrastructure**: `vercel`, `firebase`, `supabase`
|
||||
- **Communication**: `slack`
|
||||
- **Monitoring**: `sentry`
|
||||
|
||||
### [](#development-workflows) Development workflows
|
||||
|
||||
Plugins that add commands and agents for common development tasks:
|
||||
|
||||
- **commit-commands**: Git commit workflows including commit, push, and PR creation
|
||||
- **pr-review-toolkit**: Specialized agents for reviewing pull requests
|
||||
- **agent-sdk-dev**: Tools for building with the Claude Agent SDK
|
||||
- **plugin-dev**: Toolkit for creating your own plugins
|
||||
|
||||
### [](#output-styles) Output styles
|
||||
|
||||
Customize how Claude responds:
|
||||
|
||||
- **explanatory-output-style**: Educational insights about implementation choices
|
||||
- **learning-output-style**: Interactive learning mode for skill building
|
||||
|
||||
## [](#try-it:-add-the-demo-marketplace) Try it: add the demo marketplace
|
||||
|
||||
Anthropic also maintains a [demo plugins marketplace](https://github.com/anthropics/claude-code/tree/main/plugins) (`claude-code-plugins`) with example plugins that show what’s possible with the plugin system. Unlike the official marketplace, you need to add this one manually.
|
||||
|
||||
1
|
||||
|
||||
Add the marketplace
|
||||
|
||||
From within Claude Code, run the `plugin marketplace add` command for the `anthropics/claude-code` marketplace:
|
||||
|
||||
```bash
|
||||
/plugin marketplace add anthropics/claude-code
|
||||
```
|
||||
|
||||
This downloads the marketplace catalog and makes its plugins available to you.
|
||||
|
||||
2
|
||||
|
||||
Browse available plugins
|
||||
|
||||
Run `/plugin` to open the plugin manager. This opens a tabbed interface with four tabs you can cycle through using **Tab** (or **Shift+Tab** to go backward):
|
||||
|
||||
- **Discover**: browse available plugins from all your marketplaces
|
||||
- **Installed**: view and manage your installed plugins
|
||||
- **Marketplaces**: add, remove, or update your added marketplaces
|
||||
- **Errors**: view any plugin loading errors
|
||||
|
||||
Go to the **Discover** tab to see plugins from the marketplace you just added.
|
||||
|
||||
3
|
||||
|
||||
Install a plugin
|
||||
|
||||
Select a plugin to view its details, then choose an installation scope:
|
||||
|
||||
- **User scope**: install for yourself across all projects
|
||||
- **Project scope**: install for all collaborators on this repository
|
||||
- **Local scope**: install for yourself in this repository only
|
||||
|
||||
For example, select **commit-commands** (a plugin that adds git workflow commands) and install it to your user scope.You can also install directly from the command line:
|
||||
|
||||
```bash
|
||||
/plugin install commit-commands@anthropics-claude-code
|
||||
```
|
||||
|
||||
See [Configuration scopes](/docs/en/settings#configuration-scopes) to learn more about scopes.
|
||||
|
||||
4
|
||||
|
||||
Use your new plugin
|
||||
|
||||
After installing, the plugin’s commands are immediately available. Plugin commands are namespaced by the plugin name, so **commit-commands** provides commands like `/commit-commands:commit`.Try it out by making a change to a file and running:
|
||||
|
||||
```bash
|
||||
/commit-commands:commit
|
||||
```
|
||||
|
||||
This stages your changes, generates a commit message, and creates the commit.Each plugin works differently. Check the plugin’s description in the **Discover** tab or its homepage to learn what commands and capabilities it provides.
|
||||
|
||||
The rest of this guide covers all the ways you can add marketplaces, install plugins, and manage your configuration.
|
||||
|
||||
## [](#add-marketplaces) Add marketplaces
|
||||
|
||||
Use the `/plugin marketplace add` command to add marketplaces from different sources.
|
||||
|
||||
**Shortcuts**: You can use `/plugin market` instead of `/plugin marketplace`, and `rm` instead of `remove`.
|
||||
|
||||
- **GitHub repositories**: `owner/repo` format (for example, `anthropics/claude-code`)
|
||||
- **Git URLs**: any git repository URL (GitLab, Bitbucket, self-hosted)
|
||||
- **Local paths**: directories or direct paths to `marketplace.json` files
|
||||
- **Remote URLs**: direct URLs to hosted `marketplace.json` files
|
||||
|
||||
### [](#add-from-github) Add from GitHub
|
||||
|
||||
Add a GitHub repository that contains a `.claude-plugin/marketplace.json` file using the `owner/repo` format—where `owner` is the GitHub username or organization and `repo` is the repository name.
|
||||
For example, `anthropics/claude-code` refers to the `claude-code` repository owned by `anthropics`:
|
||||
|
||||
```bash
|
||||
/plugin marketplace add anthropics/claude-code
|
||||
```
|
||||
|
||||
### [](#add-from-other-git-hosts) Add from other Git hosts
|
||||
|
||||
Add any git repository by providing the full URL. This works with any Git host, including GitLab, Bitbucket, and self-hosted servers:
|
||||
Using HTTPS:
|
||||
|
||||
```bash
|
||||
/plugin marketplace add https://gitlab.com/company/plugins.git
|
||||
```
|
||||
|
||||
Using SSH:
|
||||
|
||||
```bash
|
||||
/plugin marketplace add [email protected]:company/plugins.git
|
||||
```
|
||||
|
||||
To add a specific branch or tag, append `#` followed by the ref:
|
||||
|
||||
```bash
|
||||
/plugin marketplace add https://gitlab.com/company/plugins.git#v1.0.0
|
||||
```
|
||||
|
||||
### [](#add-from-local-paths) Add from local paths
|
||||
|
||||
Add a local directory that contains a `.claude-plugin/marketplace.json` file:
|
||||
|
||||
```bash
|
||||
/plugin marketplace add ./my-marketplace
|
||||
```
|
||||
|
||||
You can also add a direct path to a `marketplace.json` file:
|
||||
|
||||
```bash
|
||||
/plugin marketplace add ./path/to/marketplace.json
|
||||
```
|
||||
|
||||
### [](#add-from-remote-urls) Add from remote URLs
|
||||
|
||||
Add a remote `marketplace.json` file via URL:
|
||||
|
||||
```bash
|
||||
/plugin marketplace add https://example.com/marketplace.json
|
||||
```
|
||||
|
||||
URL-based marketplaces have some limitations compared to Git-based marketplaces. If you encounter “path not found” errors when installing plugins, see [Troubleshooting](/docs/en/plugin-marketplaces#plugins-with-relative-paths-fail-in-url-based-marketplaces).
|
||||
|
||||
## [](#install-plugins) Install plugins
|
||||
|
||||
Once you’ve added marketplaces, you can install plugins directly (installs to user scope by default):
|
||||
|
||||
```bash
|
||||
/plugin install plugin-name@marketplace-name
|
||||
```
|
||||
|
||||
To choose a different [installation scope](/docs/en/settings#configuration-scopes), use the interactive UI: run `/plugin`, go to the **Discover** tab, and press **Enter** on a plugin. You’ll see options for:
|
||||
|
||||
- **User scope** (default): install for yourself across all projects
|
||||
- **Project scope**: install for all collaborators on this repository (adds to `.claude/settings.json`)
|
||||
- **Local scope**: install for yourself in this repository only (not shared with collaborators)
|
||||
|
||||
You may also see plugins with **managed** scope—these are installed by administrators via [managed settings](/docs/en/settings#settings-files) and cannot be modified.
|
||||
Run `/plugin` and go to the **Installed** tab to see your plugins grouped by scope.
|
||||
|
||||
Make sure you trust a plugin before installing it. Anthropic does not control what MCP servers, files, or other software are included in plugins and cannot verify that they work as intended. Check each plugin’s homepage for more information.
|
||||
|
||||
## [](#manage-installed-plugins) Manage installed plugins
|
||||
|
||||
Run `/plugin` and go to the **Installed** tab to view, enable, disable, or uninstall your plugins.
|
||||
You can also manage plugins with direct commands.
|
||||
Disable a plugin without uninstalling:
|
||||
|
||||
```bash
|
||||
/plugin disable plugin-name@marketplace-name
|
||||
```
|
||||
|
||||
Re-enable a disabled plugin:
|
||||
|
||||
```bash
|
||||
/plugin enable plugin-name@marketplace-name
|
||||
```
|
||||
|
||||
Completely remove a plugin:
|
||||
|
||||
```bash
|
||||
/plugin uninstall plugin-name@marketplace-name
|
||||
```
|
||||
|
||||
The `--scope` option lets you target a specific scope with CLI commands:
|
||||
|
||||
```bash
|
||||
claude plugin install formatter@your-org --scope project
|
||||
claude plugin uninstall formatter@your-org --scope project
|
||||
```
|
||||
|
||||
## [](#manage-marketplaces) Manage marketplaces
|
||||
|
||||
You can manage marketplaces through the interactive `/plugin` interface or with CLI commands.
|
||||
|
||||
### [](#use-the-interactive-interface) Use the interactive interface
|
||||
|
||||
Run `/plugin` and go to the **Marketplaces** tab to:
|
||||
|
||||
- View all your added marketplaces with their sources and status
|
||||
- Add new marketplaces
|
||||
- Update marketplace listings to fetch the latest plugins
|
||||
- Remove marketplaces you no longer need
|
||||
|
||||
### [](#use-cli-commands) Use CLI commands
|
||||
|
||||
You can also manage marketplaces with direct commands.
|
||||
List all configured marketplaces:
|
||||
|
||||
```bash
|
||||
/plugin marketplace list
|
||||
```
|
||||
|
||||
Refresh plugin listings from a marketplace:
|
||||
|
||||
```bash
|
||||
/plugin marketplace update marketplace-name
|
||||
```
|
||||
|
||||
Remove a marketplace:
|
||||
|
||||
```bash
|
||||
/plugin marketplace remove marketplace-name
|
||||
```
|
||||
|
||||
Removing a marketplace will uninstall any plugins you installed from it.
|
||||
|
||||
### [](#configure-auto-updates) Configure auto-updates
|
||||
|
||||
Claude Code can automatically update marketplaces and their installed plugins at startup. When auto-update is enabled for a marketplace, Claude Code refreshes the marketplace data and updates installed plugins to their latest versions. If any plugins were updated, you’ll see a notification suggesting you restart Claude Code.
|
||||
Toggle auto-update for individual marketplaces through the UI:
|
||||
|
||||
1. Run `/plugin` to open the plugin manager
|
||||
2. Select **Marketplaces**
|
||||
3. Choose a marketplace from the list
|
||||
4. Select **Enable auto-update** or **Disable auto-update**
|
||||
|
||||
Official Anthropic marketplaces have auto-update enabled by default. Third-party and local development marketplaces have auto-update disabled by default.
|
||||
To disable all automatic updates entirely for both Claude Code and all plugins, set the `DISABLE_AUTOUPDATER` environment variable. See [Auto updates](/docs/en/setup#auto-updates) for details.
|
||||
To keep plugin auto-updates enabled while disabling Claude Code auto-updates, set `FORCE_AUTOUPDATE_PLUGINS=true` along with `DISABLE_AUTOUPDATER`:
|
||||
|
||||
```bash
|
||||
export DISABLE_AUTOUPDATER=true
|
||||
export FORCE_AUTOUPDATE_PLUGINS=true
|
||||
```
|
||||
|
||||
This is useful when you want to manage Claude Code updates manually but still receive automatic plugin updates.
|
||||
|
||||
## [](#configure-team-marketplaces) Configure team marketplaces
|
||||
|
||||
Team admins can set up automatic marketplace installation for projects by adding marketplace configuration to `.claude/settings.json`. When team members trust the repository folder, Claude Code prompts them to install these marketplaces and plugins.
|
||||
For full configuration options including `extraKnownMarketplaces` and `enabledPlugins`, see [Plugin settings](/docs/en/settings#plugin-settings).
|
||||
|
||||
## [](#troubleshooting) Troubleshooting
|
||||
|
||||
### [](#/plugin-command-not-recognized) /plugin command not recognized
|
||||
|
||||
If you see “unknown command” or the `/plugin` command doesn’t appear:
|
||||
|
||||
1. **Check your version**: Run `claude --version`. Plugins require version 1.0.33 or later.
|
||||
2. **Update Claude Code**:
|
||||
- **Homebrew**: `brew upgrade claude-code`
|
||||
- **npm**: `npm update -g @anthropic-ai/claude-code`
|
||||
- **Native installer**: Re-run the install command from [Setup](/docs/en/setup)
|
||||
3. **Restart Claude Code**: After updating, restart your terminal and run `claude` again.
|
||||
|
||||
### [](#common-issues) Common issues
|
||||
|
||||
- **Marketplace not loading**: Verify the URL is accessible and that `.claude-plugin/marketplace.json` exists at the path
|
||||
- **Plugin installation failures**: Check that plugin source URLs are accessible and repositories are public (or you have access)
|
||||
- **Files not found after installation**: Plugins are copied to a cache, so paths referencing files outside the plugin directory won’t work
|
||||
- **Plugin Skills not appearing**: Clear the cache with `rm -rf ~/.claude/plugins/cache`, restart Claude Code, and reinstall the plugin. See [Plugin Skills not appearing](/docs/en/skills#plugin-skills-not-appearing-after-installation) for details.
|
||||
|
||||
For detailed troubleshooting with solutions, see [Troubleshooting](/docs/en/plugin-marketplaces#troubleshooting) in the marketplace guide. For debugging tools, see [Debugging and development tools](/docs/en/plugins-reference#debugging-and-development-tools).
|
||||
|
||||
## [](#next-steps) Next steps
|
||||
|
||||
- **Build your own plugins**: See [Plugins](/docs/en/plugins) to create custom commands, agents, and hooks
|
||||
- **Create a marketplace**: See [Create a plugin marketplace](/docs/en/plugin-marketplaces) to distribute plugins to your team or community
|
||||
- **Technical reference**: See [Plugins reference](/docs/en/plugins-reference) for complete specifications
|
||||
@@ -0,0 +1,629 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/github-actions
|
||||
title: Claude Code GitHub Actions
|
||||
---
|
||||
|
||||
Claude Code GitHub Actions brings AI-powered automation to your GitHub workflow. With a simple `@claude` mention in any PR or issue, Claude can analyze your code, create pull requests, implement features, and fix bugs - all while following your project’s standards.
|
||||
|
||||
Claude Code GitHub Actions is built on top of the [Claude Code
|
||||
SDK](https://docs.claude.com/en/docs/agent-sdk), which enables programmatic integration of
|
||||
Claude Code into your applications. You can use the SDK to build custom
|
||||
automation workflows beyond GitHub Actions.
|
||||
|
||||
**Claude Opus 4.5 is now available.** Claude Code GitHub Actions default to Sonnet. To use Opus 4.5, configure the [model parameter](#breaking-changes-reference) to use `claude-opus-4-5-20251101`.
|
||||
|
||||
## [](#why-use-claude-code-github-actions) 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) What can Claude do?
|
||||
|
||||
Claude Code provides a powerful GitHub Action that transforms how you work with code:
|
||||
|
||||
### [](#claude-code-action) 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) Setup
|
||||
|
||||
## [](#quick-setup) Quick setup
|
||||
|
||||
The easiest way to set up this action is through Claude Code in the terminal. Just open claude and run `/install-github-app`.
|
||||
This command will guide you through setting up the GitHub app and required secrets.
|
||||
|
||||
- You must be a repository admin to install the GitHub app and add secrets
|
||||
- The GitHub app will request read & write permissions for Contents, Issues, and Pull requests
|
||||
- This quickstart method is only available for direct Claude API users. If
|
||||
you’re using AWS Bedrock or Google Vertex AI, please see the [Using with AWS
|
||||
Bedrock & Google Vertex AI](#using-with-aws-bedrock-%26-google-vertex-ai)
|
||||
section.
|
||||
|
||||
## [](#manual-setup) 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>
|
||||
The Claude GitHub app requires the following repository permissions:
|
||||
- **Contents**: Read & write (to modify repository files)
|
||||
- **Issues**: Read & write (to respond to issues)
|
||||
- **Pull requests**: Read & write (to create PRs and push changes)For more details on security and permissions, see the [security documentation](https://github.com/anthropics/claude-code-action/blob/main/docs/security.md).
|
||||
2. **Add ANTHROPIC\_API\_KEY** to your repository secrets ([Learn how to use secrets in GitHub Actions](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions))
|
||||
3. **Copy the workflow file** from [examples/claude.yml](https://github.com/anthropics/claude-code-action/blob/main/examples/claude.yml) into your repository’s `.github/workflows/`
|
||||
|
||||
After completing either the quickstart or manual setup, test the action by tagging `@claude` in an issue or PR comment.
|
||||
|
||||
## [](#upgrading-from-beta) Upgrading from Beta
|
||||
|
||||
Claude Code GitHub Actions v1.0 introduces breaking changes that require updating your workflow files in order to upgrade to v1.0 from the beta version.
|
||||
|
||||
If you’re currently using the beta version of Claude Code GitHub Actions, we recommend that you update your workflows to use the GA version. The new version simplifies configuration while adding powerful new features like automatic mode detection.
|
||||
|
||||
### [](#essential-changes) 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) 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) Before and After Example
|
||||
|
||||
**Beta version:**
|
||||
|
||||
```bash
|
||||
- uses: anthropics/claude-code-action@beta
|
||||
with:
|
||||
mode: "tag"
|
||||
direct_prompt: "Review this PR for security issues"
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
custom_instructions: "Follow our coding standards"
|
||||
max_turns: "10"
|
||||
model: "claude-sonnet-4-5-20250929"
|
||||
```
|
||||
|
||||
**GA version (v1.0):**
|
||||
|
||||
```bash
|
||||
- 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
|
||||
```
|
||||
|
||||
The action now automatically detects whether to run in interactive mode (responds to `@claude` mentions) or automation mode (runs immediately with a prompt) based on your configuration.
|
||||
|
||||
## [](#example-use-cases) 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) Basic workflow
|
||||
|
||||
```bash
|
||||
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) Using slash commands
|
||||
|
||||
```bash
|
||||
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) Custom automation with prompts
|
||||
|
||||
```bash
|
||||
name: Daily Report
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 9 * * *"
|
||||
jobs:
|
||||
report:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
prompt: "Generate a summary of yesterday's commits and open issues"
|
||||
claude_args: "--model claude-opus-4-5-20251101"
|
||||
```
|
||||
|
||||
### [](#common-use-cases) Common use cases
|
||||
|
||||
In issue or PR comments:
|
||||
|
||||
```bash
|
||||
@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) Best practices
|
||||
|
||||
### [](#claude-md-configuration) 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) Security considerations
|
||||
|
||||
Never commit API keys directly to your repository.
|
||||
|
||||
For comprehensive security guidance including permissions, authentication, and best practices, see the [Claude Code Action security documentation](https://github.com/anthropics/claude-code-action/blob/main/docs/security.md).
|
||||
Always use GitHub Secrets for API keys:
|
||||
|
||||
- Add your API key as a repository secret named `ANTHROPIC_API_KEY`
|
||||
- Reference it in workflows: `anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}`
|
||||
- Limit action permissions to only what’s necessary
|
||||
- Review Claude’s suggestions before merging
|
||||
|
||||
Always use GitHub Secrets (for example, `${{ secrets.ANTHROPIC_API_KEY }}`) rather than hardcoding API keys directly in your workflow files.
|
||||
|
||||
### [](#optimizing-performance) Optimizing performance
|
||||
|
||||
Use issue templates to provide context, keep your `CLAUDE.md` concise and focused, and configure appropriate timeouts for your workflows.
|
||||
|
||||
### [](#ci-costs) 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) Configuration examples
|
||||
|
||||
The Claude Code Action v1 simplifies configuration with unified parameters:
|
||||
|
||||
```bash
|
||||
- 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.
|
||||
|
||||
When responding to issue or PR comments, Claude automatically responds to @claude mentions. For other events, use the `prompt` parameter to provide instructions.
|
||||
|
||||
## [](#using-with-aws-bedrock-&-google-vertex-ai) 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) Prerequisites
|
||||
|
||||
Before setting up Claude Code GitHub Actions with cloud providers, you need:
|
||||
|
||||
#### [](#for-google-cloud-vertex-ai:) 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:) 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
|
||||
|
||||
1
|
||||
|
||||
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>
|
||||
2. Fill in the basic information:
|
||||
- **GitHub App name**: Choose a unique name (e.g., “YourOrg Claude Assistant”)
|
||||
- **Homepage URL**: Your organization’s website or the repository URL
|
||||
3. Configure the app settings:
|
||||
- **Webhooks**: Uncheck “Active” (not needed for this integration)
|
||||
4. Set the required permissions:
|
||||
- **Repository permissions**:
|
||||
- Contents: Read & Write
|
||||
- Issues: Read & Write
|
||||
- Pull requests: Read & Write
|
||||
5. Click “Create GitHub App”
|
||||
6. After creation, click “Generate a private key” and save the downloaded `.pem` file
|
||||
7. Note your App ID from the app settings page
|
||||
8. Install the app to your repository:
|
||||
- From your app’s settings page, click “Install App” in the left sidebar
|
||||
- Select your account or organization
|
||||
- Choose “Only select repositories” and select the specific repository
|
||||
- Click “Install”
|
||||
9. Add the private key as a secret to your repository:
|
||||
- Go to your repository’s Settings → Secrets and variables → Actions
|
||||
- Create a new secret named `APP_PRIVATE_KEY` with the contents of the `.pem` file
|
||||
10. Add the App ID as a secret:
|
||||
|
||||
- Create a new secret named `APP_ID` with your GitHub App’s ID
|
||||
|
||||
This app will be used with the [actions/create-github-app-token](https://github.com/actions/create-github-app-token) action to generate authentication tokens in your workflows.
|
||||
|
||||
**Alternative for Claude API or if you don’t want to setup your own Github app**: Use the official Anthropic app:
|
||||
|
||||
1. Install from: <https://github.com/apps/claude>
|
||||
2. No additional configuration needed for authentication
|
||||
|
||||
2
|
||||
|
||||
Configure cloud provider authentication
|
||||
|
||||
Choose your cloud provider and set up secure authentication:
|
||||
|
||||
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
|
||||
|
||||
OIDC is more secure than using static AWS access keys because credentials are temporary and automatically rotated.
|
||||
|
||||
See [AWS documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html) for detailed OIDC setup instructions.
|
||||
|
||||
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
|
||||
|
||||
Workload Identity Federation eliminates the need for downloadable service account keys, improving security.
|
||||
|
||||
For detailed setup instructions, consult the [Google Cloud Workload Identity Federation documentation](https://cloud.google.com/iam/docs/workload-identity-federation).
|
||||
|
||||
3
|
||||
|
||||
Add Required Secrets
|
||||
|
||||
Add the following secrets to your repository (Settings → Secrets and variables → Actions):
|
||||
|
||||
#### [](#for-claude-api-direct-:) 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) 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) 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
|
||||
|
||||
4
|
||||
|
||||
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:
|
||||
|
||||
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 |
|
||||
|
||||
```bash
|
||||
name: Claude PR Action
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
issues: write
|
||||
id-token: write
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_review_comment:
|
||||
types: [created]
|
||||
issues:
|
||||
types: [opened, assigned]
|
||||
|
||||
jobs:
|
||||
claude-pr:
|
||||
if: |
|
||||
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'issues' && contains(github.event.issue.body, '@claude'))
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
AWS_REGION: us-west-2
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Generate GitHub App token
|
||||
id: app-token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.APP_ID }}
|
||||
private-key: ${{ secrets.APP_PRIVATE_KEY }}
|
||||
|
||||
- name: Configure AWS Credentials (OIDC)
|
||||
uses: aws-actions/configure-aws-credentials@v4
|
||||
with:
|
||||
role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }}
|
||||
aws-region: us-west-2
|
||||
|
||||
- uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
github_token: ${{ steps.app-token.outputs.token }}
|
||||
use_bedrock: "true"
|
||||
claude_args: '--model us.anthropic.claude-sonnet-4-5-20250929-v1:0 --max-turns 10'
|
||||
```
|
||||
|
||||
The model ID format for Bedrock includes the region prefix (e.g., `us.anthropic.claude...`) and version suffix.
|
||||
|
||||
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 |
|
||||
|
||||
```bash
|
||||
name: Claude PR Action
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
issues: write
|
||||
id-token: write
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_review_comment:
|
||||
types: [created]
|
||||
issues:
|
||||
types: [opened, assigned]
|
||||
|
||||
jobs:
|
||||
claude-pr:
|
||||
if: |
|
||||
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'issues' && contains(github.event.issue.body, '@claude'))
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Generate GitHub App token
|
||||
id: app-token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.APP_ID }}
|
||||
private-key: ${{ secrets.APP_PRIVATE_KEY }}
|
||||
|
||||
- name: Authenticate to Google Cloud
|
||||
id: auth
|
||||
uses: google-github-actions/auth@v2
|
||||
with:
|
||||
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
|
||||
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
|
||||
|
||||
- uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
github_token: ${{ steps.app-token.outputs.token }}
|
||||
trigger_phrase: "@claude"
|
||||
use_vertex: "true"
|
||||
claude_args: '--model claude-sonnet-4@20250514 --max-turns 10'
|
||||
env:
|
||||
ANTHROPIC_VERTEX_PROJECT_ID: ${{ steps.auth.outputs.project_id }}
|
||||
CLOUD_ML_REGION: us-east5
|
||||
VERTEX_REGION_CLAUDE_3_7_SONNET: us-east5
|
||||
```
|
||||
|
||||
The project ID is automatically retrieved from the Google Cloud authentication step, so you don’t need to hardcode it.
|
||||
|
||||
## [](#troubleshooting) Troubleshooting
|
||||
|
||||
### [](#claude-not-responding-to-@claude-commands) 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) 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) 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) Advanced configuration
|
||||
|
||||
### [](#action-parameters) 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
|
||||
|
||||
#### [](#pass-cli-arguments) Pass CLI arguments
|
||||
|
||||
The `claude_args` parameter accepts any Claude Code CLI arguments:
|
||||
|
||||
```bash
|
||||
claude_args: "--max-turns 5 --model claude-sonnet-4-5-20250929 --mcp-config /path/to/config.json"
|
||||
```
|
||||
|
||||
Common arguments:
|
||||
|
||||
- `--max-turns`: Maximum conversation turns (default: 10)
|
||||
- `--model`: Model to use (for example, `claude-sonnet-4-5-20250929`)
|
||||
- `--mcp-config`: Path to MCP configuration
|
||||
- `--allowed-tools`: Comma-separated list of allowed tools
|
||||
- `--debug`: Enable debug output
|
||||
|
||||
### [](#alternative-integration-methods) 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) 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](/docs/en/memory) for more details.
|
||||
2. **Custom prompts**: Use the `prompt` parameter in the workflow file to provide workflow-specific instructions. This allows you to customize Claude’s behavior for different workflows or tasks.
|
||||
|
||||
Claude will follow these guidelines when creating PRs and responding to requests.
|
||||
@@ -0,0 +1,434 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/gitlab-ci-cd
|
||||
title: Claude Code GitLab CI/CD
|
||||
---
|
||||
|
||||
Claude Code for GitLab CI/CD is currently in beta. Features and functionality may evolve as we refine the experience.This integration is maintained by GitLab. For support, see the following [GitLab issue](https://gitlab.com/gitlab-org/gitlab/-/issues/573776).
|
||||
|
||||
This integration is built on top of the [Claude Code CLI and SDK](https://docs.claude.com/en/docs/agent-sdk), enabling programmatic use of Claude in your CI/CD jobs and custom automation workflows.
|
||||
|
||||
## [](#why-use-claude-code-with-gitlab) 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) 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) 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) Setup
|
||||
|
||||
### [](#quick-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`**
|
||||
|
||||
```bash
|
||||
stages:
|
||||
- ai
|
||||
|
||||
claude:
|
||||
stage: ai
|
||||
image: node:24-alpine3.21
|
||||
# Adjust rules to fit how you want to trigger the job:
|
||||
# - manual runs
|
||||
# - merge request events
|
||||
# - web/API triggers when a comment contains '@claude'
|
||||
rules:
|
||||
- if: '$CI_PIPELINE_SOURCE == "web"'
|
||||
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
|
||||
variables:
|
||||
GIT_STRATEGY: fetch
|
||||
before_script:
|
||||
- apk update
|
||||
- apk add --no-cache git curl bash
|
||||
- curl -fsSL https://claude.ai/install.sh | bash
|
||||
script:
|
||||
# Optional: start a GitLab MCP server if your setup provides one
|
||||
- /bin/gitlab-mcp-server || true
|
||||
# Use AI_FLOW_* variables when invoking via web/API triggers with context payloads
|
||||
- echo "$AI_FLOW_INPUT for $AI_FLOW_CONTEXT on $AI_FLOW_EVENT"
|
||||
- >
|
||||
claude
|
||||
-p "${AI_FLOW_INPUT:-'Review this MR and implement the requested changes'}"
|
||||
--permission-mode acceptEdits
|
||||
--allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab"
|
||||
--debug
|
||||
```
|
||||
|
||||
After adding the job and your `ANTHROPIC_API_KEY` variable, test by running the job manually from **CI/CD** → **Pipelines**, or trigger it from an MR to let Claude propose updates in a branch and open an MR if needed.
|
||||
|
||||
To run on AWS Bedrock or Google Vertex AI instead of the Claude API, see the [Using with AWS Bedrock & Google Vertex AI](#using-with-aws-bedrock--google-vertex-ai) section below for authentication and environment setup.
|
||||
|
||||
### [](#manual-setup-recommended-for-production) 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) Example use cases
|
||||
|
||||
### [](#turn-issues-into-mrs) Turn issues into MRs
|
||||
|
||||
In an issue comment:
|
||||
|
||||
```bash
|
||||
@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) Get implementation help
|
||||
|
||||
In an MR discussion:
|
||||
|
||||
```bash
|
||||
@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) Fix bugs quickly
|
||||
|
||||
In an issue or MR comment:
|
||||
|
||||
```bash
|
||||
@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) 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.
|
||||
|
||||
- AWS Bedrock
|
||||
- Google Vertex AI
|
||||
|
||||
### [](#prerequisites) 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) 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:
|
||||
|
||||
```bash
|
||||
# For AWS Bedrock:
|
||||
- AWS_ROLE_TO_ASSUME
|
||||
- AWS_REGION
|
||||
```
|
||||
|
||||
Use the AWS Bedrock job example above to exchange the GitLab job token for temporary AWS credentials at runtime.
|
||||
|
||||
### [](#prerequisites-2) 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-2) 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:
|
||||
|
||||
```bash
|
||||
# For Google Vertex AI:
|
||||
- GCP_WORKLOAD_IDENTITY_PROVIDER
|
||||
- GCP_SERVICE_ACCOUNT
|
||||
- CLOUD_ML_REGION (for example, us-east5)
|
||||
```
|
||||
|
||||
Use the Google Vertex AI job example above to authenticate without storing keys.
|
||||
|
||||
## [](#configuration-examples) Configuration examples
|
||||
|
||||
Below are ready-to-use snippets you can adapt to your pipeline.
|
||||
|
||||
### [](#basic-gitlab-ci-yml-claude-api) Basic .gitlab-ci.yml (Claude API)
|
||||
|
||||
```bash
|
||||
stages:
|
||||
- ai
|
||||
|
||||
claude:
|
||||
stage: ai
|
||||
image: node:24-alpine3.21
|
||||
rules:
|
||||
- if: '$CI_PIPELINE_SOURCE == "web"'
|
||||
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
|
||||
variables:
|
||||
GIT_STRATEGY: fetch
|
||||
before_script:
|
||||
- apk update
|
||||
- apk add --no-cache git curl bash
|
||||
- curl -fsSL https://claude.ai/install.sh | bash
|
||||
script:
|
||||
- /bin/gitlab-mcp-server || true
|
||||
- >
|
||||
claude
|
||||
-p "${AI_FLOW_INPUT:-'Summarize recent changes and suggest improvements'}"
|
||||
--permission-mode acceptEdits
|
||||
--allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab"
|
||||
--debug
|
||||
# Claude Code will use ANTHROPIC_API_KEY from CI/CD variables
|
||||
```
|
||||
|
||||
### [](#aws-bedrock-job-example-oidc) 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`)
|
||||
|
||||
```bash
|
||||
claude-bedrock:
|
||||
stage: ai
|
||||
image: node:24-alpine3.21
|
||||
rules:
|
||||
- if: '$CI_PIPELINE_SOURCE == "web"'
|
||||
before_script:
|
||||
- apk add --no-cache bash curl jq git python3 py3-pip
|
||||
- pip install --no-cache-dir awscli
|
||||
- curl -fsSL https://claude.ai/install.sh | bash
|
||||
# Exchange GitLab OIDC token for AWS credentials
|
||||
- export AWS_WEB_IDENTITY_TOKEN_FILE="${CI_JOB_JWT_FILE:-/tmp/oidc_token}"
|
||||
- if [ -n "${CI_JOB_JWT_V2}" ]; then printf "%s" "$CI_JOB_JWT_V2" > "$AWS_WEB_IDENTITY_TOKEN_FILE"; fi
|
||||
- >
|
||||
aws sts assume-role-with-web-identity
|
||||
--role-arn "$AWS_ROLE_TO_ASSUME"
|
||||
--role-session-name "gitlab-claude-$(date +%s)"
|
||||
--web-identity-token "file://$AWS_WEB_IDENTITY_TOKEN_FILE"
|
||||
--duration-seconds 3600 > /tmp/aws_creds.json
|
||||
- export AWS_ACCESS_KEY_ID="$(jq -r .Credentials.AccessKeyId /tmp/aws_creds.json)"
|
||||
- export AWS_SECRET_ACCESS_KEY="$(jq -r .Credentials.SecretAccessKey /tmp/aws_creds.json)"
|
||||
- export AWS_SESSION_TOKEN="$(jq -r .Credentials.SessionToken /tmp/aws_creds.json)"
|
||||
script:
|
||||
- /bin/gitlab-mcp-server || true
|
||||
- >
|
||||
claude
|
||||
-p "${AI_FLOW_INPUT:-'Implement the requested changes and open an MR'}"
|
||||
--permission-mode acceptEdits
|
||||
--allowedTools "Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab"
|
||||
--debug
|
||||
variables:
|
||||
AWS_REGION: "us-west-2"
|
||||
```
|
||||
|
||||
Model IDs for Bedrock include region-specific prefixes and version suffixes (for example, `us.anthropic.claude-sonnet-4-5-20250929-v1:0`). Pass the desired model via your job configuration or prompt if your workflow supports it.
|
||||
|
||||
### [](#google-vertex-ai-job-example-workload-identity-federation) 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`)
|
||||
|
||||
```bash
|
||||
claude-vertex:
|
||||
stage: ai
|
||||
image: gcr.io/google.com/cloudsdktool/google-cloud-cli:slim
|
||||
rules:
|
||||
- if: '$CI_PIPELINE_SOURCE == "web"'
|
||||
before_script:
|
||||
- apt-get update && apt-get install -y git && apt-get clean
|
||||
- curl -fsSL https://claude.ai/install.sh | bash
|
||||
# Authenticate to Google Cloud via WIF (no downloaded keys)
|
||||
- >
|
||||
gcloud auth login --cred-file=<(cat <<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"
|
||||
```
|
||||
|
||||
With Workload Identity Federation, you do not need to store service account keys. Use repository-specific trust conditions and least-privilege service accounts.
|
||||
|
||||
## [](#best-practices) Best practices
|
||||
|
||||
### [](#claude-md-configuration) 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) 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) 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) CI costs
|
||||
|
||||
When using Claude Code with GitLab CI/CD, be aware of associated costs:
|
||||
|
||||
- **GitLab Runner time**:
|
||||
- Claude runs on your GitLab runners and consumes compute minutes
|
||||
- See your GitLab plan’s runner billing for details
|
||||
- **API costs**:
|
||||
- Each Claude interaction consumes tokens based on prompt and response size
|
||||
- Token usage varies by task complexity and codebase size
|
||||
- See [Anthropic pricing](https://docs.claude.com/en/docs/about-claude/pricing) for details
|
||||
- **Cost optimization tips**:
|
||||
- Use specific `@claude` commands to reduce unnecessary turns
|
||||
- Set appropriate `max_turns` and job timeout values
|
||||
- Limit concurrency to control parallel runs
|
||||
|
||||
## [](#security-and-governance) 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) Troubleshooting
|
||||
|
||||
### [](#claude-not-responding-to-@claude-commands) 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) 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) 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) Advanced configuration
|
||||
|
||||
### [](#common-parameters-and-variables) Common parameters and variables
|
||||
|
||||
Claude Code supports these commonly used inputs:
|
||||
|
||||
- `prompt` / `prompt_file`: Provide instructions inline (`-p`) or via a file
|
||||
- `max_turns`: Limit the number of back-and-forth iterations
|
||||
- `timeout_minutes`: Limit total execution time
|
||||
- `ANTHROPIC_API_KEY`: Required for the Claude API (not used for Bedrock/Vertex)
|
||||
- Provider-specific environment: `AWS_REGION`, project/region vars for Vertex
|
||||
|
||||
Exact flags and parameters may vary by version of `@anthropic-ai/claude-code`. Run `claude --help` in your job to see supported options.
|
||||
|
||||
### [](#customizing-claude’s-behavior) 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).
|
||||
@@ -0,0 +1,141 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/google-vertex-ai
|
||||
title: Claude Code on Google Vertex AI
|
||||
---
|
||||
|
||||
## [](#prerequisites) Prerequisites
|
||||
|
||||
Before configuring Claude Code with Vertex AI, ensure you have:
|
||||
|
||||
- A Google Cloud Platform (GCP) account with billing enabled
|
||||
- A GCP project with Vertex AI API enabled
|
||||
- Access to desired Claude models (for example, Claude Sonnet 4.5)
|
||||
- Google Cloud SDK (`gcloud`) installed and configured
|
||||
- Quota allocated in desired GCP region
|
||||
|
||||
## [](#region-configuration) Region Configuration
|
||||
|
||||
Claude Code can be used with both Vertex AI [global](https://cloud.google.com/blog/products/ai-machine-learning/global-endpoint-for-claude-models-generally-available-on-vertex-ai) and regional endpoints.
|
||||
|
||||
Vertex AI may not support the Claude Code default models on all regions. You may need to switch to a [supported region or model](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#genai-partner-models).
|
||||
|
||||
Vertex AI may not support the Claude Code default models on global endpoints. You may need to switch to a regional endpoint or [supported model](https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-partner-models#supported_models).
|
||||
|
||||
## [](#setup) Setup
|
||||
|
||||
### [](#1-enable-vertex-ai-api) 1. Enable Vertex AI API
|
||||
|
||||
Enable the Vertex AI API in your GCP project:
|
||||
|
||||
```bash
|
||||
# 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) 2. Request model access
|
||||
|
||||
Request access to Claude models in Vertex AI:
|
||||
|
||||
1. Navigate to the [Vertex AI Model Garden](https://console.cloud.google.com/vertex-ai/model-garden)
|
||||
2. Search for “Claude” models
|
||||
3. Request access to desired Claude models (for example, Claude Sonnet 4.5)
|
||||
4. Wait for approval (may take 24-48 hours)
|
||||
|
||||
### [](#3-configure-gcp-credentials) 3. Configure GCP credentials
|
||||
|
||||
Claude Code uses standard Google Cloud authentication.
|
||||
For more information, see [Google Cloud authentication documentation](https://cloud.google.com/docs/authentication).
|
||||
|
||||
When authenticating, Claude Code will automatically use the project ID from the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable. To override this, set one of these environment variables: `GCLOUD_PROJECT`, `GOOGLE_CLOUD_PROJECT`, or `GOOGLE_APPLICATION_CREDENTIALS`.
|
||||
|
||||
### [](#4-configure-claude-code) 4. Configure Claude Code
|
||||
|
||||
Set the following environment variables:
|
||||
|
||||
```bash
|
||||
# Enable Vertex AI integration
|
||||
export CLAUDE_CODE_USE_VERTEX=1
|
||||
export CLOUD_ML_REGION=global
|
||||
export ANTHROPIC_VERTEX_PROJECT_ID=YOUR-PROJECT-ID
|
||||
|
||||
# Optional: Disable prompt caching if needed
|
||||
export DISABLE_PROMPT_CACHING=1
|
||||
|
||||
# When CLOUD_ML_REGION=global, override region for unsupported models
|
||||
export VERTEX_REGION_CLAUDE_3_5_HAIKU=us-east5
|
||||
|
||||
# Optional: Override regions for other specific models
|
||||
export VERTEX_REGION_CLAUDE_3_5_SONNET=us-east5
|
||||
export VERTEX_REGION_CLAUDE_3_7_SONNET=us-east5
|
||||
export VERTEX_REGION_CLAUDE_4_0_OPUS=europe-west1
|
||||
export VERTEX_REGION_CLAUDE_4_0_SONNET=us-east5
|
||||
export VERTEX_REGION_CLAUDE_4_1_OPUS=europe-west1
|
||||
```
|
||||
|
||||
[Prompt caching](https://docs.claude.com/en/docs/build-with-claude/prompt-caching) is automatically supported when you specify the `cache_control` ephemeral flag. To disable it, set `DISABLE_PROMPT_CACHING=1`. For heightened rate limits, contact Google Cloud support.
|
||||
|
||||
When using Vertex AI, the `/login` and `/logout` commands are disabled since authentication is handled through Google Cloud credentials.
|
||||
|
||||
### [](#5-model-configuration) 5. Model configuration
|
||||
|
||||
Claude Code uses these default models for Vertex AI:
|
||||
|
||||
| Model type | Default value |
|
||||
| --- | --- |
|
||||
| Primary model | `claude-sonnet-4-5@20250929` |
|
||||
| Small/fast model | `claude-haiku-4-5@20251001` |
|
||||
|
||||
For Vertex AI users, Claude Code will not automatically upgrade from Haiku 3.5 to Haiku 4.5. To manually switch to a newer Haiku model, set the `ANTHROPIC_DEFAULT_HAIKU_MODEL` environment variable to the full model name (for example, `claude-haiku-4-5@20251001`).
|
||||
|
||||
To customize models:
|
||||
|
||||
```bash
|
||||
export ANTHROPIC_MODEL='claude-opus-4-1@20250805'
|
||||
export ANTHROPIC_SMALL_FAST_MODEL='claude-haiku-4-5@20251001'
|
||||
```
|
||||
|
||||
## [](#iam-configuration) IAM configuration
|
||||
|
||||
Assign the required IAM permissions:
|
||||
The `roles/aiplatform.user` role includes the required permissions:
|
||||
|
||||
- `aiplatform.endpoints.predict` - Required for model invocation and token counting
|
||||
|
||||
For more restrictive permissions, create a custom role with only the permissions above.
|
||||
For details, see [Vertex IAM documentation](https://cloud.google.com/vertex-ai/docs/general/access-control).
|
||||
|
||||
We recommend creating a dedicated GCP project for Claude Code to simplify cost tracking and access control.
|
||||
|
||||
## [](#1m-token-context-window) 1M token context window
|
||||
|
||||
Claude Sonnet 4 and Sonnet 4.5 support the [1M token context window](https://docs.claude.com/en/docs/build-with-claude/context-windows#1m-token-context-window) on Vertex AI.
|
||||
|
||||
The 1M token context window is currently in beta. To use the extended context window, include the `context-1m-2025-08-07` beta header in your Vertex AI requests.
|
||||
|
||||
## [](#troubleshooting) 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) 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)
|
||||
@@ -0,0 +1,136 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/headless
|
||||
title: Run Claude Code programmatically
|
||||
---
|
||||
|
||||
The [Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview) gives you the same tools, agent loop, and context management that power Claude Code. It’s available as a CLI for scripts and CI/CD, or as [Python](https://platform.claude.com/docs/en/agent-sdk/python) and [TypeScript](https://platform.claude.com/docs/en/agent-sdk/typescript) packages for full programmatic control.
|
||||
|
||||
The CLI was previously called “headless mode.” The `-p` flag and all CLI options work the same way.
|
||||
|
||||
To run Claude Code programmatically from the CLI, pass `-p` with your prompt and any [CLI options](/docs/en/cli-reference):
|
||||
|
||||
```bash
|
||||
claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
|
||||
```
|
||||
|
||||
This page covers using the Agent SDK via the CLI (`claude -p`). For the Python and TypeScript SDK packages with structured outputs, tool approval callbacks, and native message objects, see the [full Agent SDK documentation](https://platform.claude.com/docs/en/agent-sdk/overview).
|
||||
|
||||
## [](#basic-usage) Basic usage
|
||||
|
||||
Add the `-p` (or `--print`) flag to any `claude` command to run it non-interactively. All [CLI options](/docs/en/cli-reference) work with `-p`, including:
|
||||
|
||||
- `--continue` for [continuing conversations](#continue-conversations)
|
||||
- `--allowedTools` for [auto-approving tools](#auto-approve-tools)
|
||||
- `--output-format` for [structured output](#get-structured-output)
|
||||
|
||||
This example asks Claude a question about your codebase and prints the response:
|
||||
|
||||
```bash
|
||||
claude -p "What does the auth module do?"
|
||||
```
|
||||
|
||||
## [](#examples) Examples
|
||||
|
||||
These examples highlight common CLI patterns.
|
||||
|
||||
### [](#get-structured-output) Get structured output
|
||||
|
||||
Use `--output-format` to control how responses are returned:
|
||||
|
||||
- `text` (default): plain text output
|
||||
- `json`: structured JSON with result, session ID, and metadata
|
||||
- `stream-json`: newline-delimited JSON for real-time streaming
|
||||
|
||||
This example returns a project summary as JSON with session metadata, with the text result in the `result` field:
|
||||
|
||||
```bash
|
||||
claude -p "Summarize this project" --output-format json
|
||||
```
|
||||
|
||||
To get output conforming to a specific schema, use `--output-format json` with `--json-schema` and a [JSON Schema](https://json-schema.org/) definition. The response includes metadata about the request (session ID, usage, etc.) with the structured output in the `structured_output` field.
|
||||
This example extracts function names and returns them as an array of strings:
|
||||
|
||||
```bash
|
||||
claude -p "Extract the main function names from auth.py" \
|
||||
--output-format json \
|
||||
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'
|
||||
```
|
||||
|
||||
Use a tool like [jq](https://jqlang.github.io/jq/) to parse the response and extract specific fields:
|
||||
|
||||
```bash
|
||||
# Extract the text result
|
||||
claude -p "Summarize this project" --output-format json | jq -r '.result'
|
||||
|
||||
# Extract structured output
|
||||
claude -p "Extract function names from auth.py" \
|
||||
--output-format json \
|
||||
--json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
|
||||
| jq '.structured_output'
|
||||
```
|
||||
|
||||
### [](#auto-approve-tools) Auto-approve tools
|
||||
|
||||
Use `--allowedTools` to let Claude use certain tools without prompting. This example runs a test suite and fixes failures, allowing Claude to execute Bash commands and read/edit files without asking for permission:
|
||||
|
||||
```bash
|
||||
claude -p "Run the test suite and fix any failures" \
|
||||
--allowedTools "Bash,Read,Edit"
|
||||
```
|
||||
|
||||
### [](#create-a-commit) Create a commit
|
||||
|
||||
This example reviews staged changes and creates a commit with an appropriate message:
|
||||
|
||||
```bash
|
||||
claude -p "Look at my staged changes and create an appropriate commit" \
|
||||
--allowedTools "Bash(git diff:*),Bash(git log:*),Bash(git status:*),Bash(git commit:*)"
|
||||
```
|
||||
|
||||
The `--allowedTools` flag uses [permission rule syntax](/docs/en/settings#permission-rule-syntax). The `:*` suffix enables prefix matching, so `Bash(git diff:*)` allows any command starting with `git diff`.
|
||||
|
||||
[Slash commands](/docs/en/slash-commands) like `/commit` are only available in interactive mode. In `-p` mode, describe the task you want to accomplish instead.
|
||||
|
||||
### [](#customize-the-system-prompt) Customize the system prompt
|
||||
|
||||
Use `--append-system-prompt` to add instructions while keeping Claude Code’s default behavior. This example pipes a PR diff to Claude and instructs it to review for security vulnerabilities:
|
||||
|
||||
```bash
|
||||
gh pr diff "$1" | claude -p \
|
||||
--append-system-prompt "You are a security engineer. Review for vulnerabilities." \
|
||||
--output-format json
|
||||
```
|
||||
|
||||
See [system prompt flags](/docs/en/cli-reference#system-prompt-flags) for more options including `--system-prompt` to fully replace the default prompt.
|
||||
|
||||
### [](#continue-conversations) Continue conversations
|
||||
|
||||
Use `--continue` to continue the most recent conversation, or `--resume` with a session ID to continue a specific conversation. This example runs a review, then sends follow-up prompts:
|
||||
|
||||
```bash
|
||||
# First request
|
||||
claude -p "Review this codebase for performance issues"
|
||||
|
||||
# Continue the most recent conversation
|
||||
claude -p "Now focus on the database queries" --continue
|
||||
claude -p "Generate a summary of all issues found" --continue
|
||||
```
|
||||
|
||||
If you’re running multiple conversations, capture the session ID to resume a specific one:
|
||||
|
||||
```bash
|
||||
session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
|
||||
claude -p "Continue that review" --resume "$session_id"
|
||||
```
|
||||
|
||||
## [](#next-steps) Next steps
|
||||
|
||||
[## Agent SDK quickstart
|
||||
|
||||
Build your first agent with Python or TypeScript](https://platform.claude.com/docs/en/agent-sdk/quickstart)[## CLI reference
|
||||
|
||||
Explore all CLI flags and options](/docs/en/cli-reference)[## GitHub Actions
|
||||
|
||||
Use the Agent SDK in GitHub workflows](/docs/en/github-actions)[## GitLab CI/CD
|
||||
|
||||
Use the Agent SDK in GitLab pipelines](/docs/en/gitlab-ci-cd)
|
||||
@@ -0,0 +1,323 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/hooks-guide
|
||||
title: Get started with Claude Code hooks
|
||||
---
|
||||
|
||||
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.
|
||||
|
||||
For reference documentation on hooks, see [Hooks reference](/docs/en/hooks).
|
||||
|
||||
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.
|
||||
|
||||
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](/docs/en/hooks#security-considerations) in the hooks reference documentation.
|
||||
|
||||
## [](#hook-events-overview) 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)
|
||||
- **PermissionRequest**: Runs when a permission dialog is shown (can allow or deny)
|
||||
- **PostToolUse**: Runs after tool calls complete
|
||||
- **UserPromptSubmit**: Runs when the user submits a prompt, before Claude processes it
|
||||
- **Notification**: Runs when Claude Code sends notifications
|
||||
- **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) Quickstart
|
||||
|
||||
In this quickstart, you’ll add a hook that logs the shell commands that Claude
|
||||
Code runs.
|
||||
|
||||
### [](#prerequisites) Prerequisites
|
||||
|
||||
Install `jq` for JSON processing in the command line.
|
||||
|
||||
### [](#step-1:-open-hooks-configuration) Step 1: Open hooks configuration
|
||||
|
||||
Run the `/hooks` [slash command](/docs/en/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) Step 2: Add a matcher
|
||||
|
||||
Select `+ Add new matcher…` to run your hook only on Bash tool calls.
|
||||
Type `Bash` for the matcher.
|
||||
|
||||
You can use `*` to match all tools.
|
||||
|
||||
### [](#step-3:-add-the-hook) Step 3: Add the hook
|
||||
|
||||
Select `+ Add new hook…` and enter this command:
|
||||
|
||||
```bash
|
||||
jq -r '"\(.tool_input.command) - \(.tool_input.description // "No description")"' >> ~/.claude/bash-command-log.txt
|
||||
```
|
||||
|
||||
### [](#step-4:-save-your-configuration) 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) Step 5: Verify your hook
|
||||
|
||||
Run `/hooks` again or check `~/.claude/settings.json` to see your configuration:
|
||||
|
||||
```bash
|
||||
{
|
||||
"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) Step 6: Test your hook
|
||||
|
||||
Ask Claude to run a simple command like `ls` and check your log file:
|
||||
|
||||
```bash
|
||||
cat ~/.claude/bash-command-log.txt
|
||||
```
|
||||
|
||||
You should see entries like:
|
||||
|
||||
```bash
|
||||
ls - Lists files and directories
|
||||
```
|
||||
|
||||
## [](#more-examples) More Examples
|
||||
|
||||
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.
|
||||
|
||||
### [](#code-formatting-hook) Code Formatting Hook
|
||||
|
||||
Automatically format TypeScript files after editing:
|
||||
|
||||
```bash
|
||||
{
|
||||
"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) Markdown Formatting Hook
|
||||
|
||||
Automatically fix missing language tags and formatting issues in markdown files:
|
||||
|
||||
```bash
|
||||
{
|
||||
"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:
|
||||
|
||||
```bash
|
||||
#!/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
|
||||
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) Custom Notification Hook
|
||||
|
||||
Get desktop notifications when Claude needs input:
|
||||
|
||||
```bash
|
||||
{
|
||||
"hooks": {
|
||||
"Notification": [
|
||||
{
|
||||
"matcher": "",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "notify-send 'Claude Code' 'Awaiting your input'"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### [](#file-protection-hook) File Protection Hook
|
||||
|
||||
Block edits to sensitive files:
|
||||
|
||||
```bash
|
||||
{
|
||||
"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) Learn more
|
||||
|
||||
- For reference documentation on hooks, see [Hooks reference](/docs/en/hooks).
|
||||
- For comprehensive security best practices and safety guidelines, see [Security Considerations](/docs/en/hooks#security-considerations) in the hooks reference documentation.
|
||||
- For troubleshooting steps and debugging techniques, see [Debugging](/docs/en/hooks#debugging) in the hooks reference
|
||||
documentation.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,214 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/iam
|
||||
title: Identity and Access Management
|
||||
---
|
||||
|
||||
## [](#authentication-methods) Authentication methods
|
||||
|
||||
Setting up Claude Code requires access to Anthropic models. For teams, you can set up Claude Code access in one of these ways:
|
||||
|
||||
- [Claude for Teams or Enterprise](/docs/en/setup#for-teams-and-organizations) (recommended)
|
||||
- [Claude Console with team billing](/docs/en/setup#for-teams-and-organizations)
|
||||
- [Amazon Bedrock](/docs/en/amazon-bedrock)
|
||||
- [Google Vertex AI](/docs/en/google-vertex-ai)
|
||||
- [Microsoft Foundry](/docs/en/microsoft-foundry)
|
||||
|
||||
### [](#claude-for-teams-or-enterprise-recommended) Claude for Teams or Enterprise (recommended)
|
||||
|
||||
[Claude for Teams](https://claude.com/pricing#team-&-enterprise) and [Claude for Enterprise](https://anthropic.com/contact-sales) provide the best experience for organizations using Claude Code. Team members get access to both Claude Code and Claude on the web with centralized billing and team management.
|
||||
|
||||
- **Claude for Teams**: Self-service plan with collaboration features, admin tools, and billing management. Best for smaller teams.
|
||||
- **Claude for Enterprise**: Adds SSO, domain capture, role-based permissions, compliance API, and managed policy settings for organization-wide Claude Code configurations. Best for larger organizations with security and compliance requirements.
|
||||
|
||||
**To set up Claude Code access:**
|
||||
|
||||
1. Subscribe to [Claude for Teams](https://claude.com/pricing#team-&-enterprise) or contact sales for [Claude for Enterprise](https://anthropic.com/contact-sales)
|
||||
2. Invite team members from the admin dashboard
|
||||
3. Team members install Claude Code and log in with their Claude.ai accounts
|
||||
|
||||
### [](#claude-console-authentication) Claude Console authentication
|
||||
|
||||
For organizations that prefer API-based billing, you can set up access through the Claude Console.
|
||||
**To set up Claude Code access for your team via Claude Console:**
|
||||
|
||||
1. Use your existing Claude Console account or create a new Claude Console account
|
||||
2. You can add users through either method below:
|
||||
- Bulk invite users from within the Console (Console -> Settings -> Members -> Invite)
|
||||
- [Set up SSO](https://support.claude.com/en/articles/13132885-setting-up-single-sign-on-sso)
|
||||
3. When inviting users, they need one of the following roles:
|
||||
- “Claude Code” role means users can only create Claude Code API keys
|
||||
- “Developer” role means users can create any kind of API key
|
||||
4. Each invited user needs to complete these steps:
|
||||
- Accept the Console invite
|
||||
- [Check system requirements](/docs/en/setup#system-requirements)
|
||||
- [Install Claude Code](/docs/en/setup#installation)
|
||||
- Login with Console account credentials
|
||||
|
||||
### [](#cloud-provider-authentication) Cloud provider authentication
|
||||
|
||||
**To set up Claude Code access for your team via Bedrock, Vertex, or Azure:**
|
||||
|
||||
1. Follow the [Bedrock docs](/docs/en/amazon-bedrock), [Vertex docs](/docs/en/google-vertex-ai), or [Microsoft Foundry docs](/docs/en/microsoft-foundry)
|
||||
2. Distribute the environment variables and instructions for generating cloud credentials to your users. Read more about how to [manage configuration here](/docs/en/settings).
|
||||
3. Users can [install Claude Code](/docs/en/setup#installation)
|
||||
|
||||
## [](#access-control-and-permissions) 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) Permission system
|
||||
|
||||
Claude Code uses a tiered permission system to balance power and safety:
|
||||
|
||||
| Tool Type | Example | Approval Required | ”Yes, don’t ask again” Behavior |
|
||||
| --- | --- | --- | --- |
|
||||
| Read-only | File reads, Grep | No | N/A |
|
||||
| Bash Commands | Shell execution | Yes | Permanently per project directory and command |
|
||||
| File Modification | Edit/write files | Yes | Until session end |
|
||||
|
||||
### [](#configuring-permissions) 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 let Claude Code use the specified tool without manual approval.
|
||||
- **Ask** rules prompt for confirmation whenever Claude Code tries to use the specified tool.
|
||||
- **Deny** rules prevent Claude Code from using the specified tool.
|
||||
|
||||
Rules are evaluated in order: **deny → ask → allow**. The first matching rule wins, so deny rules always take precedence.
|
||||
|
||||
- **Additional directories** extend Claude’s file access to directories beyond the initial working directory.
|
||||
- **Default mode** controls Claude’s permission behavior when encountering new requests.
|
||||
|
||||
Permission rules use the format: `Tool` or `Tool(optional-specifier)`
|
||||
A rule that is just the tool name matches any use of that tool. For example, adding `Bash` to the allow list allows Claude Code to use the Bash tool without requiring user approval. Note that `Bash(*)` does **not** match all Bash commands. Use `Bash` without parentheses to match all uses.
|
||||
|
||||
For a quick reference on permission rule syntax including wildcards, see [Permission rule syntax](/docs/en/settings#permission-rule-syntax) in the settings documentation.
|
||||
|
||||
#### [](#permission-modes) Permission modes
|
||||
|
||||
Claude Code supports several permission modes that can be set as the `defaultMode` in [settings files](/docs/en/settings#settings-files):
|
||||
|
||||
| Mode | Description |
|
||||
| --- | --- |
|
||||
| `default` | Standard behavior - prompts for permission on first use of each tool |
|
||||
| `acceptEdits` | Automatically accepts file edit permissions for the session |
|
||||
| `plan` | Plan Mode - Claude can analyze but not modify files or execute commands |
|
||||
| `dontAsk` | Auto-denies tools unless pre-approved via `/permissions` or [`permissions.allow`](/docs/en/settings#permission-settings) rules |
|
||||
| `bypassPermissions` | Skips all permission prompts (requires safe environment - see warning below) |
|
||||
|
||||
#### [](#working-directories) 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](/docs/en/settings#settings-files)
|
||||
|
||||
Files in additional directories follow the same permission rules as the original working directory - they become readable without prompts, and file editing permissions follow the current permission mode.
|
||||
|
||||
#### [](#tool-specific-permission-rules) Tool-specific permission rules
|
||||
|
||||
Some tools support more fine-grained permission controls:
|
||||
**Bash**
|
||||
Bash permission rules support both prefix matching with `:*` and wildcard matching with `*`:
|
||||
|
||||
- `Bash(npm run build)` Matches the exact Bash command `npm run build`
|
||||
- `Bash(npm run test:*)` Matches Bash commands starting with `npm run test`
|
||||
- `Bash(npm *)` Matches any command starting with `npm` (e.g., `npm install`, `npm run build`)
|
||||
- `Bash(* install)` Matches any command ending with `install` (e.g., `npm install`, `yarn install`)
|
||||
- `Bash(git * main)` Matches commands like `git checkout main`, `git merge main`
|
||||
|
||||
Claude Code is aware of shell operators (like `&&`) so a prefix match rule like `Bash(safe-cmd:*)` won’t give it permission to run the command `safe-cmd && other-cmd`
|
||||
|
||||
Important limitations of Bash permission patterns:
|
||||
|
||||
1. The `:*` wildcard only works at the end of a pattern for prefix matching
|
||||
2. The `*` wildcard can appear at any position and matches any sequence of characters
|
||||
3. Patterns like `Bash(curl http://github.com/:*)` can be bypassed in many ways:
|
||||
- Options before URL: `curl -X GET http://github.com/...` won’t match
|
||||
- Different protocol: `curl https://github.com/...` won’t match
|
||||
- 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:
|
||||
|
||||
- **Restrict Bash network tools**: Use deny rules to block `curl`, `wget`, and similar commands, then use the WebFetch tool with `WebFetch(domain:github.com)` permission for allowed domains
|
||||
- **Use PreToolUse hooks**: Implement a hook that validates URLs in Bash commands and blocks disallowed domains
|
||||
- Instructing Claude Code about your allowed curl patterns via CLAUDE.md
|
||||
|
||||
Note that using WebFetch alone does not prevent network access. If Bash is allowed, Claude can still use `curl`, `wget`, or other tools to reach any URL.
|
||||
|
||||
**Read & 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 and Glob.
|
||||
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` |
|
||||
|
||||
A pattern like `/Users/alice/file` is NOT an absolute path - it’s relative to your settings file! Use `//Users/alice/file` for absolute paths.
|
||||
|
||||
- `Edit(/docs/**)` - Edits in `<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__*` Wildcard syntax that also matches all tools from the `puppeteer` server
|
||||
- `mcp__puppeteer__puppeteer_navigate` Matches the `puppeteer_navigate` tool provided by the `puppeteer` server
|
||||
|
||||
**Task (Subagents)**
|
||||
Use `Task(AgentName)` rules to control which [subagents](/docs/en/sub-agents) Claude can use:
|
||||
|
||||
- `Task(Explore)` Matches the Explore subagent
|
||||
- `Task(Plan)` Matches the Plan subagent
|
||||
- `Task(Verify)` Matches the Verify subagent
|
||||
|
||||
Add these rules to the `deny` array in your [settings](/docs/en/settings#permission-settings) or use the `--disallowedTools` CLI flag to disable specific agents. For example, to disable the Explore agent:
|
||||
|
||||
```bash
|
||||
{
|
||||
"permissions": {
|
||||
"deny": ["Task(Explore)"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### [](#additional-permission-control-with-hooks) Additional permission control with hooks
|
||||
|
||||
[Claude Code hooks](/docs/en/hooks-guide) provide a way to register custom shell commands to perform permission evaluation at runtime. When Claude Code makes a tool call, PreToolUse hooks run before the permission system runs, and the hook output can determine whether to approve or deny the tool call in place of the permission system.
|
||||
|
||||
### [](#managed-settings) Managed settings
|
||||
|
||||
For organizations that need centralized control over Claude Code configuration, administrators can deploy `managed-settings.json` files to [system directories](/docs/en/settings#settings-files). These policy files follow the same format as regular settings files and cannot be overridden by user or project settings.
|
||||
|
||||
### [](#settings-precedence) Settings precedence
|
||||
|
||||
When multiple settings sources exist, they are applied in the following order (highest to lowest precedence):
|
||||
|
||||
1. Managed settings (`managed-settings.json`)
|
||||
2. Command line arguments
|
||||
3. Local project settings (`.claude/settings.local.json`)
|
||||
4. Shared project settings (`.claude/settings.json`)
|
||||
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) Credential management
|
||||
|
||||
Claude Code securely manages your authentication credentials:
|
||||
|
||||
- **Storage location**: On macOS, API keys, OAuth tokens, and other credentials are stored in the encrypted macOS Keychain.
|
||||
- **Supported authentication types**: Claude.ai credentials, Claude API credentials, Azure Auth, Bedrock Auth, and Vertex Auth.
|
||||
- **Custom credential scripts**: The [`apiKeyHelper`](/docs/en/settings#available-settings) setting can be configured to run a shell script that returns an API key.
|
||||
- **Refresh intervals**: By default, `apiKeyHelper` is called after 5 minutes or on HTTP 401 response. Set `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` environment variable for custom refresh intervals.
|
||||
@@ -0,0 +1,221 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/interactive-mode
|
||||
title: Interactive mode
|
||||
---
|
||||
|
||||
## [](#keyboard-shortcuts) Keyboard shortcuts
|
||||
|
||||
Keyboard shortcuts may vary by platform and terminal. Press `?` to see available shortcuts for your environment.**macOS users**: Option/Alt key shortcuts (`Alt+B`, `Alt+F`, `Alt+Y`, `Alt+M`, `Alt+P`) require configuring Option as Meta in your terminal:
|
||||
|
||||
- **iTerm2**: Settings → Profiles → Keys → Set Left/Right Option key to “Esc+”
|
||||
- **Terminal.app**: Settings → Profiles → Keyboard → Check “Use Option as Meta Key”
|
||||
- **VS Code**: Settings → Profiles → Keys → Set Left/Right Option key to “Esc+”
|
||||
|
||||
See [Terminal configuration](/docs/en/terminal-config) for details.
|
||||
|
||||
### [](#general-controls) General controls
|
||||
|
||||
| Shortcut | Description | Context |
|
||||
| --- | --- | --- |
|
||||
| `Ctrl+C` | Cancel current input or generation | Standard interrupt |
|
||||
| `Ctrl+D` | Exit Claude Code session | EOF signal |
|
||||
| `Ctrl+G` | Open in default text editor | Edit your prompt or custom response in your default text editor |
|
||||
| `Ctrl+L` | Clear terminal screen | Keeps conversation history |
|
||||
| `Ctrl+O` | Toggle verbose output | Shows detailed tool usage and execution |
|
||||
| `Ctrl+R` | Reverse search command history | Search through previous commands interactively |
|
||||
| `Ctrl+V` or `Cmd+V` (iTerm2) or `Alt+V` (Windows) | Paste image from clipboard | Pastes an image or path to an image file |
|
||||
| `Ctrl+B` | Background running tasks | Backgrounds bash commands and agents. Tmux users press twice |
|
||||
| `Left/Right arrows` | Cycle through dialog tabs | Navigate between tabs in permission dialogs and menus |
|
||||
| `Up/Down arrows` | Navigate command history | Recall previous inputs |
|
||||
| `Esc` + `Esc` | Rewind the code/conversation | Restore the code and/or conversation to a previous point |
|
||||
| `Shift+Tab` or `Alt+M` (some configurations) | Toggle permission modes | Switch between Auto-Accept Mode, Plan Mode, and normal mode |
|
||||
| `Option+P` (macOS) or `Alt+P` (Windows/Linux) | Switch model | Switch models without clearing your prompt |
|
||||
| `Option+T` (macOS) or `Alt+T` (Windows/Linux) | Toggle extended thinking | Enable or disable extended thinking mode. Run `/terminal-setup` first to enable this shortcut |
|
||||
|
||||
### [](#text-editing) Text editing
|
||||
|
||||
| Shortcut | Description | Context |
|
||||
| --- | --- | --- |
|
||||
| `Ctrl+K` | Delete to end of line | Stores deleted text for pasting |
|
||||
| `Ctrl+U` | Delete entire line | Stores deleted text for pasting |
|
||||
| `Ctrl+Y` | Paste deleted text | Paste text deleted with `Ctrl+K` or `Ctrl+U` |
|
||||
| `Alt+Y` (after `Ctrl+Y`) | Cycle paste history | After pasting, cycle through previously deleted text. Requires [Option as Meta](#keyboard-shortcuts) on macOS |
|
||||
| `Alt+B` | Move cursor back one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS |
|
||||
| `Alt+F` | Move cursor forward one word | Word navigation. Requires [Option as Meta](#keyboard-shortcuts) on macOS |
|
||||
|
||||
### [](#theme-and-display) Theme and display
|
||||
|
||||
| Shortcut | Description | Context |
|
||||
| --- | --- | --- |
|
||||
| `Ctrl+T` | Toggle syntax highlighting for code blocks | Only works inside the `/theme` picker menu. Controls whether code in Claude’s responses uses syntax coloring |
|
||||
|
||||
Syntax highlighting is only available in the native build of Claude Code.
|
||||
|
||||
### [](#multiline-input) Multiline input
|
||||
|
||||
| Method | Shortcut | Context |
|
||||
| --- | --- | --- |
|
||||
| Quick escape | `\` + `Enter` | Works in all terminals |
|
||||
| macOS default | `Option+Enter` | Default on macOS |
|
||||
| Shift+Enter | `Shift+Enter` | Works out of the box in iTerm2, WezTerm, Ghostty, Kitty |
|
||||
| Control sequence | `Ctrl+J` | Line feed character for multiline |
|
||||
| Paste mode | Paste directly | For code blocks, logs |
|
||||
|
||||
Shift+Enter works without configuration in iTerm2, WezTerm, Ghostty, and Kitty. For other terminals (VS Code, Alacritty, Zed, Warp), run `/terminal-setup` to install the binding.
|
||||
|
||||
### [](#quick-commands) Quick commands
|
||||
|
||||
| Shortcut | Description | Notes |
|
||||
| --- | --- | --- |
|
||||
| `/` at start | Slash command | See [slash commands](/docs/en/slash-commands) |
|
||||
| `!` at start | Bash mode | Run commands directly and add execution output to the session |
|
||||
| `@` | File path mention | Trigger file path autocomplete |
|
||||
|
||||
## [](#vim-editor-mode) Vim editor mode
|
||||
|
||||
Enable vim-style editing with `/vim` command or configure permanently via `/config`.
|
||||
|
||||
### [](#mode-switching) 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) Navigation (NORMAL mode)
|
||||
|
||||
| Command | Action |
|
||||
| --- | --- |
|
||||
| `h`/`j`/`k`/`l` | Move left/down/up/right |
|
||||
| `w` | Next word |
|
||||
| `e` | End of word |
|
||||
| `b` | Previous word |
|
||||
| `0` | Beginning of line |
|
||||
| `$` | End of line |
|
||||
| `^` | First non-blank character |
|
||||
| `gg` | Beginning of input |
|
||||
| `G` | End of input |
|
||||
| `f{char}` | Jump to next occurrence of character |
|
||||
| `F{char}` | Jump to previous occurrence of character |
|
||||
| `t{char}` | Jump to just before next occurrence of character |
|
||||
| `T{char}` | Jump to just after previous occurrence of character |
|
||||
| `;` | Repeat last f/F/t/T motion |
|
||||
| `,` | Repeat last f/F/t/T motion in reverse |
|
||||
|
||||
### [](#editing-normal-mode) Editing (NORMAL mode)
|
||||
|
||||
| Command | Action |
|
||||
| --- | --- |
|
||||
| `x` | Delete character |
|
||||
| `dd` | Delete line |
|
||||
| `D` | Delete to end of line |
|
||||
| `dw`/`de`/`db` | Delete word/to end/back |
|
||||
| `cc` | Change line |
|
||||
| `C` | Change to end of line |
|
||||
| `cw`/`ce`/`cb` | Change word/to end/back |
|
||||
| `yy`/`Y` | Yank (copy) line |
|
||||
| `yw`/`ye`/`yb` | Yank word/to end/back |
|
||||
| `p` | Paste after cursor |
|
||||
| `P` | Paste before cursor |
|
||||
| `>>` | Indent line |
|
||||
| `<<` | Dedent line |
|
||||
| `J` | Join lines |
|
||||
| `.` | Repeat last change |
|
||||
|
||||
### [](#text-objects-normal-mode) Text objects (NORMAL mode)
|
||||
|
||||
Text objects work with operators like `d`, `c`, and `y`:
|
||||
|
||||
| Command | Action |
|
||||
| --- | --- |
|
||||
| `iw`/`aw` | Inner/around word |
|
||||
| `iW`/`aW` | Inner/around WORD (whitespace-delimited) |
|
||||
| `i"`/`a"` | Inner/around double quotes |
|
||||
| `i'`/`a'` | Inner/around single quotes |
|
||||
| `i(`/`a(` | Inner/around parentheses |
|
||||
| `i[`/`a[` | Inner/around brackets |
|
||||
| `i{`/`a{` | Inner/around braces |
|
||||
|
||||
## [](#command-history) 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) 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) 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) How backgrounding works
|
||||
|
||||
When Claude Code runs a command in the background, it runs the command asynchronously and immediately returns a background task ID. Claude Code can respond to new prompts while the command continues executing in the background.
|
||||
To run commands in the background, you can either:
|
||||
|
||||
- Prompt Claude Code to run a command in the background
|
||||
- Press Ctrl+B to move a regular Bash tool invocation to the background. (Tmux users must press Ctrl+B twice due to tmux’s prefix key.)
|
||||
|
||||
**Key features:**
|
||||
|
||||
- Output is buffered and Claude can retrieve it using the TaskOutput tool
|
||||
- Background tasks have unique IDs for tracking and output retrieval
|
||||
- Background tasks are automatically cleaned up when Claude Code exits
|
||||
|
||||
To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/docs/en/settings#environment-variables) for details.
|
||||
**Common backgrounded commands:**
|
||||
|
||||
- Build tools (webpack, vite, make)
|
||||
- Package managers (npm, yarn, pnpm)
|
||||
- Test runners (jest, pytest)
|
||||
- Development servers
|
||||
- Long-running processes (docker, terraform)
|
||||
|
||||
### [](#bash-mode-with-prefix) Bash mode with `!` prefix
|
||||
|
||||
Run bash commands directly without going through Claude by prefixing your input with `!`:
|
||||
|
||||
```bash
|
||||
! 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) See also
|
||||
|
||||
- [Slash commands](/docs/en/slash-commands) - Interactive session commands
|
||||
- [Checkpointing](/docs/en/checkpointing) - Rewind Claude’s edits and restore previous states
|
||||
- [CLI reference](/docs/en/cli-reference) - Command-line flags and options
|
||||
- [Settings](/docs/en/settings) - Configuration options
|
||||
- [Memory management](/docs/en/memory) - Managing CLAUDE.md files
|
||||
@@ -0,0 +1,139 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/jetbrains
|
||||
title: JetBrains IDEs
|
||||
---
|
||||
|
||||
Claude Code integrates with JetBrains IDEs through a dedicated plugin, providing features like interactive diff viewing, selection context sharing, and more.
|
||||
|
||||
## [](#supported-ides) Supported IDEs
|
||||
|
||||
The Claude Code plugin works with most JetBrains IDEs, including:
|
||||
|
||||
- IntelliJ IDEA
|
||||
- PyCharm
|
||||
- Android Studio
|
||||
- WebStorm
|
||||
- PhpStorm
|
||||
- GoLand
|
||||
|
||||
## [](#features) Features
|
||||
|
||||
- **Quick launch**: Use `Cmd+Esc` (Mac) or `Ctrl+Esc` (Windows/Linux) to open Claude Code directly from your editor, or click the Claude Code button in the UI
|
||||
- **Diff viewing**: Code changes can be displayed directly in the IDE diff viewer instead of the terminal
|
||||
- **Selection context**: The current selection/tab in the IDE is automatically shared with Claude Code
|
||||
- **File reference shortcuts**: Use `Cmd+Option+K` (Mac) or `Alt+Ctrl+K` (Linux/Windows) to insert file references (for example, @File#L1-99)
|
||||
- **Diagnostic sharing**: Diagnostic errors (lint, syntax, etc.) from the IDE are automatically shared with Claude as you work
|
||||
|
||||
## [](#installation) Installation
|
||||
|
||||
### [](#marketplace-installation) Marketplace Installation
|
||||
|
||||
Find and install the [Claude Code plugin](https://plugins.jetbrains.com/plugin/27310-claude-code-beta-) from the JetBrains marketplace and restart your IDE.
|
||||
If you haven’t installed Claude Code yet, see [our quickstart guide](/docs/en/quickstart) for installation instructions.
|
||||
|
||||
After installing the plugin, you may need to restart your IDE completely for it to take effect.
|
||||
|
||||
## [](#usage) Usage
|
||||
|
||||
### [](#from-your-ide) From Your IDE
|
||||
|
||||
Run `claude` from your IDE’s integrated terminal, and all integration features will be active.
|
||||
|
||||
### [](#from-external-terminals) From External Terminals
|
||||
|
||||
Use the `/ide` command in any external terminal to connect Claude Code to your JetBrains IDE and activate all features:
|
||||
|
||||
```bash
|
||||
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) Configuration
|
||||
|
||||
### [](#claude-code-settings) 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) Plugin Settings
|
||||
|
||||
Configure the Claude Code plugin by going to **Settings → Tools → Claude Code [Beta]**:
|
||||
|
||||
#### [](#general-settings) General Settings
|
||||
|
||||
- **Claude command**: Specify a custom command to run Claude (for example, `claude`, `/usr/local/bin/claude`, or `npx @anthropic/claude`)
|
||||
- **Suppress notification for Claude command not found**: Skip notifications about not finding the Claude command
|
||||
- **Enable using Option+Enter for multi-line prompts** (macOS only): When enabled, Option+Enter inserts new lines in Claude Code prompts. Disable if experiencing issues with the Option key being captured unexpectedly (requires terminal restart)
|
||||
- **Enable automatic updates**: Automatically check for and install plugin updates (applied on restart)
|
||||
|
||||
For WSL users: Set `wsl -d Ubuntu -- bash -lic "claude"` as your Claude command (replace `Ubuntu` with your WSL distribution name)
|
||||
|
||||
#### [](#esc-key-configuration) 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) Special Configurations
|
||||
|
||||
### [](#remote-development) Remote Development
|
||||
|
||||
When using JetBrains Remote Development, you must install the plugin in the remote host via **Settings → Plugin (Host)**.
|
||||
|
||||
The plugin must be installed on the remote host, not on your local client machine.
|
||||
|
||||
### [](#wsl-configuration) WSL Configuration
|
||||
|
||||
WSL users may need additional configuration for IDE detection to work properly. See our [WSL troubleshooting guide](/docs/en/troubleshooting#jetbrains-ide-not-detected-on-wsl2) for detailed setup instructions.
|
||||
|
||||
WSL configuration may require:
|
||||
|
||||
- Proper terminal configuration
|
||||
- Networking mode adjustments
|
||||
- Firewall settings updates
|
||||
|
||||
## [](#troubleshooting) Troubleshooting
|
||||
|
||||
### [](#plugin-not-working) 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) 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](/docs/en/troubleshooting#jetbrains-ide-not-detected-on-wsl2)
|
||||
|
||||
### [](#command-not-found) 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) 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](/docs/en/troubleshooting).
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/legal-and-compliance
|
||||
title: Legal and compliance
|
||||
---
|
||||
|
||||
## [](#legal-agreements) Legal agreements
|
||||
|
||||
### [](#license) 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) 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) Compliance
|
||||
|
||||
### [](#healthcare-compliance-baa) 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) Security and trust
|
||||
|
||||
### [](#trust-and-safety) 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) 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.
|
||||
@@ -0,0 +1,162 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/llm-gateway
|
||||
title: LLM gateway configuration
|
||||
---
|
||||
|
||||
LLM gateways provide a centralized proxy layer between Claude Code and model providers, often providing:
|
||||
|
||||
- **Centralized authentication** - Single point for API key management
|
||||
- **Usage tracking** - Monitor usage across teams and projects
|
||||
- **Cost controls** - Implement budgets and rate limits
|
||||
- **Audit logging** - Track all model interactions for compliance
|
||||
- **Model routing** - Switch between providers without code changes
|
||||
|
||||
## [](#gateway-requirements) Gateway requirements
|
||||
|
||||
For an LLM gateway to work with Claude Code, it must meet the following requirements:
|
||||
**API format**
|
||||
The gateway must expose to clients at least one of the following API formats:
|
||||
|
||||
1. **Anthropic Messages**: `/v1/messages`, `/v1/messages/count_tokens`
|
||||
- Must forward request headers: `anthropic-beta`, `anthropic-version`
|
||||
2. **Bedrock InvokeModel**: `/invoke`, `/invoke-with-response-stream`
|
||||
- Must preserve request body fields: `anthropic_beta`, `anthropic_version`
|
||||
3. **Vertex rawPredict**: `:rawPredict`, `:streamRawPredict`, `/count-tokens:rawPredict`
|
||||
- Must forward request headers: `anthropic-beta`, `anthropic-version`
|
||||
|
||||
Failure to forward headers or preserve body fields may result in reduced functionality or inability to use Claude Code features.
|
||||
|
||||
Claude Code determines which features to enable based on the API format. When using the Anthropic Messages format with Bedrock or Vertex, you may need to set environment variable `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`.
|
||||
|
||||
## [](#configuration) Configuration
|
||||
|
||||
### [](#model-selection) Model selection
|
||||
|
||||
By default, Claude Code will use standard model names for the selected API format.
|
||||
If you have configured custom model names in your gateway, use the environment variables documented in [Model configuration](/docs/en/model-config) to match your custom names.
|
||||
|
||||
## [](#litellm-configuration) LiteLLM configuration
|
||||
|
||||
LiteLLM is a third-party proxy service. Anthropic doesn’t endorse, maintain, or audit LiteLLM’s security or functionality. This guide is provided for informational purposes and may become outdated. Use at your own discretion.
|
||||
|
||||
### [](#prerequisites) 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) Basic LiteLLM setup
|
||||
|
||||
**Configure Claude Code**:
|
||||
|
||||
#### [](#authentication-methods) Authentication methods
|
||||
|
||||
##### Static API key
|
||||
|
||||
Simplest method using a fixed API key:
|
||||
|
||||
```bash
|
||||
# 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
|
||||
#!/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:
|
||||
|
||||
```bash
|
||||
{
|
||||
"apiKeyHelper": "~/bin/get-litellm-key.sh"
|
||||
}
|
||||
```
|
||||
|
||||
3. Set token refresh interval:
|
||||
|
||||
```bash
|
||||
# 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) Unified endpoint (recommended)
|
||||
|
||||
Using LiteLLM’s [Anthropic format endpoint](https://docs.litellm.ai/docs/anthropic_unified):
|
||||
|
||||
```bash
|
||||
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) Provider-specific pass-through endpoints (alternative)
|
||||
|
||||
##### Claude API through LiteLLM
|
||||
|
||||
Using [pass-through endpoint](https://docs.litellm.ai/docs/pass_through/anthropic_completion):
|
||||
|
||||
```bash
|
||||
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
|
||||
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
|
||||
export ANTHROPIC_VERTEX_BASE_URL=https://litellm-server:4000/vertex_ai/v1
|
||||
export ANTHROPIC_VERTEX_PROJECT_ID=your-gcp-project-id
|
||||
export CLAUDE_CODE_SKIP_VERTEX_AUTH=1
|
||||
export CLAUDE_CODE_USE_VERTEX=1
|
||||
export CLOUD_ML_REGION=us-east5
|
||||
```
|
||||
|
||||
For more detailed information, refer to the [LiteLLM documentation](https://docs.litellm.ai/).
|
||||
|
||||
## [](#additional-resources) Additional resources
|
||||
|
||||
- [LiteLLM documentation](https://docs.litellm.ai/)
|
||||
- [Claude Code settings](/docs/en/settings)
|
||||
- [Enterprise network configuration](/docs/en/network-config)
|
||||
- [Third-party integrations overview](/docs/en/third-party-integrations)
|
||||
@@ -0,0 +1,872 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/mcp
|
||||
title: Connect Claude Code to tools via MCP
|
||||
---
|
||||
|
||||
Claude Code can connect to hundreds of external tools and data sources through the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction), an open source standard for AI-tool integrations. MCP servers give Claude Code access to your tools, databases, and APIs.
|
||||
|
||||
## [](#what-you-can-do-with-mcp) What you can do with MCP
|
||||
|
||||
With MCP servers connected, you can ask Claude Code to:
|
||||
|
||||
- **Implement features from issue trackers**: “Add the feature described in JIRA issue ENG-4521 and create a PR on GitHub.”
|
||||
- **Analyze monitoring data**: “Check Sentry and Statsig to check the usage of the feature described in ENG-4521.”
|
||||
- **Query databases**: “Find emails of 10 random users who used feature ENG-4521, based on our PostgreSQL database.”
|
||||
- **Integrate designs**: “Update our standard email template based on the new Figma designs that were posted in Slack”
|
||||
- **Automate workflows**: “Create Gmail drafts inviting these 10 users to a feedback session about the new feature.”
|
||||
|
||||
## [](#popular-mcp-servers) Popular MCP servers
|
||||
|
||||
Here are some commonly used MCP servers you can connect to Claude Code:
|
||||
|
||||
Use third party MCP servers at your own risk - Anthropic has not verified
|
||||
the correctness or security of all these servers.
|
||||
Make sure you trust MCP servers you are installing.
|
||||
Be especially careful when using MCP servers that could fetch untrusted
|
||||
content, as these can expose you to prompt injection risk.
|
||||
|
||||
**Need a specific integration?** [Find hundreds more MCP servers on GitHub](https://github.com/modelcontextprotocol/servers), or build your own using the [MCP SDK](https://modelcontextprotocol.io/quickstart/server).
|
||||
|
||||
## [](#installing-mcp-servers) Installing MCP servers
|
||||
|
||||
MCP servers can be configured in three different ways depending on your needs:
|
||||
|
||||
### [](#option-1:-add-a-remote-http-server) Option 1: Add a remote HTTP server
|
||||
|
||||
HTTP servers are the recommended option for connecting to remote MCP servers. This is the most widely supported transport for cloud-based services.
|
||||
|
||||
```bash
|
||||
# Basic syntax
|
||||
claude mcp add --transport http <name> <url>
|
||||
|
||||
# Real example: Connect to Notion
|
||||
claude mcp add --transport http notion https://mcp.notion.com/mcp
|
||||
|
||||
# Example with Bearer token
|
||||
claude mcp add --transport http secure-api https://api.example.com/mcp \
|
||||
--header "Authorization: Bearer your-token"
|
||||
```
|
||||
|
||||
### [](#option-2:-add-a-remote-sse-server) Option 2: Add a remote SSE server
|
||||
|
||||
The SSE (Server-Sent Events) transport is deprecated. Use HTTP servers instead, where available.
|
||||
|
||||
```bash
|
||||
# Basic syntax
|
||||
claude mcp add --transport sse <name> <url>
|
||||
|
||||
# Real example: Connect to Asana
|
||||
claude mcp add --transport sse asana https://mcp.asana.com/sse
|
||||
|
||||
# Example with authentication header
|
||||
claude mcp add --transport sse private-api https://api.company.com/sse \
|
||||
--header "X-API-Key: your-key-here"
|
||||
```
|
||||
|
||||
### [](#option-3:-add-a-local-stdio-server) Option 3: Add a local stdio server
|
||||
|
||||
Stdio servers run as local processes on your machine. They’re ideal for tools that need direct system access or custom scripts.
|
||||
|
||||
```bash
|
||||
# Basic syntax
|
||||
claude mcp add [options] <name> -- <command> [args...]
|
||||
|
||||
# Real example: Add Airtable server
|
||||
claude mcp add --transport stdio --env AIRTABLE_API_KEY=YOUR_KEY airtable \
|
||||
-- npx -y airtable-mcp-server
|
||||
```
|
||||
|
||||
**Important: Option ordering**All options (`--transport`, `--env`, `--scope`, `--header`) must come **before** the server name. The `--` (double dash) then separates the server name from the command and arguments that get passed to the MCP server.For example:
|
||||
|
||||
- `claude mcp add --transport stdio myserver -- npx server` → runs `npx server`
|
||||
- `claude mcp add --transport stdio --env KEY=value myserver -- python server.py --port 8080` → runs `python server.py --port 8080` with `KEY=value` in environment
|
||||
|
||||
This prevents conflicts between Claude’s flags and the server’s flags.
|
||||
|
||||
### [](#managing-your-servers) Managing your servers
|
||||
|
||||
Once configured, you can manage your MCP servers with these commands:
|
||||
|
||||
```bash
|
||||
# List all configured servers
|
||||
claude mcp list
|
||||
|
||||
# Get details for a specific server
|
||||
claude mcp get github
|
||||
|
||||
# Remove a server
|
||||
claude mcp remove github
|
||||
|
||||
# (within Claude Code) Check server status
|
||||
/mcp
|
||||
```
|
||||
|
||||
### [](#dynamic-tool-updates) Dynamic tool updates
|
||||
|
||||
Claude Code supports MCP `list_changed` notifications, allowing MCP servers to dynamically update their available tools, prompts, and resources without requiring you to disconnect and reconnect. When an MCP server sends a `list_changed` notification, Claude Code automatically refreshes the available capabilities from that server.
|
||||
|
||||
Tips:
|
||||
|
||||
- Use the `--scope` flag to specify where the configuration is stored:
|
||||
- `local` (default): Available only to you in the current project (was called `project` in older versions)
|
||||
- `project`: Shared with everyone in the project via `.mcp.json` file
|
||||
- `user`: Available to you across all projects (was called `global` in older versions)
|
||||
- Set environment variables with `--env` flags (for example, `--env KEY=value`)
|
||||
- Configure MCP server startup timeout using the MCP\_TIMEOUT environment variable (for example, `MCP_TIMEOUT=10000 claude` sets a 10-second timeout)
|
||||
- Claude Code will display a warning when MCP tool output exceeds 10,000 tokens. To increase this limit, set the `MAX_MCP_OUTPUT_TOKENS` environment variable (for example, `MAX_MCP_OUTPUT_TOKENS=50000`)
|
||||
- Use `/mcp` to authenticate with remote servers that require OAuth 2.0 authentication
|
||||
|
||||
**Windows Users**: On native Windows (not WSL), local MCP servers that use `npx` require the `cmd /c` wrapper to ensure proper execution.
|
||||
|
||||
```bash
|
||||
# This creates command="cmd" which Windows can execute
|
||||
claude mcp add --transport stdio my-server -- cmd /c npx -y @some/package
|
||||
```
|
||||
|
||||
Without the `cmd /c` wrapper, you’ll encounter “Connection closed” errors because Windows cannot directly execute `npx`. (See the note above for an explanation of the `--` parameter.)
|
||||
|
||||
### [](#plugin-provided-mcp-servers) Plugin-provided MCP servers
|
||||
|
||||
[Plugins](/docs/en/plugins) can bundle MCP servers, automatically providing tools and integrations when the plugin is enabled. Plugin MCP servers work identically to user-configured servers.
|
||||
**How plugin MCP servers work**:
|
||||
|
||||
- Plugins define MCP servers in `.mcp.json` at the plugin root or inline in `plugin.json`
|
||||
- When a plugin is enabled, its MCP servers start automatically
|
||||
- Plugin MCP tools appear alongside manually configured MCP tools
|
||||
- Plugin servers are managed through plugin installation (not `/mcp` commands)
|
||||
|
||||
**Example plugin MCP configuration**:
|
||||
In `.mcp.json` at plugin root:
|
||||
|
||||
```bash
|
||||
{
|
||||
"database-tools": {
|
||||
"command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server",
|
||||
"args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"],
|
||||
"env": {
|
||||
"DB_URL": "${DB_URL}"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Or inline in `plugin.json`:
|
||||
|
||||
```bash
|
||||
{
|
||||
"name": "my-plugin",
|
||||
"mcpServers": {
|
||||
"plugin-api": {
|
||||
"command": "${CLAUDE_PLUGIN_ROOT}/servers/api-server",
|
||||
"args": ["--port", "8080"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Plugin MCP features**:
|
||||
|
||||
- **Automatic lifecycle**: Servers start when plugin enables, but you must restart Claude Code to apply MCP server changes (enabling or disabling)
|
||||
- **Environment variables**: Use `${CLAUDE_PLUGIN_ROOT}` for plugin-relative paths
|
||||
- **User environment access**: Access to same environment variables as manually configured servers
|
||||
- **Multiple transport types**: Support stdio, SSE, and HTTP transports (transport support may vary by server)
|
||||
|
||||
**Viewing plugin MCP servers**:
|
||||
|
||||
```bash
|
||||
# Within Claude Code, see all MCP servers including plugin ones
|
||||
/mcp
|
||||
```
|
||||
|
||||
Plugin servers appear in the list with indicators showing they come from plugins.
|
||||
**Benefits of plugin MCP servers**:
|
||||
|
||||
- **Bundled distribution**: Tools and servers packaged together
|
||||
- **Automatic setup**: No manual MCP configuration needed
|
||||
- **Team consistency**: Everyone gets the same tools when plugin is installed
|
||||
|
||||
See the [plugin components reference](/docs/en/plugins-reference#mcp-servers) for details on bundling MCP servers with plugins.
|
||||
|
||||
## [](#mcp-installation-scopes) MCP installation scopes
|
||||
|
||||
MCP servers can be configured at three different scope levels, each serving distinct purposes for managing server accessibility and sharing. Understanding these scopes helps you determine the best way to configure servers for your specific needs.
|
||||
|
||||
### [](#local-scope) Local scope
|
||||
|
||||
Local-scoped servers represent the default configuration level and are stored in `~/.claude.json` under your project’s path. These servers remain private to you and are only accessible when working within the current project directory. This scope is ideal for personal development servers, experimental configurations, or servers containing sensitive credentials that shouldn’t be shared.
|
||||
|
||||
```bash
|
||||
# Add a local-scoped server (default)
|
||||
claude mcp add --transport http stripe https://mcp.stripe.com
|
||||
|
||||
# Explicitly specify local scope
|
||||
claude mcp add --transport http stripe --scope local https://mcp.stripe.com
|
||||
```
|
||||
|
||||
### [](#project-scope) Project scope
|
||||
|
||||
Project-scoped servers enable team collaboration by storing configurations in a `.mcp.json` file at your project’s root directory. This file is designed to be checked into version control, ensuring all team members have access to the same MCP tools and services. When you add a project-scoped server, Claude Code automatically creates or updates this file with the appropriate configuration structure.
|
||||
|
||||
```bash
|
||||
# Add a project-scoped server
|
||||
claude mcp add --transport http paypal --scope project https://mcp.paypal.com/mcp
|
||||
```
|
||||
|
||||
The resulting `.mcp.json` file follows a standardized format:
|
||||
|
||||
```bash
|
||||
{
|
||||
"mcpServers": {
|
||||
"shared-server": {
|
||||
"command": "/path/to/server",
|
||||
"args": [],
|
||||
"env": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
For security reasons, Claude Code prompts for approval before using project-scoped servers from `.mcp.json` files. If you need to reset these approval choices, use the `claude mcp reset-project-choices` command.
|
||||
|
||||
### [](#user-scope) User scope
|
||||
|
||||
User-scoped servers are stored in `~/.claude.json` and provide cross-project accessibility, making them available across all projects on your machine while remaining private to your user account. This scope works well for personal utility servers, development tools, or services you frequently use across different projects.
|
||||
|
||||
```bash
|
||||
# Add a user server
|
||||
claude mcp add --transport http hubspot --scope user https://mcp.hubspot.com/anthropic
|
||||
```
|
||||
|
||||
### [](#choosing-the-right-scope) Choosing the right scope
|
||||
|
||||
Select your scope based on:
|
||||
|
||||
- **Local scope**: Personal servers, experimental configurations, or sensitive credentials specific to one project
|
||||
- **Project scope**: Team-shared servers, project-specific tools, or services required for collaboration
|
||||
- **User scope**: Personal utilities needed across multiple projects, development tools, or frequently used services
|
||||
|
||||
**Where are MCP servers stored?**
|
||||
|
||||
- **User and local scope**: `~/.claude.json` (in the `mcpServers` field or under project paths)
|
||||
- **Project scope**: `.mcp.json` in your project root (checked into source control)
|
||||
- **Managed**: `managed-mcp.json` in system directories (see [Managed MCP configuration](#managed-mcp-configuration))
|
||||
|
||||
### [](#scope-hierarchy-and-precedence) Scope hierarchy and precedence
|
||||
|
||||
MCP server configurations follow a clear precedence hierarchy. When servers with the same name exist at multiple scopes, the system resolves conflicts by prioritizing local-scoped servers first, followed by project-scoped servers, and finally user-scoped servers. This design ensures that personal configurations can override shared ones when needed.
|
||||
|
||||
### [](#environment-variable-expansion-in-mcp-json) Environment variable expansion in `.mcp.json`
|
||||
|
||||
Claude Code supports environment variable expansion in `.mcp.json` files, allowing teams to share configurations while maintaining flexibility for machine-specific paths and sensitive values like API keys.
|
||||
**Supported syntax:**
|
||||
|
||||
- `${VAR}` - Expands to the value of environment variable `VAR`
|
||||
- `${VAR:-default}` - Expands to `VAR` if set, otherwise uses `default`
|
||||
|
||||
**Expansion locations:**
|
||||
Environment variables can be expanded in:
|
||||
|
||||
- `command` - The server executable path
|
||||
- `args` - Command-line arguments
|
||||
- `env` - Environment variables passed to the server
|
||||
- `url` - For HTTP server types
|
||||
- `headers` - For HTTP server authentication
|
||||
|
||||
**Example with variable expansion:**
|
||||
|
||||
```bash
|
||||
{
|
||||
"mcpServers": {
|
||||
"api-server": {
|
||||
"type": "http",
|
||||
"url": "${API_BASE_URL:-https://api.example.com}/mcp",
|
||||
"headers": {
|
||||
"Authorization": "Bearer ${API_KEY}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If a required environment variable is not set and has no default value, Claude Code will fail to parse the config.
|
||||
|
||||
## [](#practical-examples) Practical examples
|
||||
|
||||
### [](#example:-monitor-errors-with-sentry) Example: Monitor errors with Sentry
|
||||
|
||||
```bash
|
||||
# 1. Add the Sentry MCP server
|
||||
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp
|
||||
|
||||
# 2. Use /mcp to authenticate with your Sentry account
|
||||
> /mcp
|
||||
|
||||
# 3. Debug production issues
|
||||
> "What are the most common errors in the last 24 hours?"
|
||||
> "Show me the stack trace for error ID abc123"
|
||||
> "Which deployment introduced these new errors?"
|
||||
```
|
||||
|
||||
### [](#example:-connect-to-github-for-code-reviews) Example: Connect to GitHub for code reviews
|
||||
|
||||
```bash
|
||||
# 1. Add the GitHub MCP server
|
||||
claude mcp add --transport http github https://api.githubcopilot.com/mcp/
|
||||
|
||||
# 2. In Claude Code, authenticate if needed
|
||||
> /mcp
|
||||
# Select "Authenticate" for GitHub
|
||||
|
||||
# 3. Now you can ask Claude to work with GitHub
|
||||
> "Review PR #456 and suggest improvements"
|
||||
> "Create a new issue for the bug we just found"
|
||||
> "Show me all open PRs assigned to me"
|
||||
```
|
||||
|
||||
### [](#example:-query-your-postgresql-database) Example: Query your PostgreSQL database
|
||||
|
||||
```bash
|
||||
# 1. Add the database server with your connection string
|
||||
claude mcp add --transport stdio db -- npx -y @bytebase/dbhub \
|
||||
--dsn "postgresql://readonly:[email protected]:5432/analytics"
|
||||
|
||||
# 2. Query your database naturally
|
||||
> "What's our total revenue this month?"
|
||||
> "Show me the schema for the orders table"
|
||||
> "Find customers who haven't made a purchase in 90 days"
|
||||
```
|
||||
|
||||
## [](#authenticate-with-remote-mcp-servers) Authenticate with remote MCP servers
|
||||
|
||||
Many cloud-based MCP servers require authentication. Claude Code supports OAuth 2.0 for secure connections.
|
||||
|
||||
1
|
||||
|
||||
Add the server that requires authentication
|
||||
|
||||
For example:
|
||||
|
||||
```bash
|
||||
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp
|
||||
```
|
||||
|
||||
2
|
||||
|
||||
Use the /mcp command within Claude Code
|
||||
|
||||
In Claude code, use the command:
|
||||
|
||||
```bash
|
||||
> /mcp
|
||||
```
|
||||
|
||||
Then follow the steps in your browser to login.
|
||||
|
||||
Tips:
|
||||
|
||||
- Authentication tokens are stored securely and refreshed automatically
|
||||
- Use “Clear authentication” in the `/mcp` menu to revoke access
|
||||
- If your browser doesn’t open automatically, copy the provided URL
|
||||
- OAuth authentication works with HTTP servers
|
||||
|
||||
## [](#add-mcp-servers-from-json-configuration) Add MCP servers from JSON configuration
|
||||
|
||||
If you have a JSON configuration for an MCP server, you can add it directly:
|
||||
|
||||
1
|
||||
|
||||
Add an MCP server from JSON
|
||||
|
||||
```bash
|
||||
# Basic syntax
|
||||
claude mcp add-json <name> '<json>'
|
||||
|
||||
# Example: Adding an HTTP server with JSON configuration
|
||||
claude mcp add-json weather-api '{"type":"http","url":"https://api.weather.com/mcp","headers":{"Authorization":"Bearer token"}}'
|
||||
|
||||
# Example: Adding a stdio server with JSON configuration
|
||||
claude mcp add-json local-weather '{"type":"stdio","command":"/path/to/weather-cli","args":["--api-key","abc123"],"env":{"CACHE_DIR":"/tmp"}}'
|
||||
```
|
||||
|
||||
2
|
||||
|
||||
Verify the server was added
|
||||
|
||||
```bash
|
||||
claude mcp get weather-api
|
||||
```
|
||||
|
||||
Tips:
|
||||
|
||||
- Make sure the JSON is properly escaped in your shell
|
||||
- The JSON must conform to the MCP server configuration schema
|
||||
- You can use `--scope user` to add the server to your user configuration instead of the project-specific one
|
||||
|
||||
## [](#import-mcp-servers-from-claude-desktop) Import MCP servers from Claude Desktop
|
||||
|
||||
If you’ve already configured MCP servers in Claude Desktop, you can import them:
|
||||
|
||||
1
|
||||
|
||||
Import servers from Claude Desktop
|
||||
|
||||
```bash
|
||||
# Basic syntax
|
||||
claude mcp add-from-claude-desktop
|
||||
```
|
||||
|
||||
2
|
||||
|
||||
Select which servers to import
|
||||
|
||||
After running the command, you’ll see an interactive dialog that allows you to select which servers you want to import.
|
||||
|
||||
3
|
||||
|
||||
Verify the servers were imported
|
||||
|
||||
```bash
|
||||
claude mcp list
|
||||
```
|
||||
|
||||
Tips:
|
||||
|
||||
- This feature only works on macOS and Windows Subsystem for Linux (WSL)
|
||||
- It reads the Claude Desktop configuration file from its standard location on those platforms
|
||||
- Use the `--scope user` flag to add servers to your user configuration
|
||||
- Imported servers will have the same names as in Claude Desktop
|
||||
- If servers with the same names already exist, they will get a numerical suffix (for example, `server_1`)
|
||||
|
||||
## [](#use-claude-code-as-an-mcp-server) Use Claude Code as an MCP server
|
||||
|
||||
You can use Claude Code itself as an MCP server that other applications can connect to:
|
||||
|
||||
```bash
|
||||
# Start Claude as a stdio MCP server
|
||||
claude mcp serve
|
||||
```
|
||||
|
||||
You can use this in Claude Desktop by adding this configuration to claude\_desktop\_config.json:
|
||||
|
||||
```bash
|
||||
{
|
||||
"mcpServers": {
|
||||
"claude-code": {
|
||||
"type": "stdio",
|
||||
"command": "claude",
|
||||
"args": ["mcp", "serve"],
|
||||
"env": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Configuring the executable path**: The `command` field must reference the Claude Code executable. If the `claude` command is not in your system’s PATH, you’ll need to specify the full path to the executable.To find the full path:
|
||||
|
||||
```bash
|
||||
which claude
|
||||
```
|
||||
|
||||
Then use the full path in your configuration:
|
||||
|
||||
```bash
|
||||
{
|
||||
"mcpServers": {
|
||||
"claude-code": {
|
||||
"type": "stdio",
|
||||
"command": "/full/path/to/claude",
|
||||
"args": ["mcp", "serve"],
|
||||
"env": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Without the correct executable path, you’ll encounter errors like `spawn claude ENOENT`.
|
||||
|
||||
Tips:
|
||||
|
||||
- The server provides access to Claude’s tools like View, Edit, LS, etc.
|
||||
- In Claude Desktop, try asking Claude to read files in a directory, make edits, and more.
|
||||
- Note that this MCP server is only exposing Claude Code’s tools to your MCP client, so your own client is responsible for implementing user confirmation for individual tool calls.
|
||||
|
||||
## [](#mcp-output-limits-and-warnings) MCP output limits and warnings
|
||||
|
||||
When MCP tools produce large outputs, Claude Code helps manage the token usage to prevent overwhelming your conversation context:
|
||||
|
||||
- **Output warning threshold**: Claude Code displays a warning when any MCP tool output exceeds 10,000 tokens
|
||||
- **Configurable limit**: You can adjust the maximum allowed MCP output tokens using the `MAX_MCP_OUTPUT_TOKENS` environment variable
|
||||
- **Default limit**: The default maximum is 25,000 tokens
|
||||
|
||||
To increase the limit for tools that produce large outputs:
|
||||
|
||||
```bash
|
||||
# Set a higher limit for MCP tool outputs
|
||||
export MAX_MCP_OUTPUT_TOKENS=50000
|
||||
claude
|
||||
```
|
||||
|
||||
This is particularly useful when working with MCP servers that:
|
||||
|
||||
- Query large datasets or databases
|
||||
- Generate detailed reports or documentation
|
||||
- Process extensive log files or debugging information
|
||||
|
||||
If you frequently encounter output warnings with specific MCP servers, consider increasing the limit or configuring the server to paginate or filter its responses.
|
||||
|
||||
## [](#use-mcp-resources) Use MCP resources
|
||||
|
||||
MCP servers can expose resources that you can reference using @ mentions, similar to how you reference files.
|
||||
|
||||
### [](#reference-mcp-resources) Reference MCP resources
|
||||
|
||||
1
|
||||
|
||||
List available resources
|
||||
|
||||
Type `@` in your prompt to see available resources from all connected MCP servers. Resources appear alongside files in the autocomplete menu.
|
||||
|
||||
2
|
||||
|
||||
Reference a specific resource
|
||||
|
||||
Use the format `@server:protocol://resource/path` to reference a resource:
|
||||
|
||||
```bash
|
||||
> Can you analyze @github:issue://123 and suggest a fix?
|
||||
```
|
||||
|
||||
```bash
|
||||
> Please review the API documentation at @docs:file://api/authentication
|
||||
```
|
||||
|
||||
3
|
||||
|
||||
Multiple resource references
|
||||
|
||||
You can reference multiple resources in a single prompt:
|
||||
|
||||
```bash
|
||||
> Compare @postgres:schema://users with @docs:file://database/user-model
|
||||
```
|
||||
|
||||
Tips:
|
||||
|
||||
- Resources are automatically fetched and included as attachments when referenced
|
||||
- Resource paths are fuzzy-searchable in the @ mention autocomplete
|
||||
- Claude Code automatically provides tools to list and read MCP resources when servers support them
|
||||
- Resources can contain any type of content that the MCP server provides (text, JSON, structured data, etc.)
|
||||
|
||||
## [](#scale-with-mcp-tool-search) Scale with MCP Tool Search
|
||||
|
||||
When you have many MCP servers configured, tool definitions can consume a significant portion of your context window. MCP Tool Search solves this by dynamically loading tools on-demand instead of preloading all of them.
|
||||
|
||||
### [](#how-it-works) How it works
|
||||
|
||||
Claude Code automatically enables Tool Search when your MCP tool descriptions would consume more than 10% of the context window. You can [adjust this threshold](#configure-tool-search) or disable tool search entirely. When triggered:
|
||||
|
||||
1. MCP tools are deferred rather than loaded into context upfront
|
||||
2. Claude uses a search tool to discover relevant MCP tools when needed
|
||||
3. Only the tools Claude actually needs are loaded into context
|
||||
4. MCP tools continue to work exactly as before from your perspective
|
||||
|
||||
### [](#for-mcp-server-authors) For MCP server authors
|
||||
|
||||
If you’re building an MCP server, the server instructions field becomes more useful with Tool Search enabled. Server instructions help Claude understand when to search for your tools, similar to how [skills](/docs/en/skills) work.
|
||||
Add clear, descriptive server instructions that explain:
|
||||
|
||||
- What category of tasks your tools handle
|
||||
- When Claude should search for your tools
|
||||
- Key capabilities your server provides
|
||||
|
||||
### [](#configure-tool-search) Configure tool search
|
||||
|
||||
Tool search runs in auto mode by default, meaning it activates only when your MCP tool definitions exceed the context threshold. If you have few tools, they load normally without tool search. This feature requires models that support `tool_reference` blocks: Sonnet 4 and later, or Opus 4 and later. Haiku models do not support tool search.
|
||||
Control tool search behavior with the `ENABLE_TOOL_SEARCH` environment variable:
|
||||
|
||||
| Value | Behavior |
|
||||
| --- | --- |
|
||||
| `auto` | Activates when MCP tools exceed 10% of context (default) |
|
||||
| `auto:<N>` | Activates at custom threshold, where `<N>` is a percentage (e.g., `auto:5` for 5%) |
|
||||
| `true` | Always enabled |
|
||||
| `false` | Disabled, all MCP tools loaded upfront |
|
||||
|
||||
```bash
|
||||
# Use a custom 5% threshold
|
||||
ENABLE_TOOL_SEARCH=auto:5 claude
|
||||
|
||||
# Disable tool search entirely
|
||||
ENABLE_TOOL_SEARCH=false claude
|
||||
```
|
||||
|
||||
Or set the value in your [settings.json `env` field](/docs/en/settings#available-settings).
|
||||
You can also disable the MCPSearch tool specifically using the `disallowedTools` setting:
|
||||
|
||||
```bash
|
||||
{
|
||||
"permissions": {
|
||||
"deny": ["MCPSearch"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## [](#use-mcp-prompts-as-slash-commands) Use MCP prompts as slash commands
|
||||
|
||||
MCP servers can expose prompts that become available as slash commands in Claude Code.
|
||||
|
||||
### [](#execute-mcp-prompts) Execute MCP prompts
|
||||
|
||||
1
|
||||
|
||||
Discover available prompts
|
||||
|
||||
Type `/` to see all available commands, including those from MCP servers. MCP prompts appear with the format `/mcp__servername__promptname`.
|
||||
|
||||
2
|
||||
|
||||
Execute a prompt without arguments
|
||||
|
||||
```bash
|
||||
> /mcp__github__list_prs
|
||||
```
|
||||
|
||||
3
|
||||
|
||||
Execute a prompt with arguments
|
||||
|
||||
Many prompts accept arguments. Pass them space-separated after the command:
|
||||
|
||||
```bash
|
||||
> /mcp__github__pr_review 456
|
||||
```
|
||||
|
||||
```bash
|
||||
> /mcp__jira__create_issue "Bug in login flow" high
|
||||
```
|
||||
|
||||
Tips:
|
||||
|
||||
- MCP prompts are dynamically discovered from connected servers
|
||||
- Arguments are parsed based on the prompt’s defined parameters
|
||||
- Prompt results are injected directly into the conversation
|
||||
- Server and prompt names are normalized (spaces become underscores)
|
||||
|
||||
## [](#managed-mcp-configuration) Managed MCP configuration
|
||||
|
||||
For organizations that need centralized control over MCP servers, Claude Code supports two configuration options:
|
||||
|
||||
1. **Exclusive control with `managed-mcp.json`**: Deploy a fixed set of MCP servers that users cannot modify or extend
|
||||
2. **Policy-based control with allowlists/denylists**: Allow users to add their own servers, but restrict which ones are permitted
|
||||
|
||||
These options allow IT administrators to:
|
||||
|
||||
- **Control which MCP servers employees can access**: Deploy a standardized set of approved MCP servers across the organization
|
||||
- **Prevent unauthorized MCP servers**: Restrict users from adding unapproved MCP servers
|
||||
- **Disable MCP entirely**: Remove MCP functionality completely if needed
|
||||
|
||||
### [](#option-1:-exclusive-control-with-managed-mcp-json) Option 1: Exclusive control with managed-mcp.json
|
||||
|
||||
When you deploy a `managed-mcp.json` file, it takes **exclusive control** over all MCP servers. Users cannot add, modify, or use any MCP servers other than those defined in this file. This is the simplest approach for organizations that want complete control.
|
||||
System administrators deploy the configuration file to a system-wide directory:
|
||||
|
||||
- macOS: `/Library/Application Support/ClaudeCode/managed-mcp.json`
|
||||
- Linux and WSL: `/etc/claude-code/managed-mcp.json`
|
||||
- Windows: `C:\Program Files\ClaudeCode\managed-mcp.json`
|
||||
|
||||
These are system-wide paths (not user home directories like `~/Library/...`) that require administrator privileges. They are designed to be deployed by IT administrators.
|
||||
|
||||
The `managed-mcp.json` file uses the same format as a standard `.mcp.json` file:
|
||||
|
||||
```bash
|
||||
{
|
||||
"mcpServers": {
|
||||
"github": {
|
||||
"type": "http",
|
||||
"url": "https://api.githubcopilot.com/mcp/"
|
||||
},
|
||||
"sentry": {
|
||||
"type": "http",
|
||||
"url": "https://mcp.sentry.dev/mcp"
|
||||
},
|
||||
"company-internal": {
|
||||
"type": "stdio",
|
||||
"command": "/usr/local/bin/company-mcp-server",
|
||||
"args": ["--config", "/etc/company/mcp-config.json"],
|
||||
"env": {
|
||||
"COMPANY_API_URL": "https://internal.company.com"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### [](#option-2:-policy-based-control-with-allowlists-and-denylists) Option 2: Policy-based control with allowlists and denylists
|
||||
|
||||
Instead of taking exclusive control, administrators can allow users to configure their own MCP servers while enforcing restrictions on which servers are permitted. This approach uses `allowedMcpServers` and `deniedMcpServers` in the [managed settings file](/docs/en/settings#settings-files).
|
||||
|
||||
**Choosing between options**: Use Option 1 (`managed-mcp.json`) when you want to deploy a fixed set of servers with no user customization. Use Option 2 (allowlists/denylists) when you want to allow users to add their own servers within policy constraints.
|
||||
|
||||
#### [](#restriction-options) Restriction options
|
||||
|
||||
Each entry in the allowlist or denylist can restrict servers in three ways:
|
||||
|
||||
1. **By server name** (`serverName`): Matches the configured name of the server
|
||||
2. **By command** (`serverCommand`): Matches the exact command and arguments used to start stdio servers
|
||||
3. **By URL pattern** (`serverUrl`): Matches remote server URLs with wildcard support
|
||||
|
||||
**Important**: Each entry must have exactly one of `serverName`, `serverCommand`, or `serverUrl`.
|
||||
|
||||
#### [](#example-configuration) Example configuration
|
||||
|
||||
```bash
|
||||
{
|
||||
"allowedMcpServers": [
|
||||
// Allow by server name
|
||||
{ "serverName": "github" },
|
||||
{ "serverName": "sentry" },
|
||||
|
||||
// Allow by exact command (for stdio servers)
|
||||
{ "serverCommand": ["npx", "-y", "@modelcontextprotocol/server-filesystem"] },
|
||||
{ "serverCommand": ["python", "/usr/local/bin/approved-server.py"] },
|
||||
|
||||
// Allow by URL pattern (for remote servers)
|
||||
{ "serverUrl": "https://mcp.company.com/*" },
|
||||
{ "serverUrl": "https://*.internal.corp/*" }
|
||||
],
|
||||
"deniedMcpServers": [
|
||||
// Block by server name
|
||||
{ "serverName": "dangerous-server" },
|
||||
|
||||
// Block by exact command (for stdio servers)
|
||||
{ "serverCommand": ["npx", "-y", "unapproved-package"] },
|
||||
|
||||
// Block by URL pattern (for remote servers)
|
||||
{ "serverUrl": "https://*.untrusted.com/*" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### [](#how-command-based-restrictions-work) How command-based restrictions work
|
||||
|
||||
**Exact matching**:
|
||||
|
||||
- Command arrays must match **exactly** - both the command and all arguments in the correct order
|
||||
- Example: `["npx", "-y", "server"]` will NOT match `["npx", "server"]` or `["npx", "-y", "server", "--flag"]`
|
||||
|
||||
**Stdio server behavior**:
|
||||
|
||||
- When the allowlist contains **any** `serverCommand` entries, stdio servers **must** match one of those commands
|
||||
- Stdio servers cannot pass by name alone when command restrictions are present
|
||||
- This ensures administrators can enforce which commands are allowed to run
|
||||
|
||||
**Non-stdio server behavior**:
|
||||
|
||||
- Remote servers (HTTP, SSE, WebSocket) use URL-based matching when `serverUrl` entries exist in the allowlist
|
||||
- If no URL entries exist, remote servers fall back to name-based matching
|
||||
- Command restrictions do not apply to remote servers
|
||||
|
||||
#### [](#how-url-based-restrictions-work) How URL-based restrictions work
|
||||
|
||||
URL patterns support wildcards using `*` to match any sequence of characters. This is useful for allowing entire domains or subdomains.
|
||||
**Wildcard examples**:
|
||||
|
||||
- `https://mcp.company.com/*` - Allow all paths on a specific domain
|
||||
- `https://*.example.com/*` - Allow any subdomain of example.com
|
||||
- `http://localhost:*/*` - Allow any port on localhost
|
||||
|
||||
**Remote server behavior**:
|
||||
|
||||
- When the allowlist contains **any** `serverUrl` entries, remote servers **must** match one of those URL patterns
|
||||
- Remote servers cannot pass by name alone when URL restrictions are present
|
||||
- This ensures administrators can enforce which remote endpoints are allowed
|
||||
|
||||
Example: URL-only allowlist
|
||||
|
||||
```bash
|
||||
{
|
||||
"allowedMcpServers": [
|
||||
{ "serverUrl": "https://mcp.company.com/*" },
|
||||
{ "serverUrl": "https://*.internal.corp/*" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Result**:
|
||||
|
||||
- HTTP server at `https://mcp.company.com/api`: ✅ Allowed (matches URL pattern)
|
||||
- HTTP server at `https://api.internal.corp/mcp`: ✅ Allowed (matches wildcard subdomain)
|
||||
- HTTP server at `https://external.com/mcp`: ❌ Blocked (doesn’t match any URL pattern)
|
||||
- Stdio server with any command: ❌ Blocked (no name or command entries to match)
|
||||
|
||||
Example: Command-only allowlist
|
||||
|
||||
```bash
|
||||
{
|
||||
"allowedMcpServers": [
|
||||
{ "serverCommand": ["npx", "-y", "approved-package"] }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Result**:
|
||||
|
||||
- Stdio server with `["npx", "-y", "approved-package"]`: ✅ Allowed (matches command)
|
||||
- Stdio server with `["node", "server.js"]`: ❌ Blocked (doesn’t match command)
|
||||
- HTTP server named “my-api”: ❌ Blocked (no name entries to match)
|
||||
|
||||
Example: Mixed name and command allowlist
|
||||
|
||||
```bash
|
||||
{
|
||||
"allowedMcpServers": [
|
||||
{ "serverName": "github" },
|
||||
{ "serverCommand": ["npx", "-y", "approved-package"] }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Result**:
|
||||
|
||||
- Stdio server named “local-tool” with `["npx", "-y", "approved-package"]`: ✅ Allowed (matches command)
|
||||
- Stdio server named “local-tool” with `["node", "server.js"]`: ❌ Blocked (command entries exist but doesn’t match)
|
||||
- Stdio server named “github” with `["node", "server.js"]`: ❌ Blocked (stdio servers must match commands when command entries exist)
|
||||
- HTTP server named “github”: ✅ Allowed (matches name)
|
||||
- HTTP server named “other-api”: ❌ Blocked (name doesn’t match)
|
||||
|
||||
Example: Name-only allowlist
|
||||
|
||||
```bash
|
||||
{
|
||||
"allowedMcpServers": [
|
||||
{ "serverName": "github" },
|
||||
{ "serverName": "internal-tool" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Result**:
|
||||
|
||||
- Stdio server named “github” with any command: ✅ Allowed (no command restrictions)
|
||||
- Stdio server named “internal-tool” with any command: ✅ Allowed (no command restrictions)
|
||||
- HTTP server named “github”: ✅ Allowed (matches name)
|
||||
- Any server named “other”: ❌ Blocked (name doesn’t match)
|
||||
|
||||
#### [](#allowlist-behavior-allowedmcpservers) Allowlist behavior (`allowedMcpServers`)
|
||||
|
||||
- `undefined` (default): No restrictions - users can configure any MCP server
|
||||
- Empty array `[]`: Complete lockdown - users cannot configure any MCP servers
|
||||
- List of entries: Users can only configure servers that match by name, command, or URL pattern
|
||||
|
||||
#### [](#denylist-behavior-deniedmcpservers) Denylist behavior (`deniedMcpServers`)
|
||||
|
||||
- `undefined` (default): No servers are blocked
|
||||
- Empty array `[]`: No servers are blocked
|
||||
- List of entries: Specified servers are explicitly blocked across all scopes
|
||||
|
||||
#### [](#important-notes) Important notes
|
||||
|
||||
- **Option 1 and Option 2 can be combined**: If `managed-mcp.json` exists, it has exclusive control and users cannot add servers. Allowlists/denylists still apply to the managed servers themselves.
|
||||
- **Denylist takes absolute precedence**: If a server matches a denylist entry (by name, command, or URL), it will be blocked even if it’s on the allowlist
|
||||
- Name-based, command-based, and URL-based restrictions work together: a server passes if it matches **either** a name entry, a command entry, or a URL pattern (unless blocked by denylist)
|
||||
|
||||
**When using `managed-mcp.json`**: Users cannot add MCP servers through `claude mcp add` or configuration files. The `allowedMcpServers` and `deniedMcpServers` settings still apply to filter which managed servers are actually loaded.
|
||||
@@ -0,0 +1,212 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/memory
|
||||
title: Manage Claude's memory
|
||||
---
|
||||
|
||||
Claude Code can remember your preferences across sessions, like style guidelines and common commands in your workflow.
|
||||
|
||||
## [](#determine-memory-type) 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` • Linux: `/etc/claude-code/CLAUDE.md` • Windows: `C:\Program Files\ClaudeCode\CLAUDE.md` | Organization-wide instructions managed by IT/DevOps | Company coding standards, security policies, compliance requirements | All users in organization |
|
||||
| **Project memory** | `./CLAUDE.md` or `./.claude/CLAUDE.md` | Team-shared instructions for the project | Project architecture, coding standards, common workflows | Team members via source control |
|
||||
| **Project rules** | `./.claude/rules/*.md` | Modular, topic-specific project instructions | Language-specific guidelines, testing conventions, API standards | Team members via source control |
|
||||
| **User memory** | `~/.claude/CLAUDE.md` | Personal preferences for all projects | Code styling preferences, personal tooling shortcuts | Just you (all projects) |
|
||||
| **Project memory (local)** | `./CLAUDE.local.md` | Personal project-specific preferences | Your sandbox URLs, preferred test data | Just you (current project) |
|
||||
|
||||
All memory files are automatically loaded into Claude Code’s context when launched. Files higher in the hierarchy take precedence and are loaded first, providing a foundation that more specific memories build upon.
|
||||
|
||||
CLAUDE.local.md files are automatically added to .gitignore, making them ideal for private project-specific preferences that shouldn’t be checked into version control.
|
||||
|
||||
## [](#claude-md-imports) CLAUDE.md imports
|
||||
|
||||
CLAUDE.md files can import additional files using `@path/to/import` syntax. The following example imports 3 files:
|
||||
|
||||
```bash
|
||||
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. Imports are an alternative to CLAUDE.local.md that work better across multiple git worktrees.
|
||||
|
||||
```bash
|
||||
# Individual Preferences
|
||||
- @~/.claude/my-project-instructions.md
|
||||
```
|
||||
|
||||
To avoid potential collisions, imports are not evaluated inside markdown code spans and code blocks.
|
||||
|
||||
```bash
|
||||
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) 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.
|
||||
|
||||
## [](#directly-edit-memories-with-/memory) 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) 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:
|
||||
|
||||
```bash
|
||||
> /init
|
||||
```
|
||||
|
||||
Tips:
|
||||
|
||||
- Include frequently used commands (build, test, lint) to avoid repeated searches
|
||||
- Document code style preferences and naming conventions
|
||||
- Add important architectural patterns specific to your project
|
||||
- CLAUDE.md memories can be used for both instructions shared with your team and for your individual preferences.
|
||||
|
||||
## [](#modular-rules-with-claude/rules/) Modular rules with `.claude/rules/`
|
||||
|
||||
For larger projects, you can organize instructions into multiple files using the `.claude/rules/` directory. This allows teams to maintain focused, well-organized rule files instead of one large CLAUDE.md.
|
||||
|
||||
### [](#basic-structure) Basic structure
|
||||
|
||||
Place markdown files in your project’s `.claude/rules/` directory:
|
||||
|
||||
```bash
|
||||
your-project/
|
||||
├── .claude/
|
||||
│ ├── CLAUDE.md # Main project instructions
|
||||
│ └── rules/
|
||||
│ ├── code-style.md # Code style guidelines
|
||||
│ ├── testing.md # Testing conventions
|
||||
│ └── security.md # Security requirements
|
||||
```
|
||||
|
||||
All `.md` files in `.claude/rules/` are automatically loaded as project memory, with the same priority as `.claude/CLAUDE.md`.
|
||||
|
||||
### [](#path-specific-rules) Path-specific rules
|
||||
|
||||
Rules can be scoped to specific files using YAML frontmatter with the `paths` field. These conditional rules only apply when Claude is working with files matching the specified patterns.
|
||||
|
||||
```bash
|
||||
---
|
||||
paths:
|
||||
- "src/api/**/*.ts"
|
||||
---
|
||||
|
||||
# API Development Rules
|
||||
|
||||
- All API endpoints must include input validation
|
||||
- Use the standard error response format
|
||||
- Include OpenAPI documentation comments
|
||||
```
|
||||
|
||||
Rules without a `paths` field are loaded unconditionally and apply to all files.
|
||||
|
||||
### [](#glob-patterns) Glob patterns
|
||||
|
||||
The `paths` field supports standard glob patterns:
|
||||
|
||||
| Pattern | Matches |
|
||||
| --- | --- |
|
||||
| `**/*.ts` | All TypeScript files in any directory |
|
||||
| `src/**/*` | All files under `src/` directory |
|
||||
| `*.md` | Markdown files in the project root |
|
||||
| `src/components/*.tsx` | React components in a specific directory |
|
||||
|
||||
You can specify multiple patterns:
|
||||
|
||||
```bash
|
||||
---
|
||||
paths:
|
||||
- "src/**/*.ts"
|
||||
- "lib/**/*.ts"
|
||||
- "tests/**/*.test.ts"
|
||||
---
|
||||
```
|
||||
|
||||
Brace expansion is supported for matching multiple extensions or directories:
|
||||
|
||||
```bash
|
||||
---
|
||||
paths:
|
||||
- "src/**/*.{ts,tsx}"
|
||||
- "{src,lib}/**/*.ts"
|
||||
---
|
||||
|
||||
# TypeScript/React Rules
|
||||
```
|
||||
|
||||
This expands `src/**/*.{ts,tsx}` to match both `.ts` and `.tsx` files.
|
||||
|
||||
### [](#subdirectories) Subdirectories
|
||||
|
||||
Rules can be organized into subdirectories for better structure:
|
||||
|
||||
```bash
|
||||
.claude/rules/
|
||||
├── frontend/
|
||||
│ ├── react.md
|
||||
│ └── styles.md
|
||||
├── backend/
|
||||
│ ├── api.md
|
||||
│ └── database.md
|
||||
└── general.md
|
||||
```
|
||||
|
||||
All `.md` files are discovered recursively.
|
||||
|
||||
### [](#symlinks) Symlinks
|
||||
|
||||
The `.claude/rules/` directory supports symlinks, allowing you to share common rules across multiple projects:
|
||||
|
||||
```bash
|
||||
# Symlink a shared rules directory
|
||||
ln -s ~/shared-claude-rules .claude/rules/shared
|
||||
|
||||
# Symlink individual rule files
|
||||
ln -s ~/company-standards/security.md .claude/rules/security.md
|
||||
```
|
||||
|
||||
Symlinks are resolved and their contents are loaded normally. Circular symlinks are detected and handled gracefully.
|
||||
|
||||
### [](#user-level-rules) User-level rules
|
||||
|
||||
You can create personal rules that apply to all your projects in `~/.claude/rules/`:
|
||||
|
||||
```bash
|
||||
~/.claude/rules/
|
||||
├── preferences.md # Your personal coding preferences
|
||||
└── workflows.md # Your preferred workflows
|
||||
```
|
||||
|
||||
User-level rules are loaded before project rules, giving project rules higher priority.
|
||||
|
||||
Best practices for `.claude/rules/`:
|
||||
|
||||
- **Keep rules focused**: Each file should cover one topic (e.g., `testing.md`, `api-design.md`)
|
||||
- **Use descriptive filenames**: The filename should indicate what the rules cover
|
||||
- **Use conditional rules sparingly**: Only add `paths` frontmatter when rules truly apply to specific file types
|
||||
- **Organize with subdirectories**: Group related rules (e.g., `frontend/`, `backend/`)
|
||||
|
||||
## [](#organization-level-memory-management) Organization-level memory management
|
||||
|
||||
Organizations can deploy centrally managed CLAUDE.md files that apply to all users.
|
||||
To set up organization-level memory management:
|
||||
|
||||
1. Create the managed memory file at the **Managed policy** location shown in the [memory types table above](#determine-memory-type).
|
||||
2. Deploy via your configuration management system (MDM, Group Policy, Ansible, etc.) to ensure consistent distribution across all developer machines.
|
||||
|
||||
## [](#memory-best-practices) 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.
|
||||
@@ -0,0 +1,102 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/microsoft-foundry
|
||||
title: Claude Code on Microsoft Foundry
|
||||
---
|
||||
|
||||
## [](#prerequisites) Prerequisites
|
||||
|
||||
Before configuring Claude Code with Microsoft Foundry, ensure you have:
|
||||
|
||||
- An Azure subscription with access to Microsoft Foundry
|
||||
- RBAC permissions to create Microsoft Foundry resources and deployments
|
||||
- Azure CLI installed and configured (optional - only needed if you don’t have another mechanism for getting credentials)
|
||||
|
||||
## [](#setup) Setup
|
||||
|
||||
### [](#1-provision-microsoft-foundry-resource) 1. Provision Microsoft Foundry resource
|
||||
|
||||
First, create a Claude resource in Azure:
|
||||
|
||||
1. Navigate to the [Microsoft Foundry portal](https://ai.azure.com/)
|
||||
2. Create a new resource, noting your resource name
|
||||
3. Create deployments for the Claude models:
|
||||
- Claude Opus
|
||||
- Claude Sonnet
|
||||
- Claude Haiku
|
||||
|
||||
### [](#2-configure-azure-credentials) 2. Configure Azure credentials
|
||||
|
||||
Claude Code supports two authentication methods for Microsoft Foundry. Choose the method that best fits your security requirements.
|
||||
**Option A: API key authentication**
|
||||
|
||||
1. Navigate to your resource in the Microsoft Foundry portal
|
||||
2. Go to the **Endpoints and keys** section
|
||||
3. Copy **API Key**
|
||||
4. Set the environment variable:
|
||||
|
||||
```bash
|
||||
export ANTHROPIC_FOUNDRY_API_KEY=your-azure-api-key
|
||||
```
|
||||
|
||||
**Option B: Microsoft Entra ID authentication**
|
||||
When `ANTHROPIC_FOUNDRY_API_KEY` is not set, Claude Code automatically uses the Azure SDK [default credential chain](https://learn.microsoft.com/en-us/azure/developer/javascript/sdk/authentication/credential-chains#defaultazurecredential-overview).
|
||||
This supports a variety of methods for authenticating local and remote workloads.
|
||||
On local environments, you commonly may use the Azure CLI:
|
||||
|
||||
```bash
|
||||
az login
|
||||
```
|
||||
|
||||
When using Microsoft Foundry, the `/login` and `/logout` commands are disabled since authentication is handled through Azure credentials.
|
||||
|
||||
### [](#3-configure-claude-code) 3. Configure Claude Code
|
||||
|
||||
Set the following environment variables to enable Microsoft Foundry. Note that your deployments’ names are set as the model identifiers in Claude Code (may be optional if using suggested deployment names).
|
||||
|
||||
```bash
|
||||
# Enable Microsoft Foundry integration
|
||||
export CLAUDE_CODE_USE_FOUNDRY=1
|
||||
|
||||
# Azure resource name (replace {resource} with your resource name)
|
||||
export ANTHROPIC_FOUNDRY_RESOURCE={resource}
|
||||
# Or provide the full base URL:
|
||||
# export ANTHROPIC_FOUNDRY_BASE_URL=https://{resource}.services.ai.azure.com
|
||||
|
||||
# Set models to your resource's deployment names
|
||||
export ANTHROPIC_DEFAULT_SONNET_MODEL='claude-sonnet-4-5'
|
||||
export ANTHROPIC_DEFAULT_HAIKU_MODEL='claude-haiku-4-5'
|
||||
export ANTHROPIC_DEFAULT_OPUS_MODEL='claude-opus-4-1'
|
||||
```
|
||||
|
||||
For more details on model configuration options, see [Model configuration](/docs/en/model-config).
|
||||
|
||||
## [](#azure-rbac-configuration) Azure RBAC configuration
|
||||
|
||||
The `Azure AI User` and `Cognitive Services User` default roles include all required permissions for invoking Claude models.
|
||||
For more restrictive permissions, create a custom role with the following:
|
||||
|
||||
```bash
|
||||
{
|
||||
"permissions": [
|
||||
{
|
||||
"dataActions": [
|
||||
"Microsoft.CognitiveServices/accounts/providers/*"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
For details, see [Microsoft Foundry RBAC documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/concepts/rbac-azure-ai-foundry).
|
||||
|
||||
## [](#troubleshooting) Troubleshooting
|
||||
|
||||
If you receive an error “Failed to get token from azureADTokenProvider: ChainedTokenCredential authentication failed”:
|
||||
|
||||
- Configure Entra ID on the environment, or set `ANTHROPIC_FOUNDRY_API_KEY`.
|
||||
|
||||
## [](#additional-resources) Additional resources
|
||||
|
||||
- [Microsoft Foundry documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/what-is-azure-ai-foundry)
|
||||
- [Microsoft Foundry models](https://ai.azure.com/explore/models)
|
||||
- [Microsoft Foundry pricing](https://azure.microsoft.com/en-us/pricing/details/ai-foundry/)
|
||||
@@ -0,0 +1,129 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/model-config
|
||||
title: Model configuration
|
||||
---
|
||||
|
||||
## [](#available-models) Available models
|
||||
|
||||
For the `model` setting in Claude Code, you can configure either:
|
||||
|
||||
- A **model alias**
|
||||
- A **model name**
|
||||
- Anthropic API: A full **[model name](https://docs.claude.com/en/docs/about-claude/models/overview#model-names)**
|
||||
- Bedrock: an inference profile ARN
|
||||
- Foundry: a deployment name
|
||||
- Vertex: a version name
|
||||
|
||||
### [](#model-aliases) Model aliases
|
||||
|
||||
Model aliases provide a convenient way to select model settings without
|
||||
remembering exact version numbers:
|
||||
|
||||
| Model alias | Behavior |
|
||||
| --- | --- |
|
||||
| **`default`** | Recommended model setting, depending on your account type |
|
||||
| **`sonnet`** | Uses the latest Sonnet model (currently Sonnet 4.5) for daily coding tasks |
|
||||
| **`opus`** | Uses Opus model (currently Opus 4.5) for specialized complex reasoning tasks |
|
||||
| **`haiku`** | Uses the fast and efficient Haiku model for simple tasks |
|
||||
| **`sonnet[1m]`** | Uses Sonnet with a [1 million token context window](https://docs.claude.com/en/docs/build-with-claude/context-windows#1m-token-context-window) window for long sessions |
|
||||
| **`opusplan`** | Special mode that uses `opus` during plan mode, then switches to `sonnet` for execution |
|
||||
|
||||
### [](#setting-your-model) 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
|
||||
# Start with Opus
|
||||
claude --model opus
|
||||
|
||||
# Switch to Sonnet during session
|
||||
/model sonnet
|
||||
```
|
||||
|
||||
Example settings file:
|
||||
|
||||
```bash
|
||||
{
|
||||
"permissions": {
|
||||
...
|
||||
},
|
||||
"model": "opus"
|
||||
}
|
||||
```
|
||||
|
||||
## [](#special-model-behavior) Special model behavior
|
||||
|
||||
### [](#default-model-setting) `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) `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]) Extended context with [1m]
|
||||
|
||||
For Console/API users, the `[1m]` suffix can be added to full model names to
|
||||
enable a
|
||||
[1 million token context window](https://docs.claude.com/en/docs/build-with-claude/context-windows#1m-token-context-window).
|
||||
|
||||
```bash
|
||||
# Example of using a full model name with the [1m] suffix
|
||||
/model anthropic.claude-sonnet-4-5-20250929-v1:0[1m]
|
||||
```
|
||||
|
||||
Note: Extended context models have
|
||||
[different pricing](https://docs.claude.com/en/docs/about-claude/pricing#long-context-pricing).
|
||||
|
||||
## [](#checking-your-current-model) Checking your current model
|
||||
|
||||
You can see which model you’re currently using in several ways:
|
||||
|
||||
1. In [status line](/docs/en/statusline) (if configured)
|
||||
2. In `/status`, which also displays your account information.
|
||||
|
||||
## [](#environment-variables) Environment variables
|
||||
|
||||
You can use the following environment variables, which must be full **model
|
||||
names** (or equivalent for your API provider), to control the model names that the aliases map to.
|
||||
|
||||
| Environment variable | Description |
|
||||
| --- | --- |
|
||||
| `ANTHROPIC_DEFAULT_OPUS_MODEL` | The model to use for `opus`, or for `opusplan` when Plan Mode is active. |
|
||||
| `ANTHROPIC_DEFAULT_SONNET_MODEL` | The model to use for `sonnet`, or for `opusplan` when Plan Mode is not active. |
|
||||
| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | The model to use for `haiku`, or [background functionality](/docs/en/costs#background-token-usage) |
|
||||
| `CLAUDE_CODE_SUBAGENT_MODEL` | The model to use for [subagents](/docs/en/sub-agents) |
|
||||
|
||||
Note: `ANTHROPIC_SMALL_FAST_MODEL` is deprecated in favor of
|
||||
`ANTHROPIC_DEFAULT_HAIKU_MODEL`.
|
||||
|
||||
### [](#prompt-caching-configuration) Prompt caching configuration
|
||||
|
||||
Claude Code automatically uses [prompt caching](https://docs.claude.com/en/docs/build-with-claude/prompt-caching) to optimize performance and reduce costs. You can disable prompt caching globally or for specific model tiers:
|
||||
|
||||
| Environment variable | Description |
|
||||
| --- | --- |
|
||||
| `DISABLE_PROMPT_CACHING` | Set to `1` to disable prompt caching for all models (takes precedence over per-model settings) |
|
||||
| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models only |
|
||||
| `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models only |
|
||||
| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models only |
|
||||
|
||||
These environment variables give you fine-grained control over prompt caching behavior. The global `DISABLE_PROMPT_CACHING` setting takes precedence over the model-specific settings, allowing you to quickly disable all caching when needed. The per-model settings are useful for selective control, such as when debugging specific models or working with cloud providers that may have different caching implementations.
|
||||
@@ -0,0 +1,466 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/monitoring-usage
|
||||
title: Monitoring
|
||||
---
|
||||
|
||||
Claude Code supports OpenTelemetry (OTel) metrics and events for monitoring and observability.
|
||||
All metrics are time series data exported via OpenTelemetry’s standard metrics protocol, and events are exported via OpenTelemetry’s logs/events protocol. It is the user’s responsibility to ensure their metrics and logs backends are properly configured and that the aggregation granularity meets their monitoring requirements.
|
||||
|
||||
## [](#quick-start) Quick start
|
||||
|
||||
Configure OpenTelemetry using environment variables:
|
||||
|
||||
```bash
|
||||
# 1. Enable telemetry
|
||||
export CLAUDE_CODE_ENABLE_TELEMETRY=1
|
||||
|
||||
# 2. Choose exporters (both are optional - configure only what you need)
|
||||
export OTEL_METRICS_EXPORTER=otlp # Options: otlp, prometheus, console
|
||||
export OTEL_LOGS_EXPORTER=otlp # Options: otlp, console
|
||||
|
||||
# 3. Configure OTLP endpoint (for OTLP exporter)
|
||||
export OTEL_EXPORTER_OTLP_PROTOCOL=grpc
|
||||
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
|
||||
|
||||
# 4. Set authentication (if required)
|
||||
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-token"
|
||||
|
||||
# 5. For debugging: reduce export intervals
|
||||
export OTEL_METRIC_EXPORT_INTERVAL=10000 # 10 seconds (default: 60000ms)
|
||||
export OTEL_LOGS_EXPORT_INTERVAL=5000 # 5 seconds (default: 5000ms)
|
||||
|
||||
# 6. Run Claude Code
|
||||
claude
|
||||
```
|
||||
|
||||
The default export intervals are 60 seconds for metrics and 5 seconds for logs. During setup, you may want to use shorter intervals for debugging purposes. Remember to reset these for production use.
|
||||
|
||||
For full configuration options, see the [OpenTelemetry specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options).
|
||||
|
||||
## [](#administrator-configuration) Administrator configuration
|
||||
|
||||
Administrators can configure OpenTelemetry settings for all users through the [managed settings file](/docs/en/settings#settings-files). This allows for centralized control of telemetry settings across an organization. See the [settings precedence](/docs/en/settings#settings-precedence) for more information about how settings are applied.
|
||||
Example managed settings configuration:
|
||||
|
||||
```bash
|
||||
{
|
||||
"env": {
|
||||
"CLAUDE_CODE_ENABLE_TELEMETRY": "1",
|
||||
"OTEL_METRICS_EXPORTER": "otlp",
|
||||
"OTEL_LOGS_EXPORTER": "otlp",
|
||||
"OTEL_EXPORTER_OTLP_PROTOCOL": "grpc",
|
||||
"OTEL_EXPORTER_OTLP_ENDPOINT": "http://collector.company.com:4317",
|
||||
"OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer company-token"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Managed settings can be distributed via MDM (Mobile Device Management) or other device management solutions. Environment variables defined in the managed settings file have high precedence and cannot be overridden by users.
|
||||
|
||||
## [](#configuration-details) Configuration details
|
||||
|
||||
### [](#common-configuration-variables) Common configuration variables
|
||||
|
||||
| Environment Variable | Description | Example Values |
|
||||
| --- | --- | --- |
|
||||
| `CLAUDE_CODE_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` |
|
||||
| `OTEL_METRICS_EXPORTER` | Metrics exporter type(s) (comma-separated) | `console`, `otlp`, `prometheus` |
|
||||
| `OTEL_LOGS_EXPORTER` | Logs/events exporter type(s) (comma-separated) | `console`, `otlp` |
|
||||
| `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol for OTLP exporter (all signals) | `grpc`, `http/json`, `http/protobuf` |
|
||||
| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP collector endpoint (all signals) | `http://localhost:4317` |
|
||||
| `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | Protocol for metrics (overrides general) | `grpc`, `http/json`, `http/protobuf` |
|
||||
| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | OTLP metrics endpoint (overrides general) | `http://localhost:4318/v1/metrics` |
|
||||
| `OTEL_EXPORTER_OTLP_LOGS_PROTOCOL` | Protocol for logs (overrides general) | `grpc`, `http/json`, `http/protobuf` |
|
||||
| `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | OTLP logs endpoint (overrides general) | `http://localhost:4318/v1/logs` |
|
||||
| `OTEL_EXPORTER_OTLP_HEADERS` | Authentication headers for OTLP | `Authorization=Bearer token` |
|
||||
| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY` | Client key for mTLS authentication | Path to client key file |
|
||||
| `OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE` | Client certificate for mTLS authentication | Path to client cert file |
|
||||
| `OTEL_METRIC_EXPORT_INTERVAL` | Export interval in milliseconds (default: 60000) | `5000`, `60000` |
|
||||
| `OTEL_LOGS_EXPORT_INTERVAL` | Logs export interval in milliseconds (default: 5000) | `1000`, `10000` |
|
||||
| `OTEL_LOG_USER_PROMPTS` | Enable logging of user prompt content (default: disabled) | `1` to enable |
|
||||
| `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` | Interval for refreshing dynamic headers (default: 1740000ms / 29 minutes) | `900000` |
|
||||
|
||||
### [](#metrics-cardinality-control) 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) Dynamic headers
|
||||
|
||||
For enterprise environments that require dynamic authentication, you can configure a script to generate headers dynamically:
|
||||
|
||||
#### [](#settings-configuration) Settings configuration
|
||||
|
||||
Add to your `.claude/settings.json`:
|
||||
|
||||
```bash
|
||||
{
|
||||
"otelHeadersHelper": "/bin/generate_opentelemetry_headers.sh"
|
||||
}
|
||||
```
|
||||
|
||||
#### [](#script-requirements) Script requirements
|
||||
|
||||
The script must output valid JSON with string key-value pairs representing HTTP headers:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# Example: Multiple headers
|
||||
echo "{\"Authorization\": \"Bearer $(get-token.sh)\", \"X-API-Key\": \"$(get-api-key.sh)\"}"
|
||||
```
|
||||
|
||||
#### [](#refresh-behavior) Refresh behavior
|
||||
|
||||
The headers helper script runs at startup and periodically thereafter to support token refresh. By default, the script runs every 29 minutes. Customize the interval with the `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` environment variable.
|
||||
|
||||
### [](#multi-team-organization-support) 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
|
||||
# Add custom attributes for team identification
|
||||
export OTEL_RESOURCE_ATTRIBUTES="department=engineering,team.id=platform,cost_center=eng-123"
|
||||
```
|
||||
|
||||
These custom attributes will be included in all metrics and events, allowing you to:
|
||||
|
||||
- Filter metrics by team or department
|
||||
- Track costs per cost center
|
||||
- Create team-specific dashboards
|
||||
- Set up alerts for specific teams
|
||||
|
||||
**Important formatting requirements for OTEL\_RESOURCE\_ATTRIBUTES:**The `OTEL_RESOURCE_ATTRIBUTES` environment variable follows the [W3C Baggage specification](https://www.w3.org/TR/baggage/), which has strict formatting requirements:
|
||||
|
||||
- **No spaces allowed**: Values cannot contain spaces. For example, `user.organizationName=My Company` is invalid
|
||||
- **Format**: Must be comma-separated key=value pairs: `key1=value1,key2=value2`
|
||||
- **Allowed characters**: Only US-ASCII characters excluding control characters, whitespace, double quotes, commas, semicolons, and backslashes
|
||||
- **Special characters**: Characters outside the allowed range must be percent-encoded
|
||||
|
||||
**Examples:**
|
||||
|
||||
```bash
|
||||
# ❌ Invalid - contains spaces
|
||||
export OTEL_RESOURCE_ATTRIBUTES="org.name=John's Organization"
|
||||
|
||||
# ✅ Valid - use underscores or camelCase instead
|
||||
export OTEL_RESOURCE_ATTRIBUTES="org.name=Johns_Organization"
|
||||
export OTEL_RESOURCE_ATTRIBUTES="org.name=JohnsOrganization"
|
||||
|
||||
# ✅ Valid - percent-encode special characters if needed
|
||||
export OTEL_RESOURCE_ATTRIBUTES="org.name=John%27s%20Organization"
|
||||
```
|
||||
|
||||
Note: wrapping values in quotes doesn’t escape spaces. For example, `org.name="My Company"` results in the literal value `"My Company"` (with quotes included), not `My Company`.
|
||||
|
||||
### [](#example-configurations) Example configurations
|
||||
|
||||
```bash
|
||||
# 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) Available metrics and events
|
||||
|
||||
### [](#standard-attributes) Standard attributes
|
||||
|
||||
All metrics and events share these standard attributes:
|
||||
|
||||
| Attribute | Description | Controlled By |
|
||||
| --- | --- | --- |
|
||||
| `session.id` | Unique session identifier | `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) |
|
||||
| `app.version` | Current Claude Code version | `OTEL_METRICS_INCLUDE_VERSION` (default: false) |
|
||||
| `organization.id` | Organization UUID (when authenticated) | Always included when available |
|
||||
| `user.account_uuid` | Account UUID (when authenticated) | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) |
|
||||
| `terminal.type` | Terminal type (for example, `iTerm.app`, `vscode`, `cursor`, `tmux`) | Always included when detected |
|
||||
|
||||
### [](#metrics) 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) Metric details
|
||||
|
||||
#### [](#session-counter) Session counter
|
||||
|
||||
Incremented at the start of each session.
|
||||
**Attributes**:
|
||||
|
||||
- All [standard attributes](#standard-attributes)
|
||||
|
||||
#### [](#lines-of-code-counter) Lines of code counter
|
||||
|
||||
Incremented when code is added or removed.
|
||||
**Attributes**:
|
||||
|
||||
- All [standard attributes](#standard-attributes)
|
||||
- `type`: (`"added"`, `"removed"`)
|
||||
|
||||
#### [](#pull-request-counter) Pull request counter
|
||||
|
||||
Incremented when creating pull requests via Claude Code.
|
||||
**Attributes**:
|
||||
|
||||
- All [standard attributes](#standard-attributes)
|
||||
|
||||
#### [](#commit-counter) Commit counter
|
||||
|
||||
Incremented when creating git commits via Claude Code.
|
||||
**Attributes**:
|
||||
|
||||
- All [standard attributes](#standard-attributes)
|
||||
|
||||
#### [](#cost-counter) Cost counter
|
||||
|
||||
Incremented after each API request.
|
||||
**Attributes**:
|
||||
|
||||
- All [standard attributes](#standard-attributes)
|
||||
- `model`: Model identifier (for example, “claude-sonnet-4-5-20250929”)
|
||||
|
||||
#### [](#token-counter) Token counter
|
||||
|
||||
Incremented after each API request.
|
||||
**Attributes**:
|
||||
|
||||
- All [standard attributes](#standard-attributes)
|
||||
- `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`)
|
||||
- `model`: Model identifier (for example, “claude-sonnet-4-5-20250929”)
|
||||
|
||||
#### [](#code-edit-tool-decision-counter) Code edit tool decision counter
|
||||
|
||||
Incremented when user accepts or rejects Edit, Write, or NotebookEdit tool usage.
|
||||
**Attributes**:
|
||||
|
||||
- All [standard attributes](#standard-attributes)
|
||||
- `tool`: Tool name (`"Edit"`, `"Write"`, `"NotebookEdit"`)
|
||||
- `decision`: User decision (`"accept"`, `"reject"`)
|
||||
- `language`: Programming language of the edited file (for example, `"TypeScript"`, `"Python"`, `"JavaScript"`, `"Markdown"`). Returns `"unknown"` for unrecognized file extensions.
|
||||
|
||||
#### [](#active-time-counter) 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) Events
|
||||
|
||||
Claude Code exports the following events via OpenTelemetry logs/events (when `OTEL_LOGS_EXPORTER` is configured):
|
||||
|
||||
#### [](#user-prompt-event) User prompt event
|
||||
|
||||
Logged when a user submits a prompt.
|
||||
**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) 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) API request event
|
||||
|
||||
Logged for each API request to Claude.
|
||||
**Event Name**: `claude_code.api_request`
|
||||
**Attributes**:
|
||||
|
||||
- All [standard attributes](#standard-attributes)
|
||||
- `event.name`: `"api_request"`
|
||||
- `event.timestamp`: ISO 8601 timestamp
|
||||
- `model`: Model used (for example, “claude-sonnet-4-5-20250929”)
|
||||
- `cost_usd`: Estimated cost in USD
|
||||
- `duration_ms`: Request duration in milliseconds
|
||||
- `input_tokens`: Number of input tokens
|
||||
- `output_tokens`: Number of output tokens
|
||||
- `cache_read_tokens`: Number of tokens read from cache
|
||||
- `cache_creation_tokens`: Number of tokens used for cache creation
|
||||
|
||||
#### [](#api-error-event) API error event
|
||||
|
||||
Logged when an API request to Claude fails.
|
||||
**Event Name**: `claude_code.api_error`
|
||||
**Attributes**:
|
||||
|
||||
- All [standard attributes](#standard-attributes)
|
||||
- `event.name`: `"api_error"`
|
||||
- `event.timestamp`: ISO 8601 timestamp
|
||||
- `model`: Model used (for example, “claude-sonnet-4-5-20250929”)
|
||||
- `error`: Error message
|
||||
- `status_code`: HTTP status code (if applicable)
|
||||
- `duration_ms`: Request duration in milliseconds
|
||||
- `attempt`: Attempt number (for retried requests)
|
||||
|
||||
#### [](#tool-decision-event) Tool decision event
|
||||
|
||||
Logged when a tool permission decision is made (accept/reject).
|
||||
**Event Name**: `claude_code.tool_decision`
|
||||
**Attributes**:
|
||||
|
||||
- All [standard attributes](#standard-attributes)
|
||||
- `event.name`: `"tool_decision"`
|
||||
- `event.timestamp`: ISO 8601 timestamp
|
||||
- `tool_name`: Name of the tool (for example, “Read”, “Edit”, “Write”, “NotebookEdit”)
|
||||
- `decision`: Either `"accept"` or `"reject"`
|
||||
- `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"`
|
||||
|
||||
## [](#interpreting-metrics-and-events-data) Interpreting metrics and events data
|
||||
|
||||
The metrics exported by Claude Code provide valuable insights into usage patterns and productivity. Here are some common visualizations and analyses you can create:
|
||||
|
||||
### [](#usage-monitoring) Usage monitoring
|
||||
|
||||
| Metric | Analysis Opportunity |
|
||||
| --- | --- |
|
||||
| `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) Cost monitoring
|
||||
|
||||
The `claude_code.cost.usage` metric helps with:
|
||||
|
||||
- Tracking usage trends across teams or individuals
|
||||
- Identifying high-usage sessions for optimization
|
||||
|
||||
Cost metrics are approximations. For official billing data, refer to your API provider (Claude Console, AWS Bedrock, or Google Cloud Vertex).
|
||||
|
||||
### [](#alerting-and-segmentation) 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) 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) Backend considerations
|
||||
|
||||
Your choice of metrics and logs backends determines the types of analyses you can perform:
|
||||
|
||||
### [](#for-metrics) For metrics
|
||||
|
||||
- **Time series databases (for example, Prometheus)**: Rate calculations, aggregated metrics
|
||||
- **Columnar stores (for example, ClickHouse)**: Complex queries, unique user analysis
|
||||
- **Full-featured observability platforms (for example, Honeycomb, Datadog)**: Advanced querying, visualization, alerting
|
||||
|
||||
### [](#for-events/logs) For events/logs
|
||||
|
||||
- **Log aggregation systems (for example, Elasticsearch, Loki)**: Full-text search, log analysis
|
||||
- **Columnar stores (for example, ClickHouse)**: Structured event analysis
|
||||
- **Full-featured observability platforms (for example, Honeycomb, Datadog)**: Correlation between metrics and events
|
||||
|
||||
For organizations requiring Daily/Weekly/Monthly Active User (DAU/WAU/MAU) metrics, consider backends that support efficient unique value queries.
|
||||
|
||||
## [](#service-information) Service information
|
||||
|
||||
All metrics and events are exported with the following resource attributes:
|
||||
|
||||
- `service.name`: `claude-code`
|
||||
- `service.version`: Current Claude Code version
|
||||
- `os.type`: Operating system type (for example, `linux`, `darwin`, `windows`)
|
||||
- `os.version`: Operating system version string
|
||||
- `host.arch`: Host architecture (for example, `amd64`, `arm64`)
|
||||
- `wsl.version`: WSL version number (only present when running on Windows Subsystem for Linux)
|
||||
- Meter Name: `com.anthropic.claude_code`
|
||||
|
||||
## [](#roi-measurement-resources) ROI measurement resources
|
||||
|
||||
For a comprehensive guide on measuring return on investment for Claude Code, including telemetry setup, cost analysis, productivity metrics, and automated reporting, see the [Claude Code ROI Measurement Guide](https://github.com/anthropics/claude-code-monitoring-guide). This repository provides ready-to-use Docker Compose configurations, Prometheus and OpenTelemetry setups, and templates for generating productivity reports integrated with tools like Linear.
|
||||
|
||||
## [](#security/privacy-considerations) Security/privacy considerations
|
||||
|
||||
- Telemetry is opt-in and requires explicit configuration
|
||||
- Sensitive information like API keys or file contents are never included in metrics or events
|
||||
- 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) 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).
|
||||
@@ -0,0 +1,83 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/network-config
|
||||
title: Enterprise network configuration
|
||||
---
|
||||
|
||||
Claude Code supports various enterprise network and security configurations through environment variables. This includes routing traffic through corporate proxy servers, trusting custom Certificate Authorities (CA), and authenticating with mutual Transport Layer Security (mTLS) certificates for enhanced security.
|
||||
|
||||
All environment variables shown on this page can also be configured in [`settings.json`](/docs/en/settings).
|
||||
|
||||
## [](#proxy-configuration) Proxy configuration
|
||||
|
||||
### [](#environment-variables) Environment variables
|
||||
|
||||
Claude Code respects standard proxy environment variables:
|
||||
|
||||
```bash
|
||||
# HTTPS proxy (recommended)
|
||||
export HTTPS_PROXY=https://proxy.example.com:8080
|
||||
|
||||
# HTTP proxy (if HTTPS not available)
|
||||
export HTTP_PROXY=http://proxy.example.com:8080
|
||||
|
||||
# Bypass proxy for specific requests - space-separated format
|
||||
export NO_PROXY="localhost 192.168.1.1 example.com .example.com"
|
||||
# Bypass proxy for specific requests - comma-separated format
|
||||
export NO_PROXY="localhost,192.168.1.1,example.com,.example.com"
|
||||
# Bypass proxy for all requests
|
||||
export NO_PROXY="*"
|
||||
```
|
||||
|
||||
Claude Code does not support SOCKS proxies.
|
||||
|
||||
### [](#basic-authentication) Basic authentication
|
||||
|
||||
If your proxy requires basic authentication, include credentials in the proxy URL:
|
||||
|
||||
```bash
|
||||
export HTTPS_PROXY=http://username:password@proxy.example.com:8080
|
||||
```
|
||||
|
||||
Avoid hardcoding passwords in scripts. Use environment variables or secure credential storage instead.
|
||||
|
||||
For proxies requiring advanced authentication (NTLM, Kerberos, etc.), consider using an LLM Gateway service that supports your authentication method.
|
||||
|
||||
## [](#custom-ca-certificates) 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
|
||||
export NODE_EXTRA_CA_CERTS=/path/to/ca-cert.pem
|
||||
```
|
||||
|
||||
## [](#mtls-authentication) mTLS authentication
|
||||
|
||||
For enterprise environments requiring client certificate authentication:
|
||||
|
||||
```bash
|
||||
# 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) 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) Additional resources
|
||||
|
||||
- [Claude Code settings](/docs/en/settings)
|
||||
- [Environment variables reference](/docs/en/settings#environment-variables)
|
||||
- [Troubleshooting guide](/docs/en/troubleshooting)
|
||||
@@ -0,0 +1,107 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/output-styles
|
||||
title: Output styles
|
||||
---
|
||||
|
||||
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) 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) How output styles work
|
||||
|
||||
Output styles directly modify Claude Code’s system prompt.
|
||||
|
||||
- All output styles exclude instructions for efficient output (such as
|
||||
responding concisely).
|
||||
- Custom output styles exclude instructions for coding (such as verifying code
|
||||
with tests), unless `keep-coding-instructions` is true.
|
||||
- All output styles have their own custom instructions added to the end of the
|
||||
system prompt.
|
||||
- All output styles trigger reminders for Claude to adhere to the output style
|
||||
instructions during the conversation.
|
||||
|
||||
## [](#change-your-output-style) Change your output style
|
||||
|
||||
You can either:
|
||||
|
||||
- Run `/output-style` to access a menu and select your output style (this can
|
||||
also be accessed from the `/config` menu)
|
||||
- Run `/output-style [style]`, such as `/output-style explanatory`, to directly
|
||||
switch to a style
|
||||
|
||||
These changes apply to the [local project level](/docs/en/settings) and are saved in
|
||||
`.claude/settings.local.json`. You can also directly edit the `outputStyle`
|
||||
field in a settings file at a different level.
|
||||
|
||||
## [](#create-a-custom-output-style) Create a custom output style
|
||||
|
||||
Custom output styles are Markdown files with frontmatter and the text that will
|
||||
be added to the system prompt:
|
||||
|
||||
```bash
|
||||
---
|
||||
name: My Custom Style
|
||||
description:
|
||||
A brief description of what this style does, to be displayed to the user
|
||||
---
|
||||
|
||||
# Custom Style Instructions
|
||||
|
||||
You are an interactive CLI tool that helps users with software engineering
|
||||
tasks. [Your custom instructions here...]
|
||||
|
||||
## Specific Behaviors
|
||||
|
||||
[Define how the assistant should behave in this style...]
|
||||
```
|
||||
|
||||
You can save these files at the user level (`~/.claude/output-styles`) or
|
||||
project level (`.claude/output-styles`).
|
||||
|
||||
### [](#frontmatter) Frontmatter
|
||||
|
||||
Output style files support frontmatter, useful for specifying metadata about the
|
||||
command:
|
||||
|
||||
| Frontmatter | Purpose | Default |
|
||||
| --- | --- | --- |
|
||||
| `name` | Name of the output style, if not the file name | Inherits from file name |
|
||||
| `description` | Description of the output style. Used only in the UI of `/output-style` | None |
|
||||
| `keep-coding-instructions` | Whether to keep the parts of Claude Code’s system prompt related to coding. | false |
|
||||
|
||||
## [](#comparisons-to-related-features) Comparisons to related features
|
||||
|
||||
### [](#output-styles-vs-claude-md-vs-—append-system-prompt) Output Styles vs. CLAUDE.md vs. —append-system-prompt
|
||||
|
||||
Output styles completely “turn off” the parts of Claude Code’s default system
|
||||
prompt specific to software engineering. Neither CLAUDE.md nor
|
||||
`--append-system-prompt` edit Claude Code’s default system prompt. CLAUDE.md
|
||||
adds the contents as a user message *following* Claude Code’s default system
|
||||
prompt. `--append-system-prompt` appends the content to the system prompt.
|
||||
|
||||
### [](#output-styles-vs-agents) Output Styles vs. [Agents](/docs/en/sub-agents)
|
||||
|
||||
Output styles directly affect the main agent loop and only affect the system
|
||||
prompt. Agents are invoked to handle specific tasks and can include additional
|
||||
settings like the model to use, the tools they have available, and some context
|
||||
about when to use the agent.
|
||||
|
||||
### [](#output-styles-vs-custom-slash-commands) Output Styles vs. [Custom Slash Commands](/docs/en/slash-commands)
|
||||
|
||||
You can think of output styles as “stored system prompts” and custom slash
|
||||
commands as “stored prompts”.
|
||||
@@ -0,0 +1,106 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/overview
|
||||
title: Claude Code overview
|
||||
---
|
||||
|
||||
## [](#get-started-in-30-seconds) Get started in 30 seconds
|
||||
|
||||
Prerequisites:
|
||||
|
||||
- A [Claude subscription](https://claude.com/pricing) (Pro, Max, Teams, or Enterprise) or [Claude Console](https://console.anthropic.com/) account
|
||||
|
||||
**Install Claude Code:**
|
||||
To install Claude Code, use one of the following methods:
|
||||
|
||||
- Native Install (Recommended)
|
||||
- Homebrew
|
||||
- WinGet
|
||||
|
||||
**macOS, Linux, WSL:**
|
||||
|
||||
```bash
|
||||
curl -fsSL https://claude.ai/install.sh | bash
|
||||
```
|
||||
|
||||
**Windows PowerShell:**
|
||||
|
||||
```bash
|
||||
irm https://claude.ai/install.ps1 | iex
|
||||
```
|
||||
|
||||
**Windows CMD:**
|
||||
|
||||
```bash
|
||||
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
|
||||
```
|
||||
|
||||
Native installations automatically update in the background to keep you on the latest version.
|
||||
|
||||
```bash
|
||||
brew install --cask claude-code
|
||||
```
|
||||
|
||||
Homebrew installations do not auto-update. Run `brew upgrade claude-code` periodically to get the latest features and security fixes.
|
||||
|
||||
```bash
|
||||
winget install Anthropic.ClaudeCode
|
||||
```
|
||||
|
||||
WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.
|
||||
|
||||
**Start using Claude Code:**
|
||||
|
||||
```bash
|
||||
cd your-project
|
||||
claude
|
||||
```
|
||||
|
||||
You’ll be prompted to log in on first use. That’s it! [Continue with Quickstart (5 minutes) →](/docs/en/quickstart)
|
||||
|
||||
See [advanced setup](/docs/en/setup) for installation options, manual updates, or uninstallation instructions. Visit [troubleshooting](/docs/en/troubleshooting) if you hit issues.
|
||||
|
||||
## [](#what-claude-code-does-for-you) 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](/docs/en/mcp) can pull from external data sources like Google Drive, Figma, and Slack.
|
||||
- **Automate tedious tasks**: Fix fiddly lint issues, resolve merge conflicts, and write release notes. Do all this in a single command from your developer machines, or automatically in CI.
|
||||
|
||||
## [](#why-developers-love-claude-code) 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](/docs/en/mcp) lets Claude read your design docs in Google Drive, update your tickets in Jira, or use *your* custom developer tooling.
|
||||
- **Unix philosophy**: Claude Code is composable and scriptable. `tail -f app.log | claude -p "Slack me if you see any anomalies appear in this log stream"` *works*. Your CI can run `claude -p "If there are new text strings, translate them into French and raise a PR for @lang-fr-team to review"`.
|
||||
- **Enterprise-ready**: Use the Claude API, or host on AWS or GCP. Enterprise-grade [security](/docs/en/security), [privacy](/docs/en/data-usage), and [compliance](https://trust.anthropic.com/) is built-in.
|
||||
|
||||
## [](#next-steps) Next steps
|
||||
|
||||
[## Quickstart
|
||||
|
||||
See Claude Code in action with practical examples](/docs/en/quickstart)[## Common workflows
|
||||
|
||||
Step-by-step guides for common workflows](/docs/en/common-workflows)[## Troubleshooting
|
||||
|
||||
Solutions for common issues with Claude Code](/docs/en/troubleshooting)[## IDE setup
|
||||
|
||||
Add Claude Code to your IDE](/docs/en/vs-code)
|
||||
|
||||
## [](#additional-resources) Additional resources
|
||||
|
||||
[## About Claude Code
|
||||
|
||||
Learn more about Claude Code on claude.com](https://claude.com/product/claude-code)[## Build with the Agent SDK
|
||||
|
||||
Create custom AI agents with the Claude Agent SDK](https://docs.claude.com/en/docs/agent-sdk/overview)[## Host on AWS or GCP
|
||||
|
||||
Configure Claude Code with Amazon Bedrock or Google Vertex AI](/docs/en/third-party-integrations)[## Settings
|
||||
|
||||
Customize Claude Code for your workflow](/docs/en/settings)[## Commands
|
||||
|
||||
Learn about CLI commands and controls](/docs/en/cli-reference)[## Reference implementation
|
||||
|
||||
Clone our development container reference implementation](https://github.com/anthropics/claude-code/tree/main/.devcontainer)[## Security
|
||||
|
||||
Discover Claude Code’s safeguards and best practices for safe usage](/docs/en/security)[## Privacy and data usage
|
||||
|
||||
Understand how Claude Code handles your data](/docs/en/data-usage)
|
||||
@@ -0,0 +1,553 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/plugin-marketplaces
|
||||
title: Create and distribute a plugin marketplace
|
||||
---
|
||||
|
||||
A plugin marketplace is a catalog that lets you distribute plugins to others. Marketplaces provide centralized discovery, version tracking, automatic updates, and support for multiple source types (git repositories, local paths, and more). This guide shows you how to create your own marketplace to share plugins with your team or community.
|
||||
Looking to install plugins from an existing marketplace? See [Discover and install prebuilt plugins](/docs/en/discover-plugins).
|
||||
|
||||
## [](#overview) Overview
|
||||
|
||||
Creating and distributing a marketplace involves:
|
||||
|
||||
1. **Creating plugins**: build one or more plugins with commands, agents, hooks, MCP servers, or LSP servers. This guide assumes you already have plugins to distribute; see [Create plugins](/docs/en/plugins) for details on how to create them.
|
||||
2. **Creating a marketplace file**: define a `marketplace.json` that lists your plugins and where to find them (see [Create the marketplace file](#create-the-marketplace-file)).
|
||||
3. **Host the marketplace**: push to GitHub, GitLab, or another git host (see [Host and distribute marketplaces](#host-and-distribute-marketplaces)).
|
||||
4. **Share with users**: users add your marketplace with `/plugin marketplace add` and install individual plugins (see [Discover and install plugins](/docs/en/discover-plugins)).
|
||||
|
||||
Once your marketplace is live, you can update it by pushing changes to your repository. Users refresh their local copy with `/plugin marketplace update`.
|
||||
|
||||
## [](#walkthrough:-create-a-local-marketplace) Walkthrough: create a local marketplace
|
||||
|
||||
This example creates a marketplace with one plugin: a `/review` command for code reviews. You’ll create the directory structure, add a slash command, create the plugin manifest and marketplace catalog, then install and test it.
|
||||
|
||||
1
|
||||
|
||||
Create the directory structure
|
||||
|
||||
```bash
|
||||
mkdir -p my-marketplace/.claude-plugin
|
||||
mkdir -p my-marketplace/plugins/review-plugin/.claude-plugin
|
||||
mkdir -p my-marketplace/plugins/review-plugin/commands
|
||||
```
|
||||
|
||||
2
|
||||
|
||||
Create the plugin command
|
||||
|
||||
Create a Markdown file that defines what the `/review` command does.
|
||||
|
||||
my-marketplace/plugins/review-plugin/commands/review.md
|
||||
|
||||
```bash
|
||||
Review the code I've selected or the recent changes for:
|
||||
- Potential bugs or edge cases
|
||||
- Security concerns
|
||||
- Performance issues
|
||||
- Readability improvements
|
||||
|
||||
Be concise and actionable.
|
||||
```
|
||||
|
||||
3
|
||||
|
||||
Create the plugin manifest
|
||||
|
||||
Create a `plugin.json` file that describes the plugin. The manifest goes in the `.claude-plugin/` directory.
|
||||
|
||||
my-marketplace/plugins/review-plugin/.claude-plugin/plugin.json
|
||||
|
||||
```bash
|
||||
{
|
||||
"name": "review-plugin",
|
||||
"description": "Adds a /review command for quick code reviews",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
```
|
||||
|
||||
4
|
||||
|
||||
Create the marketplace file
|
||||
|
||||
Create the marketplace catalog that lists your plugin.
|
||||
|
||||
my-marketplace/.claude-plugin/marketplace.json
|
||||
|
||||
```bash
|
||||
{
|
||||
"name": "my-plugins",
|
||||
"owner": {
|
||||
"name": "Your Name"
|
||||
},
|
||||
"plugins": [
|
||||
{
|
||||
"name": "review-plugin",
|
||||
"source": "./plugins/review-plugin",
|
||||
"description": "Adds a /review command for quick code reviews"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
5
|
||||
|
||||
Add and install
|
||||
|
||||
Add the marketplace and install the plugin.
|
||||
|
||||
```bash
|
||||
/plugin marketplace add ./my-marketplace
|
||||
/plugin install review-plugin@my-plugins
|
||||
```
|
||||
|
||||
6
|
||||
|
||||
Try it out
|
||||
|
||||
Select some code in your editor and run your new command.
|
||||
|
||||
```bash
|
||||
/review
|
||||
```
|
||||
|
||||
To learn more about what plugins can do, including hooks, agents, MCP servers, and LSP servers, see [Plugins](/docs/en/plugins).
|
||||
|
||||
**How plugins are installed**: When users install a plugin, Claude Code copies the plugin directory to a cache location. This means plugins can’t reference files outside their directory using paths like `../shared-utils`, because those files won’t be copied.If you need to share files across plugins, use symlinks (which are followed during copying) or restructure your marketplace so the shared directory is inside the plugin source path. See [Plugin caching and file resolution](/docs/en/plugins-reference#plugin-caching-and-file-resolution) for details.
|
||||
|
||||
## [](#create-the-marketplace-file) Create the marketplace file
|
||||
|
||||
Create `.claude-plugin/marketplace.json` in your repository root. This file defines your marketplace’s name, owner information, and a list of plugins with their sources.
|
||||
Each plugin entry needs at minimum a `name` and `source` (where to fetch it from). See the [full schema](#marketplace-schema) below for all available fields.
|
||||
|
||||
```bash
|
||||
{
|
||||
"name": "company-tools",
|
||||
"owner": {
|
||||
"name": "DevTools Team",
|
||||
"email": "[email protected]"
|
||||
},
|
||||
"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) Marketplace schema
|
||||
|
||||
### [](#required-fields) Required fields
|
||||
|
||||
| Field | Type | Description | Example |
|
||||
| --- | --- | --- | --- |
|
||||
| `name` | string | Marketplace identifier (kebab-case, no spaces). This is public-facing: users see it when installing plugins (for example, `/plugin install my-tool@your-marketplace`). | `"acme-tools"` |
|
||||
| `owner` | object | Marketplace maintainer information ([see fields below](#owner-fields)) | |
|
||||
| `plugins` | array | List of available plugins | See below |
|
||||
|
||||
**Reserved names**: The following marketplace names are reserved for official Anthropic use and cannot be used by third-party marketplaces: `claude-code-marketplace`, `claude-code-plugins`, `claude-plugins-official`, `anthropic-marketplace`, `anthropic-plugins`, `agent-skills`, `life-sciences`. Names that impersonate official marketplaces (like `official-claude-plugins` or `anthropic-tools-v2`) are also blocked.
|
||||
|
||||
### [](#owner-fields) Owner fields
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `name` | string | Yes | Name of the maintainer or team |
|
||||
| `email` | string | No | Contact email for the maintainer |
|
||||
|
||||
### [](#optional-metadata) Optional metadata
|
||||
|
||||
| Field | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| `metadata.description` | string | Brief marketplace description |
|
||||
| `metadata.version` | string | Marketplace version |
|
||||
| `metadata.pluginRoot` | string | Base directory prepended to relative plugin source paths (for example, `"./plugins"` lets you write `"source": "formatter"` instead of `"source": "./plugins/formatter"`) |
|
||||
|
||||
## [](#plugin-entries) Plugin entries
|
||||
|
||||
Each plugin entry in the `plugins` array describes a plugin and where to find it. You can include any field from the [plugin manifest schema](/docs/en/plugins-reference#plugin-manifest-schema) (like `description`, `version`, `author`, `commands`, `hooks`, etc.), plus these marketplace-specific fields: `source`, `category`, `tags`, and `strict`.
|
||||
|
||||
### [](#required-fields-2) Required fields
|
||||
|
||||
| Field | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| `name` | string | Plugin identifier (kebab-case, no spaces). This is public-facing: users see it when installing (for example, `/plugin install my-plugin@marketplace`). |
|
||||
| `source` | string|object | Where to fetch the plugin from (see [Plugin sources](#plugin-sources) below) |
|
||||
|
||||
### [](#optional-plugin-fields) Optional plugin fields
|
||||
|
||||
**Standard metadata fields:**
|
||||
|
||||
| Field | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| `description` | string | Brief plugin description |
|
||||
| `version` | string | Plugin version |
|
||||
| `author` | object | Plugin author information (`name` required, `email` optional) |
|
||||
| `homepage` | string | Plugin homepage or documentation URL |
|
||||
| `repository` | string | Source code repository URL |
|
||||
| `license` | string | SPDX license identifier (for example, MIT, Apache-2.0) |
|
||||
| `keywords` | array | Tags for plugin discovery and categorization |
|
||||
| `category` | string | Plugin category for organization |
|
||||
| `tags` | array | Tags for searchability |
|
||||
| `strict` | boolean | Controls whether plugins need their own `plugin.json` file. When `true` (default), the plugin source must contain a `plugin.json`, and any fields you add here in the marketplace entry get merged with it. When `false`, the plugin doesn’t need its own `plugin.json`; the marketplace entry itself defines everything about the plugin. Use `false` when you want to define simple plugins entirely in your marketplace file. |
|
||||
|
||||
**Component configuration fields:**
|
||||
|
||||
| Field | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| `commands` | string|array | Custom paths to command files or directories |
|
||||
| `agents` | string|array | Custom paths to agent files |
|
||||
| `hooks` | string|object | Custom hooks configuration or path to hooks file |
|
||||
| `mcpServers` | string|object | MCP server configurations or path to MCP config |
|
||||
| `lspServers` | string|object | LSP server configurations or path to LSP config |
|
||||
|
||||
## [](#plugin-sources) Plugin sources
|
||||
|
||||
### [](#relative-paths) Relative paths
|
||||
|
||||
For plugins in the same repository:
|
||||
|
||||
```bash
|
||||
{
|
||||
"name": "my-plugin",
|
||||
"source": "./plugins/my-plugin"
|
||||
}
|
||||
```
|
||||
|
||||
Relative paths only work when users add your marketplace via Git (GitHub, GitLab, or git URL). If users add your marketplace via a direct URL to the `marketplace.json` file, relative paths will not resolve correctly. For URL-based distribution, use GitHub, npm, or git URL sources instead. See [Troubleshooting](#plugins-with-relative-paths-fail-in-url-based-marketplaces) for details.
|
||||
|
||||
### [](#github-repositories) GitHub repositories
|
||||
|
||||
```bash
|
||||
{
|
||||
"name": "github-plugin",
|
||||
"source": {
|
||||
"source": "github",
|
||||
"repo": "owner/plugin-repo"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### [](#git-repositories) Git repositories
|
||||
|
||||
```bash
|
||||
{
|
||||
"name": "git-plugin",
|
||||
"source": {
|
||||
"source": "url",
|
||||
"url": "https://gitlab.com/team/plugin.git"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### [](#advanced-plugin-entries) Advanced plugin entries
|
||||
|
||||
This example shows a plugin entry using many of the optional fields, including custom paths for commands, agents, hooks, and MCP servers:
|
||||
|
||||
```bash
|
||||
{
|
||||
"name": "enterprise-tools",
|
||||
"source": {
|
||||
"source": "github",
|
||||
"repo": "company/enterprise-plugin"
|
||||
},
|
||||
"description": "Enterprise workflow automation tools",
|
||||
"version": "2.1.0",
|
||||
"author": {
|
||||
"name": "Enterprise Team",
|
||||
"email": "[email protected]"
|
||||
},
|
||||
"homepage": "https://docs.example.com/plugins/enterprise-tools",
|
||||
"repository": "https://github.com/company/enterprise-plugin",
|
||||
"license": "MIT",
|
||||
"keywords": ["enterprise", "workflow", "automation"],
|
||||
"category": "productivity",
|
||||
"commands": [
|
||||
"./commands/core/",
|
||||
"./commands/enterprise/",
|
||||
"./commands/experimental/preview.md"
|
||||
],
|
||||
"agents": ["./agents/security-reviewer.md", "./agents/compliance-checker.md"],
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write|Edit",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"mcpServers": {
|
||||
"enterprise-db": {
|
||||
"command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server",
|
||||
"args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"]
|
||||
}
|
||||
},
|
||||
"strict": false
|
||||
}
|
||||
```
|
||||
|
||||
Key things to notice:
|
||||
|
||||
- **`commands` and `agents`**: You can specify multiple directories or individual files. Paths are relative to the plugin root.
|
||||
- **`${CLAUDE_PLUGIN_ROOT}`**: Use this variable in hooks and MCP server configs to reference files within the plugin’s installation directory. This is necessary because plugins are copied to a cache location when installed.
|
||||
- **`strict: false`**: Since this is set to false, the plugin doesn’t need its own `plugin.json`. The marketplace entry defines everything.
|
||||
|
||||
## [](#host-and-distribute-marketplaces) Host and distribute marketplaces
|
||||
|
||||
### [](#host-on-github-recommended) Host on GitHub (recommended)
|
||||
|
||||
GitHub provides the easiest distribution method:
|
||||
|
||||
1. **Create a repository**: Set up a new repository for your marketplace
|
||||
2. **Add marketplace file**: Create `.claude-plugin/marketplace.json` with your plugin definitions
|
||||
3. **Share with teams**: Users add your marketplace with `/plugin marketplace add owner/repo`
|
||||
|
||||
**Benefits**: Built-in version control, issue tracking, and team collaboration features.
|
||||
|
||||
### [](#host-on-other-git-services) Host on other git services
|
||||
|
||||
Any git hosting service works, such as GitLab, Bitbucket, and self-hosted servers. Users add with the full repository URL:
|
||||
|
||||
```bash
|
||||
/plugin marketplace add https://gitlab.com/company/plugins.git
|
||||
```
|
||||
|
||||
### [](#private-repositories) Private repositories
|
||||
|
||||
Claude Code supports installing plugins from private repositories. Set the appropriate authentication token in your environment, and Claude Code will use it when authentication is required.
|
||||
|
||||
| Provider | Environment variables | Notes |
|
||||
| --- | --- | --- |
|
||||
| GitHub | `GITHUB_TOKEN` or `GH_TOKEN` | Personal access token or GitHub App token |
|
||||
| GitLab | `GITLAB_TOKEN` or `GL_TOKEN` | Personal access token or project token |
|
||||
| Bitbucket | `BITBUCKET_TOKEN` | App password or repository access token |
|
||||
|
||||
Set the token in your shell configuration (for example, `.bashrc`, `.zshrc`) or pass it when running Claude Code:
|
||||
|
||||
```bash
|
||||
export GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx
|
||||
```
|
||||
|
||||
Authentication tokens are only used when a repository requires authentication. Public repositories work without any tokens configured, even if tokens are present in your environment.
|
||||
|
||||
For CI/CD environments, configure the token as a secret environment variable. GitHub Actions automatically provides `GITHUB_TOKEN` for repositories in the same organization.
|
||||
|
||||
### [](#test-locally-before-distribution) Test locally before distribution
|
||||
|
||||
Test your marketplace locally before sharing:
|
||||
|
||||
```bash
|
||||
/plugin marketplace add ./my-local-marketplace
|
||||
/plugin install test-plugin@my-local-marketplace
|
||||
```
|
||||
|
||||
For the full range of add commands (GitHub, Git URLs, local paths, remote URLs), see [Add marketplaces](/docs/en/discover-plugins#add-marketplaces).
|
||||
|
||||
### [](#require-marketplaces-for-your-team) Require marketplaces for your team
|
||||
|
||||
You can configure your repository so team members are automatically prompted to install your marketplace when they trust the project folder. Add your marketplace to `.claude/settings.json`:
|
||||
|
||||
```bash
|
||||
{
|
||||
"extraKnownMarketplaces": {
|
||||
"company-tools": {
|
||||
"source": {
|
||||
"source": "github",
|
||||
"repo": "your-org/claude-plugins"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You can also specify which plugins should be enabled by default:
|
||||
|
||||
```bash
|
||||
{
|
||||
"enabledPlugins": {
|
||||
"code-formatter@company-tools": true,
|
||||
"deployment-tools@company-tools": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
For full configuration options, see [Plugin settings](/docs/en/settings#plugin-settings).
|
||||
|
||||
### [](#managed-marketplace-restrictions) Managed marketplace restrictions
|
||||
|
||||
For organizations requiring strict control over plugin sources, administrators can restrict which plugin marketplaces users are allowed to add using the [`strictKnownMarketplaces`](/docs/en/settings#strictknownmarketplaces) setting in managed settings.
|
||||
When `strictKnownMarketplaces` is configured in managed settings, the restriction behavior depends on the value:
|
||||
|
||||
| Value | Behavior |
|
||||
| --- | --- |
|
||||
| Undefined (default) | No restrictions. Users can add any marketplace |
|
||||
| Empty array `[]` | Complete lockdown. Users cannot add any new marketplaces |
|
||||
| List of sources | Users can only add marketplaces that match the allowlist exactly |
|
||||
|
||||
#### [](#common-configurations) Common configurations
|
||||
|
||||
Disable all marketplace additions:
|
||||
|
||||
```bash
|
||||
{
|
||||
"strictKnownMarketplaces": []
|
||||
}
|
||||
```
|
||||
|
||||
Allow specific marketplaces only:
|
||||
|
||||
```bash
|
||||
{
|
||||
"strictKnownMarketplaces": [
|
||||
{
|
||||
"source": "github",
|
||||
"repo": "acme-corp/approved-plugins"
|
||||
},
|
||||
{
|
||||
"source": "github",
|
||||
"repo": "acme-corp/security-tools",
|
||||
"ref": "v2.0"
|
||||
},
|
||||
{
|
||||
"source": "url",
|
||||
"url": "https://plugins.example.com/marketplace.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### [](#how-restrictions-work) How restrictions work
|
||||
|
||||
Restrictions are validated early in the plugin installation process, before any network requests or filesystem operations occur. This prevents unauthorized marketplace access attempts.
|
||||
The allowlist uses exact matching. For a marketplace to be allowed, all specified fields must match exactly:
|
||||
|
||||
- For GitHub sources: `repo` is required, and `ref` or `path` must also match if specified in the allowlist
|
||||
- For URL sources: the full URL must match exactly
|
||||
|
||||
Because `strictKnownMarketplaces` is set in [managed settings](/docs/en/settings#settings-file-locations), individual users and project configurations cannot override these restrictions.
|
||||
For complete configuration details including all supported source types and comparison with `extraKnownMarketplaces`, see the [strictKnownMarketplaces reference](/docs/en/settings#strictknownmarketplaces).
|
||||
|
||||
## [](#validation-and-testing) Validation and testing
|
||||
|
||||
Test your marketplace before sharing.
|
||||
Validate your marketplace JSON syntax:
|
||||
|
||||
```bash
|
||||
claude plugin validate .
|
||||
```
|
||||
|
||||
Or from within Claude Code:
|
||||
|
||||
```bash
|
||||
/plugin validate .
|
||||
```
|
||||
|
||||
Add the marketplace for testing:
|
||||
|
||||
```bash
|
||||
/plugin marketplace add ./path/to/marketplace
|
||||
```
|
||||
|
||||
Install a test plugin to verify everything works:
|
||||
|
||||
```bash
|
||||
/plugin install test-plugin@marketplace-name
|
||||
```
|
||||
|
||||
For complete plugin testing workflows, see [Test your plugins locally](/docs/en/plugins#test-your-plugins-locally). For technical troubleshooting, see [Plugins reference](/docs/en/plugins-reference).
|
||||
|
||||
## [](#troubleshooting) Troubleshooting
|
||||
|
||||
### [](#marketplace-not-loading) Marketplace not loading
|
||||
|
||||
**Symptoms**: Can’t add marketplace or see plugins from it
|
||||
**Solutions**:
|
||||
|
||||
- Verify the marketplace URL is accessible
|
||||
- Check that `.claude-plugin/marketplace.json` exists at the specified path
|
||||
- Ensure JSON syntax is valid using `claude plugin validate` or `/plugin validate`
|
||||
- For private repositories, confirm you have access permissions
|
||||
|
||||
### [](#marketplace-validation-errors) Marketplace validation errors
|
||||
|
||||
Run `claude plugin validate .` or `/plugin validate .` from your marketplace directory to check for issues. Common errors:
|
||||
|
||||
| Error | Cause | Solution |
|
||||
| --- | --- | --- |
|
||||
| `File not found: .claude-plugin/marketplace.json` | Missing manifest | Create `.claude-plugin/marketplace.json` with required fields |
|
||||
| `Invalid JSON syntax: Unexpected token...` | JSON syntax error | Check for missing commas, extra commas, or unquoted strings |
|
||||
| `Duplicate plugin name "x" found in marketplace` | Two plugins share the same name | Give each plugin a unique `name` value |
|
||||
| `plugins[0].source: Path traversal not allowed` | Source path contains `..` | Use paths relative to marketplace root without `..` |
|
||||
|
||||
**Warnings** (non-blocking):
|
||||
|
||||
- `Marketplace has no plugins defined`: add at least one plugin to the `plugins` array
|
||||
- `No marketplace description provided`: add `metadata.description` to help users understand your marketplace
|
||||
- `Plugin "x" uses npm source which is not yet fully implemented`: use `github` or local path sources instead
|
||||
|
||||
### [](#plugin-installation-failures) Plugin installation failures
|
||||
|
||||
**Symptoms**: Marketplace appears but plugin installation fails
|
||||
**Solutions**:
|
||||
|
||||
- Verify plugin source URLs are accessible
|
||||
- Check that plugin directories contain required files
|
||||
- For GitHub sources, ensure repositories are public or you have access
|
||||
- Test plugin sources manually by cloning/downloading
|
||||
|
||||
### [](#private-repository-authentication-fails) Private repository authentication fails
|
||||
|
||||
**Symptoms**: Authentication errors when installing plugins from private repositories, even with tokens configured
|
||||
**Solutions**:
|
||||
|
||||
- Verify your token is set in the current shell session: `echo $GITHUB_TOKEN`
|
||||
- Check that the token has the required permissions (read access to the repository)
|
||||
- For GitHub, ensure the token has the `repo` scope for private repositories
|
||||
- For GitLab, ensure the token has at least `read_repository` scope
|
||||
- Verify the token hasn’t expired
|
||||
- If using multiple git providers, ensure you’ve set the token for the correct provider
|
||||
|
||||
### [](#plugins-with-relative-paths-fail-in-url-based-marketplaces) Plugins with relative paths fail in URL-based marketplaces
|
||||
|
||||
**Symptoms**: Added a marketplace via URL (such as `https://example.com/marketplace.json`), but plugins with relative path sources like `"./plugins/my-plugin"` fail to install with “path not found” errors.
|
||||
**Cause**: URL-based marketplaces only download the `marketplace.json` file itself. They do not download plugin files from the server. Relative paths in the marketplace entry reference files on the remote server that were not downloaded.
|
||||
**Solutions**:
|
||||
|
||||
- **Use external sources**: Change plugin entries to use GitHub, npm, or git URL sources instead of relative paths:
|
||||
|
||||
```bash
|
||||
{ "name": "my-plugin", "source": { "source": "github", "repo": "owner/repo" } }
|
||||
```
|
||||
- **Use a Git-based marketplace**: Host your marketplace in a Git repository and add it with the git URL. Git-based marketplaces clone the entire repository, making relative paths work correctly.
|
||||
|
||||
### [](#files-not-found-after-installation) Files not found after installation
|
||||
|
||||
**Symptoms**: Plugin installs but references to files fail, especially files outside the plugin directory
|
||||
**Cause**: Plugins are copied to a cache directory rather than used in-place. Paths that reference files outside the plugin’s directory (such as `../shared-utils`) won’t work because those files aren’t copied.
|
||||
**Solutions**: See [Plugin caching and file resolution](/docs/en/plugins-reference#plugin-caching-and-file-resolution) for workarounds including symlinks and directory restructuring.
|
||||
For additional debugging tools and common issues, see [Debugging and development tools](/docs/en/plugins-reference#debugging-and-development-tools).
|
||||
|
||||
## [](#see-also) See also
|
||||
|
||||
- [Discover and install prebuilt plugins](/docs/en/discover-plugins) - Installing plugins from existing marketplaces
|
||||
- [Plugins](/docs/en/plugins) - Creating your own plugins
|
||||
- [Plugins reference](/docs/en/plugins-reference) - Complete technical specifications and schemas
|
||||
- [Plugin settings](/docs/en/settings#plugin-settings) - Plugin configuration options
|
||||
- [strictKnownMarketplaces reference](/docs/en/settings#strictknownmarketplaces) - Managed marketplace restrictions
|
||||
@@ -0,0 +1,710 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/plugins-reference
|
||||
title: Plugins reference
|
||||
---
|
||||
|
||||
Looking to install plugins? See [Discover and install plugins](/docs/en/discover-plugins). For creating plugins, see [Plugins](/docs/en/plugins). For distributing plugins, see [Plugin marketplaces](/docs/en/plugin-marketplaces).
|
||||
|
||||
This reference provides complete technical specifications for the Claude Code plugin system, including component schemas, CLI commands, and development tools.
|
||||
|
||||
## [](#plugin-components-reference) Plugin components reference
|
||||
|
||||
This section documents the five types of components that plugins can provide.
|
||||
|
||||
### [](#commands) 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](/docs/en/slash-commands#plugin-commands).
|
||||
|
||||
### [](#agents) 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**:
|
||||
|
||||
```bash
|
||||
---
|
||||
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) 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**:
|
||||
|
||||
```bash
|
||||
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](/docs/en/skills)
|
||||
- [Agent Skills overview](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview#skill-structure)
|
||||
|
||||
### [](#hooks) 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**:
|
||||
|
||||
```bash
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write|Edit",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/format-code.sh"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Available events**:
|
||||
|
||||
- `PreToolUse`: Before Claude uses any tool
|
||||
- `PostToolUse`: After Claude successfully uses any tool
|
||||
- `PostToolUseFailure`: After Claude tool execution fails
|
||||
- `PermissionRequest`: When a permission dialog is shown
|
||||
- `UserPromptSubmit`: When user submits a prompt
|
||||
- `Notification`: When Claude Code sends notifications
|
||||
- `Stop`: When Claude attempts to stop
|
||||
- `SubagentStart`: When a subagent is started
|
||||
- `SubagentStop`: When a subagent attempts to stop
|
||||
- `SessionStart`: At the beginning of sessions
|
||||
- `SessionEnd`: At the end of sessions
|
||||
- `PreCompact`: Before conversation history is compacted
|
||||
|
||||
**Hook types**:
|
||||
|
||||
- `command`: Execute shell commands or scripts
|
||||
- `prompt`: Evaluate a prompt with an LLM (uses `$ARGUMENTS` placeholder for context)
|
||||
- `agent`: Run an agentic verifier with tools for complex verification tasks
|
||||
|
||||
### [](#mcp-servers) 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**:
|
||||
|
||||
```bash
|
||||
{
|
||||
"mcpServers": {
|
||||
"plugin-database": {
|
||||
"command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server",
|
||||
"args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"],
|
||||
"env": {
|
||||
"DB_PATH": "${CLAUDE_PLUGIN_ROOT}/data"
|
||||
}
|
||||
},
|
||||
"plugin-api-client": {
|
||||
"command": "npx",
|
||||
"args": ["@company/mcp-server", "--plugin-mode"],
|
||||
"cwd": "${CLAUDE_PLUGIN_ROOT}"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Integration behavior**:
|
||||
|
||||
- Plugin MCP servers start automatically when the plugin is enabled
|
||||
- Servers appear as standard MCP tools in Claude’s toolkit
|
||||
- Server capabilities integrate seamlessly with Claude’s existing tools
|
||||
- Plugin servers can be configured independently of user MCP servers
|
||||
|
||||
### [](#lsp-servers) LSP servers
|
||||
|
||||
Looking to use LSP plugins? Install them from the official marketplace—search for “lsp” in the `/plugin` Discover tab. This section documents how to create LSP plugins for languages not covered by the official marketplace.
|
||||
|
||||
Plugins can provide [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) (LSP) servers to give Claude real-time code intelligence while working on your codebase.
|
||||
LSP integration provides:
|
||||
|
||||
- **Instant diagnostics**: Claude sees errors and warnings immediately after each edit
|
||||
- **Code navigation**: go to definition, find references, and hover information
|
||||
- **Language awareness**: type information and documentation for code symbols
|
||||
|
||||
**Location**: `.lsp.json` in plugin root, or inline in `plugin.json`
|
||||
**Format**: JSON configuration mapping language server names to their configurations
|
||||
**`.lsp.json` file format**:
|
||||
|
||||
```bash
|
||||
{
|
||||
"go": {
|
||||
"command": "gopls",
|
||||
"args": ["serve"],
|
||||
"extensionToLanguage": {
|
||||
".go": "go"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Inline in `plugin.json`**:
|
||||
|
||||
```bash
|
||||
{
|
||||
"name": "my-plugin",
|
||||
"lspServers": {
|
||||
"go": {
|
||||
"command": "gopls",
|
||||
"args": ["serve"],
|
||||
"extensionToLanguage": {
|
||||
".go": "go"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Required fields:**
|
||||
|
||||
| Field | Description |
|
||||
| --- | --- |
|
||||
| `command` | The LSP binary to execute (must be in PATH) |
|
||||
| `extensionToLanguage` | Maps file extensions to language identifiers |
|
||||
|
||||
**Optional fields:**
|
||||
|
||||
| Field | Description |
|
||||
| --- | --- |
|
||||
| `args` | Command-line arguments for the LSP server |
|
||||
| `transport` | Communication transport: `stdio` (default) or `socket` |
|
||||
| `env` | Environment variables to set when starting the server |
|
||||
| `initializationOptions` | Options passed to the server during initialization |
|
||||
| `settings` | Settings passed via `workspace/didChangeConfiguration` |
|
||||
| `workspaceFolder` | Workspace folder path for the server |
|
||||
| `startupTimeout` | Max time to wait for server startup (milliseconds) |
|
||||
| `shutdownTimeout` | Max time to wait for graceful shutdown (milliseconds) |
|
||||
| `restartOnCrash` | Whether to automatically restart the server if it crashes |
|
||||
| `maxRestarts` | Maximum number of restart attempts before giving up |
|
||||
|
||||
**You must install the language server binary separately.** LSP plugins configure how Claude Code connects to a language server, but they don’t include the server itself. If you see `Executable not found in $PATH` in the `/plugin` Errors tab, install the required binary for your language.
|
||||
|
||||
**Available LSP plugins:**
|
||||
|
||||
| Plugin | Language server | Install command |
|
||||
| --- | --- | --- |
|
||||
| `pyright-lsp` | Pyright (Python) | `pip install pyright` or `npm install -g pyright` |
|
||||
| `typescript-lsp` | TypeScript Language Server | `npm install -g typescript-language-server typescript` |
|
||||
| `rust-lsp` | rust-analyzer | [See rust-analyzer installation](https://rust-analyzer.github.io/manual.html#installation) |
|
||||
|
||||
Install the language server first, then install the plugin from the marketplace.
|
||||
|
||||
---
|
||||
|
||||
## [](#plugin-installation-scopes) Plugin installation scopes
|
||||
|
||||
When you install a plugin, you choose a **scope** that determines where the plugin is available and who else can use it:
|
||||
|
||||
| Scope | Settings file | Use case |
|
||||
| --- | --- | --- |
|
||||
| `user` | `~/.claude/settings.json` | Personal plugins available across all projects (default) |
|
||||
| `project` | `.claude/settings.json` | Team plugins shared via version control |
|
||||
| `local` | `.claude/settings.local.json` | Project-specific plugins, gitignored |
|
||||
| `managed` | `managed-settings.json` | Managed plugins (read-only, update only) |
|
||||
|
||||
Plugins use the same scope system as other Claude Code configurations. For installation instructions and scope flags, see [Install plugins](/docs/en/discover-plugins#install-plugins). For a complete explanation of scopes, see [Configuration scopes](/docs/en/settings#configuration-scopes).
|
||||
|
||||
---
|
||||
|
||||
## [](#plugin-manifest-schema) Plugin manifest schema
|
||||
|
||||
The `plugin.json` file defines your plugin’s metadata and configuration. This section documents all supported fields and options.
|
||||
|
||||
### [](#complete-schema) Complete schema
|
||||
|
||||
```bash
|
||||
{
|
||||
"name": "plugin-name",
|
||||
"version": "1.2.0",
|
||||
"description": "Brief plugin description",
|
||||
"author": {
|
||||
"name": "Author Name",
|
||||
"email": "[email protected]",
|
||||
"url": "https://github.com/author"
|
||||
},
|
||||
"homepage": "https://docs.example.com/plugin",
|
||||
"repository": "https://github.com/author/plugin",
|
||||
"license": "MIT",
|
||||
"keywords": ["keyword1", "keyword2"],
|
||||
"commands": ["./custom/commands/special.md"],
|
||||
"agents": "./custom/agents/",
|
||||
"skills": "./custom/skills/",
|
||||
"hooks": "./config/hooks.json",
|
||||
"mcpServers": "./mcp-config.json",
|
||||
"outputStyles": "./styles/",
|
||||
"lspServers": "./.lsp.json"
|
||||
}
|
||||
```
|
||||
|
||||
### [](#required-fields) Required fields
|
||||
|
||||
| Field | Type | Description | Example |
|
||||
| --- | --- | --- | --- |
|
||||
| `name` | string | Unique identifier (kebab-case, no spaces) | `"deployment-tools"` |
|
||||
|
||||
### [](#metadata-fields) 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": "[email protected]"}` |
|
||||
| `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) Component path fields
|
||||
|
||||
| Field | Type | Description | Example |
|
||||
| --- | --- | --- | --- |
|
||||
| `commands` | string|array | Additional command files/directories | `"./custom/cmd.md"` or `["./cmd1.md"]` |
|
||||
| `agents` | string|array | Additional agent files | `"./custom/agents/"` |
|
||||
| `skills` | string|array | Additional skill directories | `"./custom/skills/"` |
|
||||
| `hooks` | string|object | Hook config path or inline config | `"./hooks.json"` |
|
||||
| `mcpServers` | string|object | MCP config path or inline config | `"./mcp-config.json"` |
|
||||
| `outputStyles` | string|array | Additional output style files/directories | `"./styles/"` |
|
||||
| `lspServers` | string|object | [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) config for code intelligence (go to definition, find references, etc.) | `"./.lsp.json"` |
|
||||
|
||||
### [](#path-behavior-rules) 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**:
|
||||
|
||||
```bash
|
||||
{
|
||||
"commands": [
|
||||
"./specialized/deploy.md",
|
||||
"./utilities/batch-process.md"
|
||||
],
|
||||
"agents": [
|
||||
"./custom-agents/reviewer.md",
|
||||
"./custom-agents/tester.md"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### [](#environment-variables) 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.
|
||||
|
||||
```bash
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/process.sh"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## [](#plugin-caching-and-file-resolution) Plugin caching and file resolution
|
||||
|
||||
For security and verification purposes, Claude Code copies plugins to a cache directory rather than using them in-place. Understanding this behavior is important when developing plugins that reference external files.
|
||||
|
||||
### [](#how-plugin-caching-works) How plugin caching works
|
||||
|
||||
When you install a plugin, Claude Code copies the plugin files to a cache directory:
|
||||
|
||||
- **For marketplace plugins with relative paths**: The path specified in the `source` field is copied recursively. For example, if your marketplace entry specifies `"source": "./plugins/my-plugin"`, the entire `./plugins` directory is copied.
|
||||
- **For plugins with `.claude-plugin/plugin.json`**: The implicit root directory (the directory containing `.claude-plugin/plugin.json`) is copied recursively.
|
||||
|
||||
### [](#path-traversal-limitations) Path traversal limitations
|
||||
|
||||
Plugins cannot reference files outside their copied directory structure. Paths that traverse outside the plugin root (such as `../shared-utils`) will not work after installation because those external files are not copied to the cache.
|
||||
|
||||
### [](#working-with-external-dependencies) Working with external dependencies
|
||||
|
||||
If your plugin needs to access files outside its directory, you have two options:
|
||||
**Option 1: Use symlinks**
|
||||
Create symbolic links to external files within your plugin directory. Symlinks are honored during the copy process:
|
||||
|
||||
```bash
|
||||
# Inside your plugin directory
|
||||
ln -s /path/to/shared-utils ./shared-utils
|
||||
```
|
||||
|
||||
The symlinked content will be copied into the plugin cache.
|
||||
**Option 2: Restructure your marketplace**
|
||||
Set the plugin path to a parent directory that contains all required files, then provide the rest of the plugin manifest directly in the marketplace entry:
|
||||
|
||||
```bash
|
||||
{
|
||||
"name": "my-plugin",
|
||||
"source": "./",
|
||||
"description": "Plugin that needs root-level access",
|
||||
"commands": ["./plugins/my-plugin/commands/"],
|
||||
"agents": ["./plugins/my-plugin/agents/"],
|
||||
"strict": false
|
||||
}
|
||||
```
|
||||
|
||||
This approach copies the entire marketplace root, giving your plugin access to sibling directories.
|
||||
|
||||
Symlinks that point to locations outside the plugin’s logical root are followed during copying. This provides flexibility while maintaining the security benefits of the caching system.
|
||||
|
||||
---
|
||||
|
||||
## [](#plugin-directory-structure) Plugin directory structure
|
||||
|
||||
### [](#standard-plugin-layout) Standard plugin layout
|
||||
|
||||
A complete plugin follows this structure:
|
||||
|
||||
```bash
|
||||
enterprise-plugin/
|
||||
├── .claude-plugin/ # Metadata directory
|
||||
│ └── plugin.json # Required: plugin manifest
|
||||
├── commands/ # Default command location
|
||||
│ ├── status.md
|
||||
│ └── logs.md
|
||||
├── agents/ # Default agent location
|
||||
│ ├── security-reviewer.md
|
||||
│ ├── performance-tester.md
|
||||
│ └── compliance-checker.md
|
||||
├── skills/ # Agent Skills
|
||||
│ ├── code-reviewer/
|
||||
│ │ └── SKILL.md
|
||||
│ └── pdf-processor/
|
||||
│ ├── SKILL.md
|
||||
│ └── scripts/
|
||||
├── hooks/ # Hook configurations
|
||||
│ ├── hooks.json # Main hook config
|
||||
│ └── security-hooks.json # Additional hooks
|
||||
├── .mcp.json # MCP server definitions
|
||||
├── .lsp.json # LSP server configurations
|
||||
├── scripts/ # Hook and utility scripts
|
||||
│ ├── security-scan.sh
|
||||
│ ├── format-code.py
|
||||
│ └── deploy.js
|
||||
├── LICENSE # License file
|
||||
└── CHANGELOG.md # Version history
|
||||
```
|
||||
|
||||
The `.claude-plugin/` directory contains the `plugin.json` file. All other directories (commands/, agents/, skills/, hooks/) must be at the plugin root, not inside `.claude-plugin/`.
|
||||
|
||||
### [](#file-locations-reference) 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 |
|
||||
| **LSP servers** | `.lsp.json` | Language server configurations |
|
||||
|
||||
---
|
||||
|
||||
## [](#cli-commands-reference) CLI commands reference
|
||||
|
||||
Claude Code provides CLI commands for non-interactive plugin management, useful for scripting and automation.
|
||||
|
||||
### [](#plugin-install) plugin install
|
||||
|
||||
Install a plugin from available marketplaces.
|
||||
|
||||
```bash
|
||||
claude plugin install <plugin> [options]
|
||||
```
|
||||
|
||||
**Arguments:**
|
||||
|
||||
- `<plugin>`: Plugin name or `plugin-name@marketplace-name` for a specific marketplace
|
||||
|
||||
**Options:**
|
||||
|
||||
| Option | Description | Default |
|
||||
| --- | --- | --- |
|
||||
| `-s, --scope <scope>` | Installation scope: `user`, `project`, or `local` | `user` |
|
||||
| `-h, --help` | Display help for command | |
|
||||
|
||||
**Examples:**
|
||||
|
||||
```bash
|
||||
# Install to user scope (default)
|
||||
claude plugin install formatter@my-marketplace
|
||||
|
||||
# Install to project scope (shared with team)
|
||||
claude plugin install formatter@my-marketplace --scope project
|
||||
|
||||
# Install to local scope (gitignored)
|
||||
claude plugin install formatter@my-marketplace --scope local
|
||||
```
|
||||
|
||||
### [](#plugin-uninstall) plugin uninstall
|
||||
|
||||
Remove an installed plugin.
|
||||
|
||||
```bash
|
||||
claude plugin uninstall <plugin> [options]
|
||||
```
|
||||
|
||||
**Arguments:**
|
||||
|
||||
- `<plugin>`: Plugin name or `plugin-name@marketplace-name`
|
||||
|
||||
**Options:**
|
||||
|
||||
| Option | Description | Default |
|
||||
| --- | --- | --- |
|
||||
| `-s, --scope <scope>` | Uninstall from scope: `user`, `project`, or `local` | `user` |
|
||||
| `-h, --help` | Display help for command | |
|
||||
|
||||
**Aliases:** `remove`, `rm`
|
||||
|
||||
### [](#plugin-enable) plugin enable
|
||||
|
||||
Enable a disabled plugin.
|
||||
|
||||
```bash
|
||||
claude plugin enable <plugin> [options]
|
||||
```
|
||||
|
||||
**Arguments:**
|
||||
|
||||
- `<plugin>`: Plugin name or `plugin-name@marketplace-name`
|
||||
|
||||
**Options:**
|
||||
|
||||
| Option | Description | Default |
|
||||
| --- | --- | --- |
|
||||
| `-s, --scope <scope>` | Scope to enable: `user`, `project`, or `local` | `user` |
|
||||
| `-h, --help` | Display help for command | |
|
||||
|
||||
### [](#plugin-disable) plugin disable
|
||||
|
||||
Disable a plugin without uninstalling it.
|
||||
|
||||
```bash
|
||||
claude plugin disable <plugin> [options]
|
||||
```
|
||||
|
||||
**Arguments:**
|
||||
|
||||
- `<plugin>`: Plugin name or `plugin-name@marketplace-name`
|
||||
|
||||
**Options:**
|
||||
|
||||
| Option | Description | Default |
|
||||
| --- | --- | --- |
|
||||
| `-s, --scope <scope>` | Scope to disable: `user`, `project`, or `local` | `user` |
|
||||
| `-h, --help` | Display help for command | |
|
||||
|
||||
### [](#plugin-update) plugin update
|
||||
|
||||
Update a plugin to the latest version.
|
||||
|
||||
```bash
|
||||
claude plugin update <plugin> [options]
|
||||
```
|
||||
|
||||
**Arguments:**
|
||||
|
||||
- `<plugin>`: Plugin name or `plugin-name@marketplace-name`
|
||||
|
||||
**Options:**
|
||||
|
||||
| Option | Description | Default |
|
||||
| --- | --- | --- |
|
||||
| `-s, --scope <scope>` | Scope to update: `user`, `project`, `local`, or `managed` | `user` |
|
||||
| `-h, --help` | Display help for command | |
|
||||
|
||||
---
|
||||
|
||||
## [](#debugging-and-development-tools) Debugging and development tools
|
||||
|
||||
### [](#debugging-commands) Debugging commands
|
||||
|
||||
Use `claude --debug` to see plugin loading details:
|
||||
|
||||
```bash
|
||||
claude --debug
|
||||
```
|
||||
|
||||
This shows:
|
||||
|
||||
- Which plugins are being loaded
|
||||
- Any errors in plugin manifests
|
||||
- Command, agent, and hook registration
|
||||
- MCP server initialization
|
||||
|
||||
### [](#common-issues) Common issues
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
| --- | --- | --- |
|
||||
| Plugin not loading | Invalid `plugin.json` | Validate JSON syntax with `claude plugin validate` or `/plugin validate` |
|
||||
| Commands not appearing | Wrong directory structure | Ensure `commands/` at root, not in `.claude-plugin/` |
|
||||
| Hooks not firing | Script not executable | Run `chmod +x script.sh` |
|
||||
| MCP server fails | Missing `${CLAUDE_PLUGIN_ROOT}` | Use variable for all plugin paths |
|
||||
| Path errors | Absolute paths used | All paths must be relative and start with `./` |
|
||||
| LSP `Executable not found in $PATH` | Language server not installed | Install the binary (e.g., `npm install -g typescript-language-server typescript`) |
|
||||
|
||||
### [](#example-error-messages) Example error messages
|
||||
|
||||
**Manifest validation errors**:
|
||||
|
||||
- `Invalid JSON syntax: Unexpected token } in JSON at position 142`: check for missing commas, extra commas, or unquoted strings
|
||||
- `Plugin has an invalid manifest file at .claude-plugin/plugin.json. Validation errors: name: Required`: a required field is missing
|
||||
- `Plugin has a corrupt manifest file at .claude-plugin/plugin.json. JSON parse error: ...`: JSON syntax error
|
||||
|
||||
**Plugin loading errors**:
|
||||
|
||||
- `Warning: No commands found in plugin my-plugin custom directory: ./cmds. Expected .md files or SKILL.md in subdirectories.`: command path exists but contains no valid command files
|
||||
- `Plugin directory not found at path: ./plugins/my-plugin. Check that the marketplace entry has the correct path.`: the `source` path in marketplace.json points to a non-existent directory
|
||||
- `Plugin my-plugin has conflicting manifests: both plugin.json and marketplace entry specify components.`: remove duplicate component definitions or set `strict: true` in marketplace entry
|
||||
|
||||
### [](#hook-troubleshooting) Hook troubleshooting
|
||||
|
||||
**Hook script not executing**:
|
||||
|
||||
1. Check the script is executable: `chmod +x ./scripts/your-script.sh`
|
||||
2. Verify the shebang line: First line should be `#!/bin/bash` or `#!/usr/bin/env bash`
|
||||
3. Check the path uses `${CLAUDE_PLUGIN_ROOT}`: `"command": "${CLAUDE_PLUGIN_ROOT}/scripts/your-script.sh"`
|
||||
4. Test the script manually: `./scripts/your-script.sh`
|
||||
|
||||
**Hook not triggering on expected events**:
|
||||
|
||||
1. Verify the event name is correct (case-sensitive): `PostToolUse`, not `postToolUse`
|
||||
2. Check the matcher pattern matches your tools: `"matcher": "Write|Edit"` for file operations
|
||||
3. Confirm the hook type is valid: `command`, `prompt`, or `agent`
|
||||
|
||||
### [](#mcp-server-troubleshooting) MCP server troubleshooting
|
||||
|
||||
**Server not starting**:
|
||||
|
||||
1. Check the command exists and is executable
|
||||
2. Verify all paths use `${CLAUDE_PLUGIN_ROOT}` variable
|
||||
3. Check the MCP server logs: `claude --debug` shows initialization errors
|
||||
4. Test the server manually outside of Claude Code
|
||||
|
||||
**Server tools not appearing**:
|
||||
|
||||
1. Ensure the server is properly configured in `.mcp.json` or `plugin.json`
|
||||
2. Verify the server implements the MCP protocol correctly
|
||||
3. Check for connection timeouts in debug output
|
||||
|
||||
### [](#directory-structure-mistakes) Directory structure mistakes
|
||||
|
||||
**Symptoms**: Plugin loads but components (commands, agents, hooks) are missing.
|
||||
**Correct structure**: Components must be at the plugin root, not inside `.claude-plugin/`. Only `plugin.json` belongs in `.claude-plugin/`.
|
||||
|
||||
```bash
|
||||
my-plugin/
|
||||
├── .claude-plugin/
|
||||
│ └── plugin.json ← Only manifest here
|
||||
├── commands/ ← At root level
|
||||
├── agents/ ← At root level
|
||||
└── hooks/ ← At root level
|
||||
```
|
||||
|
||||
If your components are inside `.claude-plugin/`, move them to the plugin root.
|
||||
**Debug checklist**:
|
||||
|
||||
1. Run `claude --debug` and look for “loading plugin” messages
|
||||
2. Check that each component directory is listed in the debug output
|
||||
3. Verify file permissions allow reading the plugin files
|
||||
|
||||
---
|
||||
|
||||
## [](#distribution-and-versioning-reference) Distribution and versioning reference
|
||||
|
||||
### [](#version-management) Version management
|
||||
|
||||
Follow semantic versioning for plugin releases:
|
||||
|
||||
```bash
|
||||
{
|
||||
"name": "my-plugin",
|
||||
"version": "2.1.0"
|
||||
}
|
||||
```
|
||||
|
||||
**Version format**: `MAJOR.MINOR.PATCH`
|
||||
|
||||
- **MAJOR**: Breaking changes (incompatible API changes)
|
||||
- **MINOR**: New features (backward-compatible additions)
|
||||
- **PATCH**: Bug fixes (backward-compatible fixes)
|
||||
|
||||
**Best practices**:
|
||||
|
||||
- Start at `1.0.0` for your first stable release
|
||||
- Update the version in `plugin.json` before distributing changes
|
||||
- Document changes in a `CHANGELOG.md` file
|
||||
- Use pre-release versions like `2.0.0-beta.1` for testing
|
||||
|
||||
---
|
||||
|
||||
## [](#see-also) See also
|
||||
|
||||
- [Plugins](/docs/en/plugins) - Tutorials and practical usage
|
||||
- [Plugin marketplaces](/docs/en/plugin-marketplaces) - Creating and managing marketplaces
|
||||
- [Slash commands](/docs/en/slash-commands) - Command development details
|
||||
- [Subagents](/docs/en/sub-agents) - Agent configuration and capabilities
|
||||
- [Agent Skills](/docs/en/skills) - Extend Claude’s capabilities
|
||||
- [Hooks](/docs/en/hooks) - Event handling and automation
|
||||
- [MCP](/docs/en/mcp) - External tool integration
|
||||
- [Settings](/docs/en/settings) - Configuration options for plugins
|
||||
@@ -0,0 +1,404 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/plugins
|
||||
title: Create plugins
|
||||
---
|
||||
|
||||
Plugins let you extend Claude Code with custom functionality that can be shared across projects and teams. This guide covers creating your own plugins with slash commands, agents, Skills, hooks, and MCP servers.
|
||||
Looking to install existing plugins? See [Discover and install plugins](/docs/en/discover-plugins). For complete technical specifications, see [Plugins reference](/docs/en/plugins-reference).
|
||||
|
||||
## [](#when-to-use-plugins-vs-standalone-configuration) When to use plugins vs standalone configuration
|
||||
|
||||
Claude Code supports two ways to add custom slash commands, agents, and hooks:
|
||||
|
||||
| Approach | Slash command names | Best for |
|
||||
| --- | --- | --- |
|
||||
| **Standalone** (`.claude/` directory) | `/hello` | Personal workflows, project-specific customizations, quick experiments |
|
||||
| **Plugins** (directories with `.claude-plugin/plugin.json`) | `/plugin-name:hello` | Sharing with teammates, distributing to community, versioned releases, reusable across projects |
|
||||
|
||||
**Use standalone configuration when**:
|
||||
|
||||
- You’re customizing Claude Code for a single project
|
||||
- The configuration is personal and doesn’t need to be shared
|
||||
- You’re experimenting with slash commands or hooks before packaging them
|
||||
- You want short slash command names like `/hello` or `/review`
|
||||
|
||||
**Use plugins when**:
|
||||
|
||||
- You want to share functionality with your team or community
|
||||
- You need the same slash commands/agents across multiple projects
|
||||
- You want version control and easy updates for your extensions
|
||||
- You’re distributing through a marketplace
|
||||
- You’re okay with namespaced slash commands like `/my-plugin:hello` (namespacing prevents conflicts between plugins)
|
||||
|
||||
Start with standalone configuration in `.claude/` for quick iteration, then [convert to a plugin](#convert-existing-configurations-to-plugins) when you’re ready to share.
|
||||
|
||||
## [](#quickstart) Quickstart
|
||||
|
||||
This quickstart walks you through creating a plugin with a custom slash command. You’ll create a manifest (the configuration file that defines your plugin), add a slash command, and test it locally using the `--plugin-dir` flag.
|
||||
|
||||
### [](#prerequisites) Prerequisites
|
||||
|
||||
- Claude Code [installed and authenticated](/docs/en/quickstart#step-1-install-claude-code)
|
||||
- Claude Code version 1.0.33 or later (run `claude --version` to check)
|
||||
|
||||
If you don’t see the `/plugin` command, update Claude Code to the latest version. See [Troubleshooting](/docs/en/troubleshooting) for upgrade instructions.
|
||||
|
||||
### [](#create-your-first-plugin) Create your first plugin
|
||||
|
||||
1
|
||||
|
||||
Create the plugin directory
|
||||
|
||||
Every plugin lives in its own directory containing a manifest and your custom commands, agents, or hooks. Create one now:
|
||||
|
||||
```bash
|
||||
mkdir my-first-plugin
|
||||
```
|
||||
|
||||
2
|
||||
|
||||
Create the plugin manifest
|
||||
|
||||
The manifest file at `.claude-plugin/plugin.json` defines your plugin’s identity: its name, description, and version. Claude Code uses this metadata to display your plugin in the plugin manager.Create the `.claude-plugin` directory inside your plugin folder:
|
||||
|
||||
```bash
|
||||
mkdir my-first-plugin/.claude-plugin
|
||||
```
|
||||
|
||||
Then create `my-first-plugin/.claude-plugin/plugin.json` with this content:
|
||||
|
||||
my-first-plugin/.claude-plugin/plugin.json
|
||||
|
||||
```bash
|
||||
{
|
||||
"name": "my-first-plugin",
|
||||
"description": "A greeting plugin to learn the basics",
|
||||
"version": "1.0.0",
|
||||
"author": {
|
||||
"name": "Your Name"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Purpose |
|
||||
| --- | --- |
|
||||
| `name` | Unique identifier and slash command namespace. Slash commands are prefixed with this (e.g., `/my-first-plugin:hello`). |
|
||||
| `description` | Shown in the plugin manager when browsing or installing plugins. |
|
||||
| `version` | Track releases using [semantic versioning](/docs/en/plugins-reference#version-management). |
|
||||
| `author` | Optional. Helpful for attribution. |
|
||||
|
||||
For additional fields like `homepage`, `repository`, and `license`, see the [full manifest schema](/docs/en/plugins-reference#plugin-manifest-schema).
|
||||
|
||||
3
|
||||
|
||||
Add a slash command
|
||||
|
||||
Slash commands are Markdown files in the `commands/` directory. The filename becomes the slash command name, prefixed with the plugin’s namespace (`hello.md` in a plugin named `my-first-plugin` creates `/my-first-plugin:hello`). The Markdown content tells Claude how to respond when someone runs the slash command.Create a `commands` directory in your plugin folder:
|
||||
|
||||
```bash
|
||||
mkdir my-first-plugin/commands
|
||||
```
|
||||
|
||||
Then create `my-first-plugin/commands/hello.md` with this content:
|
||||
|
||||
my-first-plugin/commands/hello.md
|
||||
|
||||
```bash
|
||||
---
|
||||
description: Greet the user with a friendly message
|
||||
---
|
||||
|
||||
# Hello Command
|
||||
|
||||
Greet the user warmly and ask how you can help them today.
|
||||
```
|
||||
|
||||
4
|
||||
|
||||
Test your plugin
|
||||
|
||||
Run Claude Code with the `--plugin-dir` flag to load your plugin:
|
||||
|
||||
```bash
|
||||
claude --plugin-dir ./my-first-plugin
|
||||
```
|
||||
|
||||
Once Claude Code starts, try your new command:
|
||||
|
||||
```bash
|
||||
/my-first-plugin:hello
|
||||
```
|
||||
|
||||
You’ll see Claude respond with a greeting. Run `/help` to see your command listed under the plugin namespace.
|
||||
|
||||
**Why namespacing?** Plugin slash commands are always namespaced (like `/greet:hello`) to prevent conflicts when multiple plugins have commands with the same name.To change the namespace prefix, update the `name` field in `plugin.json`.
|
||||
|
||||
5
|
||||
|
||||
Add slash command arguments
|
||||
|
||||
Make your slash command dynamic by accepting user input. The `$ARGUMENTS` placeholder captures any text the user provides after the slash command.Update your `hello.md` file:
|
||||
|
||||
my-first-plugin/commands/hello.md
|
||||
|
||||
```bash
|
||||
---
|
||||
description: Greet the user with a personalized message
|
||||
---
|
||||
|
||||
# Hello Command
|
||||
|
||||
Greet the user named "$ARGUMENTS" warmly and ask how you can help them today. Make the greeting personal and encouraging.
|
||||
```
|
||||
|
||||
Restart Claude Code to pick up the changes, then try the command with your name:
|
||||
|
||||
```bash
|
||||
/my-first-plugin:hello Alex
|
||||
```
|
||||
|
||||
Claude will greet you by name. For more argument options like `$1`, `$2` for individual parameters, see [Slash commands](/docs/en/slash-commands).
|
||||
|
||||
You’ve successfully created and tested a plugin with these key components:
|
||||
|
||||
- **Plugin manifest** (`.claude-plugin/plugin.json`): describes your plugin’s metadata
|
||||
- **Commands directory** (`commands/`): contains your custom slash commands
|
||||
- **Command arguments** (`$ARGUMENTS`): captures user input for dynamic behavior
|
||||
|
||||
The `--plugin-dir` flag is useful for development and testing. When you’re ready to share your plugin with others, see [Create and distribute a plugin marketplace](/docs/en/plugin-marketplaces).
|
||||
|
||||
## [](#plugin-structure-overview) Plugin structure overview
|
||||
|
||||
You’ve created a plugin with a slash command, but plugins can include much more: custom agents, Skills, hooks, MCP servers, and LSP servers.
|
||||
|
||||
**Common mistake**: Don’t put `commands/`, `agents/`, `skills/`, or `hooks/` inside the `.claude-plugin/` directory. Only `plugin.json` goes inside `.claude-plugin/`. All other directories must be at the plugin root level.
|
||||
|
||||
| Directory | Location | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `.claude-plugin/` | Plugin root | Contains only `plugin.json` manifest (required) |
|
||||
| `commands/` | Plugin root | Slash commands as Markdown files |
|
||||
| `agents/` | Plugin root | Custom agent definitions |
|
||||
| `skills/` | Plugin root | Agent Skills with `SKILL.md` files |
|
||||
| `hooks/` | Plugin root | Event handlers in `hooks.json` |
|
||||
| `.mcp.json` | Plugin root | MCP server configurations |
|
||||
| `.lsp.json` | Plugin root | LSP server configurations for code intelligence |
|
||||
|
||||
**Next steps**: Ready to add more features? Jump to [Develop more complex plugins](#develop-more-complex-plugins) to add agents, hooks, MCP servers, and LSP servers. For complete technical specifications of all plugin components, see [Plugins reference](/docs/en/plugins-reference).
|
||||
|
||||
## [](#develop-more-complex-plugins) Develop more complex plugins
|
||||
|
||||
Once you’re comfortable with basic plugins, you can create more sophisticated extensions.
|
||||
|
||||
### [](#add-skills-to-your-plugin) Add Skills to your plugin
|
||||
|
||||
Plugins can include [Agent Skills](/docs/en/skills) to extend Claude’s capabilities. Skills are model-invoked: Claude automatically uses them based on the task context.
|
||||
Add a `skills/` directory at your plugin root with Skill folders containing `SKILL.md` files:
|
||||
|
||||
```bash
|
||||
my-plugin/
|
||||
├── .claude-plugin/
|
||||
│ └── plugin.json
|
||||
└── skills/
|
||||
└── code-review/
|
||||
└── SKILL.md
|
||||
```
|
||||
|
||||
Each `SKILL.md` needs frontmatter with `name` and `description` fields, followed by instructions:
|
||||
|
||||
```bash
|
||||
---
|
||||
name: code-review
|
||||
description: Reviews code for best practices and potential issues. Use when reviewing code, checking PRs, or analyzing code quality.
|
||||
---
|
||||
|
||||
When reviewing code, check for:
|
||||
1. Code organization and structure
|
||||
2. Error handling
|
||||
3. Security concerns
|
||||
4. Test coverage
|
||||
```
|
||||
|
||||
After installing the plugin, restart Claude Code to load the Skills. For complete Skill authoring guidance including progressive disclosure and tool restrictions, see [Agent Skills](/docs/en/skills).
|
||||
|
||||
### [](#add-lsp-servers-to-your-plugin) Add LSP servers to your plugin
|
||||
|
||||
For common languages like TypeScript, Python, and Rust, install the pre-built LSP plugins from the official marketplace. Create custom LSP plugins only when you need support for languages not already covered.
|
||||
|
||||
LSP (Language Server Protocol) plugins give Claude real-time code intelligence. If you need to support a language that doesn’t have an official LSP plugin, you can create your own by adding an `.lsp.json` file to your plugin:
|
||||
|
||||
.lsp.json
|
||||
|
||||
```bash
|
||||
{
|
||||
"go": {
|
||||
"command": "gopls",
|
||||
"args": ["serve"],
|
||||
"extensionToLanguage": {
|
||||
".go": "go"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Users installing your plugin must have the language server binary installed on their machine.
|
||||
For complete LSP configuration options, see [LSP servers](/docs/en/plugins-reference#lsp-servers).
|
||||
|
||||
### [](#organize-complex-plugins) 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](/docs/en/plugins-reference#plugin-directory-structure).
|
||||
|
||||
### [](#test-your-plugins-locally) Test your plugins locally
|
||||
|
||||
Use the `--plugin-dir` flag to test plugins during development. This loads your plugin directly without requiring installation.
|
||||
|
||||
```bash
|
||||
claude --plugin-dir ./my-plugin
|
||||
```
|
||||
|
||||
As you make changes to your plugin, restart Claude Code to pick up the updates. Test your plugin components:
|
||||
|
||||
- Try your commands with `/command-name`
|
||||
- Check that agents appear in `/agents`
|
||||
- Verify hooks work as expected
|
||||
|
||||
You can load multiple plugins at once by specifying the flag multiple times:
|
||||
|
||||
```bash
|
||||
claude --plugin-dir ./plugin-one --plugin-dir ./plugin-two
|
||||
```
|
||||
|
||||
### [](#debug-plugin-issues) 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](/docs/en/plugins-reference#debugging-and-development-tools) for CLI commands and troubleshooting techniques
|
||||
|
||||
### [](#share-your-plugins) 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](/docs/en/plugins-reference#version-management) in your `plugin.json`
|
||||
3. **Create or use a marketplace**: Distribute through [plugin marketplaces](/docs/en/plugin-marketplaces) for installation
|
||||
4. **Test with others**: Have team members test the plugin before wider distribution
|
||||
|
||||
Once your plugin is in a marketplace, others can install it using the instructions in [Discover and install plugins](/docs/en/discover-plugins).
|
||||
|
||||
For complete technical specifications, debugging techniques, and distribution strategies, see [Plugins reference](/docs/en/plugins-reference).
|
||||
|
||||
## [](#convert-existing-configurations-to-plugins) Convert existing configurations to plugins
|
||||
|
||||
If you already have custom commands, Skills, or hooks in your `.claude/` directory, you can convert them into a plugin for easier sharing and distribution.
|
||||
|
||||
### [](#migration-steps) Migration steps
|
||||
|
||||
1
|
||||
|
||||
Create the plugin structure
|
||||
|
||||
Create a new plugin directory:
|
||||
|
||||
```bash
|
||||
mkdir -p my-plugin/.claude-plugin
|
||||
```
|
||||
|
||||
Create the manifest file at `my-plugin/.claude-plugin/plugin.json`:
|
||||
|
||||
my-plugin/.claude-plugin/plugin.json
|
||||
|
||||
```bash
|
||||
{
|
||||
"name": "my-plugin",
|
||||
"description": "Migrated from standalone configuration",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
```
|
||||
|
||||
2
|
||||
|
||||
Copy your existing files
|
||||
|
||||
Copy your existing configurations to the plugin directory:
|
||||
|
||||
```bash
|
||||
# Copy commands
|
||||
cp -r .claude/commands my-plugin/
|
||||
|
||||
# Copy agents (if any)
|
||||
cp -r .claude/agents my-plugin/
|
||||
|
||||
# Copy skills (if any)
|
||||
cp -r .claude/skills my-plugin/
|
||||
```
|
||||
|
||||
3
|
||||
|
||||
Migrate hooks
|
||||
|
||||
If you have hooks in your settings, create a hooks directory:
|
||||
|
||||
```bash
|
||||
mkdir my-plugin/hooks
|
||||
```
|
||||
|
||||
Create `my-plugin/hooks/hooks.json` with your hooks configuration. Copy the `hooks` object from your `.claude/settings.json` or `settings.local.json`—the format is the same:
|
||||
|
||||
my-plugin/hooks/hooks.json
|
||||
|
||||
```bash
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write|Edit",
|
||||
"hooks": [{ "type": "command", "command": "npm run lint:fix $FILE" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
4
|
||||
|
||||
Test your migrated plugin
|
||||
|
||||
Load your plugin to verify everything works:
|
||||
|
||||
```bash
|
||||
claude --plugin-dir ./my-plugin
|
||||
```
|
||||
|
||||
Test each component: run your commands, check agents appear in `/agents`, and verify hooks trigger correctly.
|
||||
|
||||
### [](#what-changes-when-migrating) What changes when migrating
|
||||
|
||||
| Standalone (`.claude/`) | Plugin |
|
||||
| --- | --- |
|
||||
| Only available in one project | Can be shared via marketplaces |
|
||||
| Files in `.claude/commands/` | Files in `plugin-name/commands/` |
|
||||
| Hooks in `settings.json` | Hooks in `hooks/hooks.json` |
|
||||
| Must manually copy to share | Install with `/plugin install` |
|
||||
|
||||
After migrating, you can remove the original files from `.claude/` to avoid duplicates. The plugin version will take precedence when loaded.
|
||||
|
||||
## [](#next-steps) Next steps
|
||||
|
||||
Now that you understand Claude Code’s plugin system, here are suggested paths for different goals:
|
||||
|
||||
### [](#for-plugin-users) For plugin users
|
||||
|
||||
- [Discover and install plugins](/docs/en/discover-plugins): browse marketplaces and install plugins
|
||||
- [Configure team marketplaces](/docs/en/discover-plugins#configure-team-marketplaces): set up repository-level plugins for your team
|
||||
|
||||
### [](#for-plugin-developers) For plugin developers
|
||||
|
||||
- [Create and distribute a marketplace](/docs/en/plugin-marketplaces): package and share your plugins
|
||||
- [Plugins reference](/docs/en/plugins-reference): complete technical specifications
|
||||
- Dive deeper into specific plugin components:
|
||||
- [Slash commands](/docs/en/slash-commands): command development details
|
||||
- [Subagents](/docs/en/sub-agents): agent configuration and capabilities
|
||||
- [Agent Skills](/docs/en/skills): extend Claude’s capabilities
|
||||
- [Hooks](/docs/en/hooks): event handling and automation
|
||||
- [MCP](/docs/en/mcp): external tool integration
|
||||
@@ -0,0 +1,305 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/quickstart
|
||||
title: Quickstart
|
||||
---
|
||||
|
||||
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) Before you begin
|
||||
|
||||
Make sure you have:
|
||||
|
||||
- A terminal or command prompt open
|
||||
- A code project to work with
|
||||
- A [Claude subscription](https://claude.com/pricing) (Pro, Max, Teams, or Enterprise) or [Claude Console](https://console.anthropic.com/) account
|
||||
|
||||
## [](#step-1:-install-claude-code) Step 1: Install Claude Code
|
||||
|
||||
To install Claude Code, use one of the following methods:
|
||||
|
||||
- Native Install (Recommended)
|
||||
- Homebrew
|
||||
- WinGet
|
||||
|
||||
**macOS, Linux, WSL:**
|
||||
|
||||
```bash
|
||||
curl -fsSL https://claude.ai/install.sh | bash
|
||||
```
|
||||
|
||||
**Windows PowerShell:**
|
||||
|
||||
```bash
|
||||
irm https://claude.ai/install.ps1 | iex
|
||||
```
|
||||
|
||||
**Windows CMD:**
|
||||
|
||||
```bash
|
||||
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
|
||||
```
|
||||
|
||||
Native installations automatically update in the background to keep you on the latest version.
|
||||
|
||||
```bash
|
||||
brew install --cask claude-code
|
||||
```
|
||||
|
||||
Homebrew installations do not auto-update. Run `brew upgrade claude-code` periodically to get the latest features and security fixes.
|
||||
|
||||
```bash
|
||||
winget install Anthropic.ClaudeCode
|
||||
```
|
||||
|
||||
WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.
|
||||
|
||||
## [](#step-2:-log-in-to-your-account) 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
|
||||
claude
|
||||
# You'll be prompted to log in on first use
|
||||
```
|
||||
|
||||
```bash
|
||||
/login
|
||||
# Follow the prompts to log in with your account
|
||||
```
|
||||
|
||||
You can log in using any of these account types:
|
||||
|
||||
- [Claude Pro, Max, Teams, or Enterprise](https://claude.com/pricing) (recommended)
|
||||
- [Claude Console](https://console.anthropic.com/) (API access with pre-paid credits)
|
||||
|
||||
Once logged in, your credentials are stored and you won’t need to log in again.
|
||||
|
||||
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 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.
|
||||
|
||||
## [](#step-3:-start-your-first-session) Step 3: Start your first session
|
||||
|
||||
Open your terminal in any project directory and start Claude Code:
|
||||
|
||||
```bash
|
||||
cd /path/to/your/project
|
||||
claude
|
||||
```
|
||||
|
||||
You’ll see the Claude Code welcome screen with your session information, recent conversations, and latest updates. Type `/help` for available commands or `/resume` to continue a previous conversation.
|
||||
|
||||
After logging in (Step 2), your credentials are stored on your system. Learn more in [Credential Management](/docs/en/iam#credential-management).
|
||||
|
||||
## [](#step-4:-ask-your-first-question) Step 4: Ask your first question
|
||||
|
||||
Let’s start with understanding your codebase. Try one of these commands:
|
||||
|
||||
```bash
|
||||
> what does this project do?
|
||||
```
|
||||
|
||||
Claude will analyze your files and provide a summary. You can also ask more specific questions:
|
||||
|
||||
```bash
|
||||
> what technologies does this project use?
|
||||
```
|
||||
|
||||
```bash
|
||||
> where is the main entry point?
|
||||
```
|
||||
|
||||
```bash
|
||||
> explain the folder structure
|
||||
```
|
||||
|
||||
You can also ask Claude about its own capabilities:
|
||||
|
||||
```bash
|
||||
> what can Claude Code do?
|
||||
```
|
||||
|
||||
```bash
|
||||
> how do I use slash commands in Claude Code?
|
||||
```
|
||||
|
||||
```bash
|
||||
> can Claude Code work with Docker?
|
||||
```
|
||||
|
||||
Claude Code reads your files as needed - you don’t have to manually add context. Claude also has access to its own documentation and can answer questions about its features and capabilities.
|
||||
|
||||
## [](#step-5:-make-your-first-code-change) Step 5: Make your first code change
|
||||
|
||||
Now let’s make Claude Code do some actual coding. Try a simple task:
|
||||
|
||||
```bash
|
||||
> add a hello world function to the main file
|
||||
```
|
||||
|
||||
Claude Code will:
|
||||
|
||||
1. Find the appropriate file
|
||||
2. Show you the proposed changes
|
||||
3. Ask for your approval
|
||||
4. Make the edit
|
||||
|
||||
Claude Code always asks for permission before modifying files. You can approve individual changes or enable “Accept all” mode for a session.
|
||||
|
||||
## [](#step-6:-use-git-with-claude-code) Step 6: Use Git with Claude Code
|
||||
|
||||
Claude Code makes Git operations conversational:
|
||||
|
||||
```bash
|
||||
> what files have I changed?
|
||||
```
|
||||
|
||||
```bash
|
||||
> commit my changes with a descriptive message
|
||||
```
|
||||
|
||||
You can also prompt for more complex Git operations:
|
||||
|
||||
```bash
|
||||
> create a new branch called feature/quickstart
|
||||
```
|
||||
|
||||
```bash
|
||||
> show me the last 5 commits
|
||||
```
|
||||
|
||||
```bash
|
||||
> help me resolve merge conflicts
|
||||
```
|
||||
|
||||
## [](#step-7:-fix-a-bug-or-add-a-feature) Step 7: Fix a bug or add a feature
|
||||
|
||||
Claude is proficient at debugging and feature implementation.
|
||||
Describe what you want in natural language:
|
||||
|
||||
```bash
|
||||
> add input validation to the user registration form
|
||||
```
|
||||
|
||||
Or fix existing issues:
|
||||
|
||||
```bash
|
||||
> 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) Step 8: Test out other common workflows
|
||||
|
||||
There are a number of ways to work with Claude:
|
||||
**Refactor code**
|
||||
|
||||
```bash
|
||||
> refactor the authentication module to use async/await instead of callbacks
|
||||
```
|
||||
|
||||
**Write tests**
|
||||
|
||||
```bash
|
||||
> write unit tests for the calculator functions
|
||||
```
|
||||
|
||||
**Update documentation**
|
||||
|
||||
```bash
|
||||
> update the README with installation instructions
|
||||
```
|
||||
|
||||
**Code review**
|
||||
|
||||
```bash
|
||||
> review my changes and suggest improvements
|
||||
```
|
||||
|
||||
**Remember**: Claude Code is your AI pair programmer. Talk to it like you would a helpful colleague - describe what you want to achieve, and it will help you get there.
|
||||
|
||||
## [](#essential-commands) Essential commands
|
||||
|
||||
Here are the most important commands for daily use:
|
||||
|
||||
| Command | What it does | Example |
|
||||
| --- | --- | --- |
|
||||
| `claude` | Start interactive mode | `claude` |
|
||||
| `claude "task"` | Run a one-time task | `claude "fix the build error"` |
|
||||
| `claude -p "query"` | Run one-off query, then exit | `claude -p "explain this function"` |
|
||||
| `claude -c` | Continue most recent conversation in current directory | `claude -c` |
|
||||
| `claude -r` | Resume a previous conversation | `claude -r` |
|
||||
| `claude commit` | Create a Git commit | `claude commit` |
|
||||
| `/clear` | Clear conversation history | `> /clear` |
|
||||
| `/help` | Show available commands | `> /help` |
|
||||
| `exit` or Ctrl+C | Exit Claude Code | `> exit` |
|
||||
|
||||
See the [CLI reference](/docs/en/cli-reference) for a complete list of commands.
|
||||
|
||||
## [](#pro-tips-for-beginners) Pro tips for beginners
|
||||
|
||||
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”
|
||||
|
||||
Use step-by-step instructions
|
||||
|
||||
Break complex tasks into steps:
|
||||
|
||||
```bash
|
||||
> 1. create a new database table for user profiles
|
||||
```
|
||||
|
||||
```bash
|
||||
> 2. create an API endpoint to get and update user profiles
|
||||
```
|
||||
|
||||
```bash
|
||||
> 3. build a webpage that allows users to see and edit their information
|
||||
```
|
||||
|
||||
Let Claude explore first
|
||||
|
||||
Before making changes, let Claude understand your code:
|
||||
|
||||
```bash
|
||||
> analyze the database schema
|
||||
```
|
||||
|
||||
```bash
|
||||
> build a dashboard showing products that are most frequently returned by our UK customers
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
## [](#what’s-next) What’s next?
|
||||
|
||||
Now that you’ve learned the basics, explore more advanced features:
|
||||
|
||||
[## Common workflows
|
||||
|
||||
Step-by-step guides for common tasks](/docs/en/common-workflows)[## CLI reference
|
||||
|
||||
Master all commands and options](/docs/en/cli-reference)[## Configuration
|
||||
|
||||
Customize Claude Code for your workflow](/docs/en/settings)[## Claude Code on the web
|
||||
|
||||
Run tasks asynchronously in the cloud](/docs/en/claude-code-on-the-web)[## About Claude Code
|
||||
|
||||
Learn more on claude.com](https://claude.com/product/claude-code)
|
||||
|
||||
## [](#getting-help) 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
|
||||
@@ -0,0 +1,203 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/sandboxing
|
||||
title: Sandboxing
|
||||
---
|
||||
|
||||
## [](#overview) Overview
|
||||
|
||||
Claude Code features native sandboxing to provide a more secure environment for agent execution while reducing the need for constant permission prompts. Instead of asking permission for each bash command, sandboxing creates defined boundaries upfront where Claude Code can work more freely with reduced risk.
|
||||
The sandboxed bash tool uses OS-level primitives to enforce both filesystem and network isolation.
|
||||
|
||||
## [](#why-sandboxing-matters) Why sandboxing matters
|
||||
|
||||
Traditional permission-based security requires constant user approval for bash commands. While this provides control, it can lead to:
|
||||
|
||||
- **Approval fatigue**: Repeatedly clicking “approve” can cause users to pay less attention to what they’re approving
|
||||
- **Reduced productivity**: Constant interruptions slow down development workflows
|
||||
- **Limited autonomy**: Claude Code cannot work as efficiently when waiting for approvals
|
||||
|
||||
Sandboxing addresses these challenges by:
|
||||
|
||||
1. **Defining clear boundaries**: Specify exactly which directories and network hosts Claude Code can access
|
||||
2. **Reducing permission prompts**: Safe commands within the sandbox don’t require approval
|
||||
3. **Maintaining security**: Attempts to access resources outside the sandbox trigger immediate notifications
|
||||
4. **Enabling autonomy**: Claude Code can run more independently within defined limits
|
||||
|
||||
Effective sandboxing requires **both** filesystem and network isolation. Without network isolation, a compromised agent could exfiltrate sensitive files like SSH keys. Without filesystem isolation, a compromised agent could backdoor system resources to gain network access. When configuring sandboxing it is important to ensure that your configured settings do not create bypasses in these systems.
|
||||
|
||||
## [](#how-it-works) How it works
|
||||
|
||||
### [](#filesystem-isolation) Filesystem isolation
|
||||
|
||||
The sandboxed bash tool restricts file system access to specific directories:
|
||||
|
||||
- **Default writes behavior**: Read and write access to the current working directory and its subdirectories
|
||||
- **Default read behavior**: Read access to the entire computer, except certain denied directories
|
||||
- **Blocked access**: Cannot modify files outside the current working directory without explicit permission
|
||||
- **Configurable**: Define custom allowed and denied paths through settings
|
||||
|
||||
### [](#network-isolation) Network isolation
|
||||
|
||||
Network access is controlled through a proxy server running outside the sandbox:
|
||||
|
||||
- **Domain restrictions**: Only approved domains can be accessed
|
||||
- **User confirmation**: New domain requests trigger permission prompts
|
||||
- **Custom proxy support**: Advanced users can implement custom rules on outgoing traffic
|
||||
- **Comprehensive coverage**: Restrictions apply to all scripts, programs, and subprocesses spawned by commands
|
||||
|
||||
### [](#os-level-enforcement) OS-level enforcement
|
||||
|
||||
The sandboxed bash tool leverages operating system security primitives:
|
||||
|
||||
- **Linux**: Uses [bubblewrap](https://github.com/containers/bubblewrap) for isolation
|
||||
- **macOS**: Uses Seatbelt for sandbox enforcement
|
||||
|
||||
These OS-level restrictions ensure that all child processes spawned by Claude Code’s commands inherit the same security boundaries.
|
||||
|
||||
## [](#getting-started) Getting started
|
||||
|
||||
### [](#enable-sandboxing) Enable sandboxing
|
||||
|
||||
You can enable sandboxing by running the `/sandbox` slash command:
|
||||
|
||||
```bash
|
||||
> /sandbox
|
||||
```
|
||||
|
||||
This opens a menu where you can choose between sandbox modes.
|
||||
|
||||
### [](#sandbox-modes) Sandbox modes
|
||||
|
||||
Claude Code offers two sandbox modes:
|
||||
**Auto-allow mode**: Bash commands will attempt to run inside the sandbox and are automatically allowed without requiring permission. Commands that cannot be sandboxed (such as those needing network access to non-allowed hosts) fall back to the regular permission flow. Explicit ask/deny rules you’ve configured are always respected.
|
||||
**Regular permissions mode**: All bash commands go through the standard permission flow, even when sandboxed. This provides more control but requires more approvals.
|
||||
In both modes, the sandbox enforces the same filesystem and network restrictions. The difference is only in whether sandboxed commands are auto-approved or require explicit permission.
|
||||
|
||||
Auto-allow mode works independently of your permission mode setting. Even if you’re not in “accept edits” mode, sandboxed bash commands will run automatically when auto-allow is enabled. This means bash commands that modify files within the sandbox boundaries will execute without prompting, even when file edit tools would normally require approval.
|
||||
|
||||
### [](#configure-sandboxing) Configure sandboxing
|
||||
|
||||
Customize sandbox behavior through your `settings.json` file. See [Settings](/docs/en/settings#sandbox-settings) for complete configuration reference.
|
||||
|
||||
Not all commands are compatible with sandboxing out of the box. Some notes that may help you make the most out of the sandbox:
|
||||
|
||||
- Many CLI tools require accessing certain hosts. As you use these tools, they will request permission to access certain hosts. Granting permission will allow them to access these hosts now and in the future, enabling them to safely execute inside the sandbox.
|
||||
- `watchman` is incompatible with running in the sandbox. If you’re running `jest`, consider using `jest --no-watchman`
|
||||
- `docker` is incompatible with running in the sandbox. Consider specifying `docker` in `excludedCommands` to force it to run outside of the sandbox.
|
||||
|
||||
Claude Code includes an intentional escape hatch mechanism that allows commands to run outside the sandbox when necessary. When a command fails due to sandbox restrictions (such as network connectivity issues or incompatible tools), Claude is prompted to analyze the failure and may retry the command with the `dangerouslyDisableSandbox` parameter. Commands that use this parameter go through the normal Claude Code permissions flow requiring user permission to execute. This allows Claude Code to handle edge cases where certain tools or network operations cannot function within sandbox constraints.You can disable this escape hatch by setting `"allowUnsandboxedCommands": false` in your [sandbox settings](/docs/en/settings#sandbox-settings). When disabled, the `dangerouslyDisableSandbox` parameter is completely ignored and all commands must run sandboxed or be explicitly listed in `excludedCommands`.
|
||||
|
||||
## [](#security-benefits) Security benefits
|
||||
|
||||
### [](#protection-against-prompt-injection) Protection against prompt injection
|
||||
|
||||
Even if an attacker successfully manipulates Claude Code’s behavior through prompt injection, the sandbox ensures your system remains secure:
|
||||
**Filesystem protection:**
|
||||
|
||||
- Cannot modify critical config files such as `~/.bashrc`
|
||||
- Cannot modify system-level files in `/bin/`
|
||||
- Cannot read files that are denied in your [Claude permission settings](/docs/en/iam#configuring-permissions)
|
||||
|
||||
**Network protection:**
|
||||
|
||||
- Cannot exfiltrate data to attacker-controlled servers
|
||||
- Cannot download malicious scripts from unauthorized domains
|
||||
- Cannot make unexpected API calls to unapproved services
|
||||
- Cannot contact any domains not explicitly allowed
|
||||
|
||||
**Monitoring and control:**
|
||||
|
||||
- All access attempts outside the sandbox are blocked at the OS level
|
||||
- You receive immediate notifications when boundaries are tested
|
||||
- You can choose to deny, allow once, or permanently update your configuration
|
||||
|
||||
### [](#reduced-attack-surface) Reduced attack surface
|
||||
|
||||
Sandboxing limits the potential damage from:
|
||||
|
||||
- **Malicious dependencies**: NPM packages or other dependencies with harmful code
|
||||
- **Compromised scripts**: Build scripts or tools with security vulnerabilities
|
||||
- **Social engineering**: Attacks that trick users into running dangerous commands
|
||||
- **Prompt injection**: Attacks that trick Claude into running dangerous commands
|
||||
|
||||
### [](#transparent-operation) Transparent operation
|
||||
|
||||
When Claude Code attempts to access network resources outside the sandbox:
|
||||
|
||||
1. The operation is blocked at the OS level
|
||||
2. You receive an immediate notification
|
||||
3. You can choose to:
|
||||
- Deny the request
|
||||
- Allow it once
|
||||
- Update your sandbox configuration to permanently allow it
|
||||
|
||||
## [](#security-limitations) Security Limitations
|
||||
|
||||
- Network Sandboxing Limitations: The network filtering system operates by restricting the domains that processes are allowed to connect to. It does not otherwise inspect the traffic passing through the proxy and users are responsible for ensuring they only allow trusted domains in their policy.
|
||||
|
||||
Users should be aware of potential risks that come from allowing broad domains like `github.com` that may allow for data exfiltration. Also, in some cases it may be possible to bypass the network filtering through [domain fronting](https://en.wikipedia.org/wiki/Domain_fronting).
|
||||
|
||||
- Privilege Escalation via Unix Sockets: The `allowUnixSockets` configuration can inadvertently grant access to powerful system services that could lead to sandbox bypasses. For example, if it is used to allow access to `/var/run/docker.sock` this would effectively grant access to the host system through exploiting the docker socket. Users are encouraged to carefully consider any unix sockets that they allow through the sandbox.
|
||||
- Filesystem Permission Escalation: Overly broad filesystem write permissions can enable privilege escalation attacks. Allowing writes to directories containing executables in `$PATH`, system configuration directories, or user shell configuration files (`.bashrc`, `.zshrc`) can lead to code execution in different security contexts when other users or system processes access these files.
|
||||
- Linux Sandbox Strength: The Linux implementation provides strong filesystem and network isolation but includes an `enableWeakerNestedSandbox` mode that enables it to work inside of Docker environments without privileged namespaces. This option considerably weakens security and should only be used in cases where additional isolation is otherwise enforced.
|
||||
|
||||
## [](#advanced-usage) Advanced usage
|
||||
|
||||
### [](#custom-proxy-configuration) Custom proxy configuration
|
||||
|
||||
For organizations requiring advanced network security, you can implement a custom proxy to:
|
||||
|
||||
- Decrypt and inspect HTTPS traffic
|
||||
- Apply custom filtering rules
|
||||
- Log all network requests
|
||||
- Integrate with existing security infrastructure
|
||||
|
||||
```bash
|
||||
{
|
||||
"sandbox": {
|
||||
"network": {
|
||||
"httpProxyPort": 8080,
|
||||
"socksProxyPort": 8081
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### [](#integration-with-existing-security-tools) Integration with existing security tools
|
||||
|
||||
The sandboxed bash tool works alongside:
|
||||
|
||||
- **IAM policies**: Combine with [permission settings](/docs/en/iam) for defense-in-depth
|
||||
- **Development containers**: Use with [devcontainers](/docs/en/devcontainer) for additional isolation
|
||||
- **Enterprise policies**: Enforce sandbox configurations through [managed settings](/docs/en/settings#settings-precedence)
|
||||
|
||||
## [](#best-practices) Best practices
|
||||
|
||||
1. **Start restrictive**: Begin with minimal permissions and expand as needed
|
||||
2. **Monitor logs**: Review sandbox violation attempts to understand Claude Code’s needs
|
||||
3. **Use environment-specific configs**: Different sandbox rules for development vs. production contexts
|
||||
4. **Combine with permissions**: Use sandboxing alongside IAM policies for comprehensive security
|
||||
5. **Test configurations**: Verify your sandbox settings don’t block legitimate workflows
|
||||
|
||||
## [](#open-source) Open source
|
||||
|
||||
The sandbox runtime is available as an open source npm package for use in your own agent projects. This enables the broader AI agent community to build safer, more secure autonomous systems. This can also be used to sandbox other programs you may wish to run. For example, to sandbox an MCP server you could run:
|
||||
|
||||
```bash
|
||||
npx @anthropic-ai/sandbox-runtime <command-to-sandbox>
|
||||
```
|
||||
|
||||
For implementation details and source code, visit the [GitHub repository](https://github.com/anthropic-experimental/sandbox-runtime).
|
||||
|
||||
## [](#limitations) Limitations
|
||||
|
||||
- **Performance overhead**: Minimal, but some filesystem operations may be slightly slower
|
||||
- **Compatibility**: Some tools that require specific system access patterns may need configuration adjustments, or may even need to be run outside of the sandbox
|
||||
- **Platform support**: Currently supports Linux and macOS; Windows support planned
|
||||
|
||||
## [](#see-also) See also
|
||||
|
||||
- [Security](/docs/en/security) - Comprehensive security features and best practices
|
||||
- [IAM](/docs/en/iam) - Permission configuration and access control
|
||||
- [Settings](/docs/en/settings) - Complete configuration reference
|
||||
- [CLI reference](/docs/en/cli-reference) - Command-line options
|
||||
@@ -0,0 +1,130 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/security
|
||||
title: Security
|
||||
---
|
||||
|
||||
## [](#how-we-approach-security) How we approach security
|
||||
|
||||
### [](#security-foundation) 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) 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](/docs/en/iam).
|
||||
|
||||
### [](#built-in-protections) Built-in protections
|
||||
|
||||
To mitigate risks in agentic systems:
|
||||
|
||||
- **Sandboxed bash tool**: [Sandbox](/docs/en/sandboxing) bash commands with filesystem and network isolation, reducing permission prompts while maintaining security. Enable with `/sandbox` to define boundaries where Claude Code can work autonomously
|
||||
- **Write access restriction**: Claude Code can only write to the folder where it was started and its subfolders—it cannot modify files in parent directories without explicit permission. While Claude Code can read files outside the working directory (useful for accessing system libraries and dependencies), write operations are strictly confined to the project scope, creating a clear security boundary
|
||||
- **Prompt fatigue mitigation**: Support for allowlisting frequently used safe commands per-user, per-codebase, or per-organization
|
||||
- **Accept Edits mode**: Batch accept multiple edits while maintaining permission prompts for commands with side effects
|
||||
|
||||
### [](#user-responsibility) 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) 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) 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](/docs/en/iam#tool-specific-permission-rules)
|
||||
|
||||
### [](#privacy-safeguards) 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) 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](/docs/en/iam#credential-management)
|
||||
|
||||
**Windows WebDAV security risk**: When running Claude Code on Windows, we recommend against enabling WebDAV or allowing Claude Code to access paths such as `\\*` that may contain WebDAV subdirectories. [WebDAV has been deprecated by Microsoft](https://learn.microsoft.com/en-us/windows/whats-new/deprecated-features#:~:text=The%20Webclient%20(WebDAV)%20service%20is%20deprecated) due to security risks. Enabling WebDAV may allow Claude Code to trigger network requests to remote hosts, bypassing the permission system.
|
||||
|
||||
**Best practices for working with untrusted content**:
|
||||
|
||||
1. Review suggested commands before approval
|
||||
2. Avoid piping untrusted content directly to Claude
|
||||
3. Verify proposed changes to critical files
|
||||
4. Use virtual machines (VMs) to run scripts and make tool calls, especially when interacting with external web services
|
||||
5. Report suspicious behavior with `/bug`
|
||||
|
||||
While these protections significantly reduce risk, no system is completely
|
||||
immune to all attacks. Always maintain good security practices when working
|
||||
with any AI tool.
|
||||
|
||||
## [](#mcp-security) 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) IDE security
|
||||
|
||||
See [here](/docs/en/vs-code#security) for more information on the security of running Claude Code in an IDE.
|
||||
|
||||
## [](#cloud-execution-security) Cloud execution security
|
||||
|
||||
When using [Claude Code on the web](/docs/en/claude-code-on-the-web), additional security controls are in place:
|
||||
|
||||
- **Isolated virtual machines**: Each cloud session runs in an isolated, Anthropic-managed VM
|
||||
- **Network access controls**: Network access is limited by default and can be configured to be disabled or allow only specific domains
|
||||
- **Credential protection**: Authentication is handled through a secure proxy that uses a scoped credential inside the sandbox, which is then translated to your actual GitHub authentication token
|
||||
- **Branch restrictions**: Git push operations are restricted to the current working branch
|
||||
- **Audit logging**: All operations in cloud environments are logged for compliance and audit purposes
|
||||
- **Automatic cleanup**: Cloud environments are automatically terminated after session completion
|
||||
|
||||
For more details on cloud execution, see [Claude Code on the web](/docs/en/claude-code-on-the-web).
|
||||
|
||||
## [](#security-best-practices) Security best practices
|
||||
|
||||
### [](#working-with-sensitive-code) Working with sensitive code
|
||||
|
||||
- Review all suggested changes before approval
|
||||
- Use project-specific permission settings for sensitive repositories
|
||||
- Consider using [devcontainers](/docs/en/devcontainer) for additional isolation
|
||||
- Regularly audit your permission settings with `/permissions`
|
||||
|
||||
### [](#team-security) Team security
|
||||
|
||||
- Use [managed settings](/docs/en/iam#managed-settings) to enforce organizational standards
|
||||
- Share approved permission configurations through version control
|
||||
- Train team members on security best practices
|
||||
- Monitor Claude Code usage through [OpenTelemetry metrics](/docs/en/monitoring-usage)
|
||||
|
||||
### [](#reporting-security-issues) 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) Related resources
|
||||
|
||||
- [Sandboxing](/docs/en/sandboxing) - Filesystem and network isolation for bash commands
|
||||
- [Identity and Access Management](/docs/en/iam) - Configure permissions and access controls
|
||||
- [Monitoring usage](/docs/en/monitoring-usage) - Track and audit Claude Code activity
|
||||
- [Development containers](/docs/en/devcontainer) - Secure, isolated environments
|
||||
- [Anthropic Trust Center](https://trust.anthropic.com) - Security certifications and compliance
|
||||
@@ -0,0 +1,903 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/settings
|
||||
title: Claude Code settings
|
||||
---
|
||||
|
||||
Claude Code offers a variety of settings to configure its behavior to meet your needs. You can configure Claude Code by running the `/config` command when using the interactive REPL, which opens a tabbed Settings interface where you can view status information and modify configuration options.
|
||||
|
||||
## [](#configuration-scopes) Configuration scopes
|
||||
|
||||
Claude Code uses a **scope system** to determine where configurations apply and who they’re shared with. Understanding scopes helps you decide how to configure Claude Code for personal use, team collaboration, or enterprise deployment.
|
||||
|
||||
### [](#available-scopes) Available scopes
|
||||
|
||||
| Scope | Location | Who it affects | Shared with team? |
|
||||
| --- | --- | --- | --- |
|
||||
| **Managed** | System-level `managed-settings.json` | All users on the machine | Yes (deployed by IT) |
|
||||
| **User** | `~/.claude/` directory | You, across all projects | No |
|
||||
| **Project** | `.claude/` in repository | All collaborators on this repository | Yes (committed to git) |
|
||||
| **Local** | `.claude/*.local.*` files | You, in this repository only | No (gitignored) |
|
||||
|
||||
### [](#when-to-use-each-scope) When to use each scope
|
||||
|
||||
**Managed scope** is for:
|
||||
|
||||
- Security policies that must be enforced organization-wide
|
||||
- Compliance requirements that can’t be overridden
|
||||
- Standardized configurations deployed by IT/DevOps
|
||||
|
||||
**User scope** is best for:
|
||||
|
||||
- Personal preferences you want everywhere (themes, editor settings)
|
||||
- Tools and plugins you use across all projects
|
||||
- API keys and authentication (stored securely)
|
||||
|
||||
**Project scope** is best for:
|
||||
|
||||
- Team-shared settings (permissions, hooks, MCP servers)
|
||||
- Plugins the whole team should have
|
||||
- Standardizing tooling across collaborators
|
||||
|
||||
**Local scope** is best for:
|
||||
|
||||
- Personal overrides for a specific project
|
||||
- Testing configurations before sharing with the team
|
||||
- Machine-specific settings that won’t work for others
|
||||
|
||||
### [](#how-scopes-interact) How scopes interact
|
||||
|
||||
When the same setting is configured in multiple scopes, more specific scopes take precedence:
|
||||
|
||||
1. **Managed** (highest) - can’t be overridden by anything
|
||||
2. **Command line arguments** - temporary session overrides
|
||||
3. **Local** - overrides project and user settings
|
||||
4. **Project** - overrides user settings
|
||||
5. **User** (lowest) - applies when nothing else specifies the setting
|
||||
|
||||
For example, if a permission is allowed in user settings but denied in project settings, the project setting takes precedence and the permission is blocked.
|
||||
|
||||
### [](#what-uses-scopes) What uses scopes
|
||||
|
||||
Scopes apply to many Claude Code features:
|
||||
|
||||
| Feature | User location | Project location | Local location |
|
||||
| --- | --- | --- | --- |
|
||||
| **Settings** | `~/.claude/settings.json` | `.claude/settings.json` | `.claude/settings.local.json` |
|
||||
| **Subagents** | `~/.claude/agents/` | `.claude/agents/` | — |
|
||||
| **MCP servers** | `~/.claude.json` | `.mcp.json` | `~/.claude.json` (per-project) |
|
||||
| **Plugins** | `~/.claude/settings.json` | `.claude/settings.json` | `.claude/settings.local.json` |
|
||||
| **CLAUDE.md** | `~/.claude/CLAUDE.md` | `CLAUDE.md` or `.claude/CLAUDE.md` | `CLAUDE.local.md` |
|
||||
|
||||
---
|
||||
|
||||
## [](#settings-files) Settings files
|
||||
|
||||
The `settings.json` file is our official mechanism for configuring Claude
|
||||
Code through hierarchical settings:
|
||||
|
||||
- **User settings** are defined in `~/.claude/settings.json` and apply to all
|
||||
projects.
|
||||
- **Project settings** are saved in your project directory:
|
||||
- `.claude/settings.json` for settings that are checked into source control and shared with your team
|
||||
- `.claude/settings.local.json` for settings that are not checked in, useful for personal preferences and experimentation. Claude Code will configure git to ignore `.claude/settings.local.json` when it is created.
|
||||
- **Managed settings**: For organizations that need centralized control, Claude Code supports `managed-settings.json` and `managed-mcp.json` files that can be deployed to system directories:
|
||||
- macOS: `/Library/Application Support/ClaudeCode/`
|
||||
- Linux and WSL: `/etc/claude-code/`
|
||||
- Windows: `C:\Program Files\ClaudeCode\`
|
||||
|
||||
These are system-wide paths (not user home directories like `~/Library/...`) that require administrator privileges. They are designed to be deployed by IT administrators.
|
||||
|
||||
See [Managed settings](/docs/en/iam#managed-settings) and [Managed MCP configuration](/docs/en/mcp#managed-mcp-configuration) for details.
|
||||
|
||||
Managed deployments can also restrict **plugin marketplace additions** using
|
||||
`strictKnownMarketplaces`. For more information, see [Managed marketplace restrictions](/docs/en/plugin-marketplaces#managed-marketplace-restrictions).
|
||||
- **Other configuration** is stored in `~/.claude.json`. This file contains your preferences (theme, notification settings, editor mode), OAuth session, [MCP server](/docs/en/mcp) configurations for user and local scopes, per-project state (allowed tools, trust settings), and various caches. Project-scoped MCP servers are stored separately in `.mcp.json`.
|
||||
|
||||
Example settings.json
|
||||
|
||||
```bash
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(npm run lint)",
|
||||
"Bash(npm run test:*)",
|
||||
"Read(~/.zshrc)"
|
||||
],
|
||||
"deny": [
|
||||
"Bash(curl:*)",
|
||||
"Read(./.env)",
|
||||
"Read(./.env.*)",
|
||||
"Read(./secrets/**)"
|
||||
]
|
||||
},
|
||||
"env": {
|
||||
"CLAUDE_CODE_ENABLE_TELEMETRY": "1",
|
||||
"OTEL_METRICS_EXPORTER": "otlp"
|
||||
},
|
||||
"companyAnnouncements": [
|
||||
"Welcome to Acme Corp! Review our code guidelines at docs.acme.com",
|
||||
"Reminder: Code reviews required for all PRs",
|
||||
"New security policy in effect"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### [](#available-settings) Available settings
|
||||
|
||||
`settings.json` supports a number of options:
|
||||
|
||||
| Key | Description | Example |
|
||||
| --- | --- | --- |
|
||||
| `apiKeyHelper` | Custom script, to be executed in `/bin/sh`, to generate an auth value. This value will be sent as `X-Api-Key` and `Authorization: Bearer` headers for model requests | `/bin/generate_temp_api_key.sh` |
|
||||
| `cleanupPeriodDays` | Sessions inactive for longer than this period are deleted at startup. Setting to `0` immediately deletes all sessions. (default: 30 days) | `20` |
|
||||
| `companyAnnouncements` | Announcement to display to users at startup. If multiple announcements are provided, they will be cycled through at random. | `["Welcome to Acme Corp! Review our code guidelines at docs.acme.com"]` |
|
||||
| `env` | Environment variables that will be applied to every session | `{"FOO": "bar"}` |
|
||||
| `attribution` | Customize attribution for git commits and pull requests. See [Attribution settings](#attribution-settings) | `{"commit": "🤖 Generated with Claude Code", "pr": ""}` |
|
||||
| `includeCoAuthoredBy` | **Deprecated**: Use `attribution` instead. Whether to include the `co-authored-by Claude` byline in git commits and pull requests (default: `true`) | `false` |
|
||||
| `permissions` | See table below for structure of permissions. | |
|
||||
| `hooks` | Configure custom commands to run before or after tool executions. See [hooks documentation](/docs/en/hooks) | `{"PreToolUse": {"Bash": "echo 'Running command...'"}}` |
|
||||
| `disableAllHooks` | Disable all [hooks](/docs/en/hooks) | `true` |
|
||||
| `allowManagedHooksOnly` | (Managed settings only) Prevent loading of user, project, and plugin hooks. Only allows managed hooks and SDK hooks. See [Hook configuration](#hook-configuration) | `true` |
|
||||
| `model` | Override the default model to use for Claude Code | `"claude-sonnet-4-5-20250929"` |
|
||||
| `otelHeadersHelper` | Script to generate dynamic OpenTelemetry headers. Runs at startup and periodically (see [Dynamic headers](/docs/en/monitoring-usage#dynamic-headers)) | `/bin/generate_otel_headers.sh` |
|
||||
| `statusLine` | Configure a custom status line to display context. See [`statusLine` documentation](/docs/en/statusline) | `{"type": "command", "command": "~/.claude/statusline.sh"}` |
|
||||
| `fileSuggestion` | Configure a custom script for `@` file autocomplete. See [File suggestion settings](#file-suggestion-settings) | `{"type": "command", "command": "~/.claude/file-suggestion.sh"}` |
|
||||
| `respectGitignore` | Control whether the `@` file picker respects `.gitignore` patterns. When `true` (default), files matching `.gitignore` patterns are excluded from suggestions | `false` |
|
||||
| `outputStyle` | Configure an output style to adjust the system prompt. See [output styles documentation](/docs/en/output-styles) | `"Explanatory"` |
|
||||
| `forceLoginMethod` | Use `claudeai` to restrict login to Claude.ai accounts, `console` to restrict login to Claude Console (API usage billing) accounts | `claudeai` |
|
||||
| `forceLoginOrgUUID` | Specify the UUID of an organization to automatically select it during login, bypassing the organization selection step. Requires `forceLoginMethod` to be set | `"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"` |
|
||||
| `enableAllProjectMcpServers` | Automatically approve all MCP servers defined in project `.mcp.json` files | `true` |
|
||||
| `enabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to approve | `["memory", "github"]` |
|
||||
| `disabledMcpjsonServers` | List of specific MCP servers from `.mcp.json` files to reject | `["filesystem"]` |
|
||||
| `allowedMcpServers` | When set in managed-settings.json, allowlist of MCP servers users can configure. Undefined = no restrictions, empty array = lockdown. Applies to all scopes. Denylist takes precedence. See [Managed MCP configuration](/docs/en/mcp#managed-mcp-configuration) | `[{ "serverName": "github" }]` |
|
||||
| `deniedMcpServers` | When set in managed-settings.json, denylist of MCP servers that are explicitly blocked. Applies to all scopes including managed servers. Denylist takes precedence over allowlist. See [Managed MCP configuration](/docs/en/mcp#managed-mcp-configuration) | `[{ "serverName": "filesystem" }]` |
|
||||
| `strictKnownMarketplaces` | When set in managed-settings.json, allowlist of plugin marketplaces users can add. Undefined = no restrictions, empty array = lockdown. Applies to marketplace additions only. See [Managed marketplace restrictions](/docs/en/plugin-marketplaces#managed-marketplace-restrictions) | `[{ "source": "github", "repo": "acme-corp/plugins" }]` |
|
||||
| `awsAuthRefresh` | Custom script that modifies the `.aws` directory (see [advanced credential configuration](/docs/en/amazon-bedrock#advanced-credential-configuration)) | `aws sso login --profile myprofile` |
|
||||
| `awsCredentialExport` | Custom script that outputs JSON with AWS credentials (see [advanced credential configuration](/docs/en/amazon-bedrock#advanced-credential-configuration)) | `/bin/generate_aws_grant.sh` |
|
||||
| `alwaysThinkingEnabled` | Enable [extended thinking](/docs/en/common-workflows#use-extended-thinking) by default for all sessions. Typically configured via the `/config` command rather than editing directly | `true` |
|
||||
| `plansDirectory` | Customize where plan files are stored. Path is relative to project root. Default: `~/.claude/plans` | `"./plans"` |
|
||||
| `showTurnDuration` | Show turn duration messages after responses (e.g., “Cooked for 1m 6s”). Set to `false` to hide these messages | `true` |
|
||||
| `language` | Configure Claude’s preferred response language (e.g., `"japanese"`, `"spanish"`, `"french"`). Claude will respond in this language by default | `"japanese"` |
|
||||
| `autoUpdatesChannel` | Release channel to follow for updates. Use `"stable"` for a version that is typically about one week old and skips versions with major regressions, or `"latest"` (default) for the most recent release | `"stable"` |
|
||||
| `spinnerTipsEnabled` | Show tips in the spinner while Claude is working. Set to `false` to disable tips (default: `true`) | `false` |
|
||||
| `terminalProgressBarEnabled` | Enable the terminal progress bar that shows progress in supported terminals like Windows Terminal and iTerm2 (default: `true`) | `false` |
|
||||
|
||||
### [](#permission-settings) Permission settings
|
||||
|
||||
| Keys | Description | Example |
|
||||
| --- | --- | --- |
|
||||
| `allow` | Array of permission rules to allow tool use. See [Permission rule syntax](#permission-rule-syntax) below for pattern matching details | `[ "Bash(git diff:*)" ]` |
|
||||
| `ask` | Array of permission rules to ask for confirmation upon tool use. See [Permission rule syntax](#permission-rule-syntax) below | `[ "Bash(git push:*)" ]` |
|
||||
| `deny` | Array of permission rules to deny tool use. Use this to exclude sensitive files from Claude Code access. See [Permission rule syntax](#permission-rule-syntax) and [Bash permission limitations](/docs/en/iam#tool-specific-permission-rules) | `[ "WebFetch", "Bash(curl:*)", "Read(./.env)", "Read(./secrets/**)" ]` |
|
||||
| `additionalDirectories` | Additional [working directories](/docs/en/iam#working-directories) that Claude has access to | `[ "../docs/" ]` |
|
||||
| `defaultMode` | Default [permission mode](/docs/en/iam#permission-modes) when opening Claude Code | `"acceptEdits"` |
|
||||
| `disableBypassPermissionsMode` | Set to `"disable"` to prevent `bypassPermissions` mode from being activated. This disables the `--dangerously-skip-permissions` command-line flag. See [managed settings](/docs/en/iam#managed-settings) | `"disable"` |
|
||||
|
||||
### [](#permission-rule-syntax) Permission rule syntax
|
||||
|
||||
Permission rules follow the format `Tool` or `Tool(specifier)`. Understanding the syntax helps you write rules that match exactly what you intend.
|
||||
|
||||
#### [](#rule-evaluation-order) Rule evaluation order
|
||||
|
||||
When multiple rules could match the same tool use, rules are evaluated in this order:
|
||||
|
||||
1. **Deny** rules are checked first
|
||||
2. **Ask** rules are checked second
|
||||
3. **Allow** rules are checked last
|
||||
|
||||
The first matching rule determines the behavior. This means deny rules always take precedence over allow rules, even if both match the same command.
|
||||
|
||||
#### [](#matching-all-uses-of-a-tool) Matching all uses of a tool
|
||||
|
||||
To match all uses of a tool, use just the tool name without parentheses:
|
||||
|
||||
| Rule | Effect |
|
||||
| --- | --- |
|
||||
| `Bash` | Matches **all** Bash commands |
|
||||
| `WebFetch` | Matches **all** web fetch requests |
|
||||
| `Read` | Matches **all** file reads |
|
||||
|
||||
`Bash(*)` does **not** match all Bash commands. The `*` wildcard only matches within the specifier context. To allow or deny all uses of a tool, use just the tool name: `Bash`, not `Bash(*)`.
|
||||
|
||||
#### [](#using-specifiers-for-fine-grained-control) Using specifiers for fine-grained control
|
||||
|
||||
Add a specifier in parentheses to match specific tool uses:
|
||||
|
||||
| Rule | Effect |
|
||||
| --- | --- |
|
||||
| `Bash(npm run build)` | Matches the exact command `npm run build` |
|
||||
| `Read(./.env)` | Matches reading the `.env` file in the current directory |
|
||||
| `WebFetch(domain:example.com)` | Matches fetch requests to example.com |
|
||||
|
||||
#### [](#wildcard-patterns) Wildcard patterns
|
||||
|
||||
Two wildcard syntaxes are available for Bash rules:
|
||||
|
||||
| Wildcard | Position | Behavior | Example |
|
||||
| --- | --- | --- | --- |
|
||||
| `:*` | End of pattern only | **Prefix matching** - matches commands starting with the prefix | `Bash(npm run:*)` matches `npm run test`, `npm run build` |
|
||||
| `*` | Anywhere in pattern | **Glob matching** - matches any sequence of characters at that position | `Bash(* install)` matches `npm install`, `yarn install` |
|
||||
|
||||
**Prefix matching with `:*`**
|
||||
The `:*` suffix matches any command that starts with the specified prefix. This works with multi-word commands. The following configuration allows npm and git commit commands while blocking git push and rm -rf:
|
||||
|
||||
```bash
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(npm run:*)",
|
||||
"Bash(git commit:*)",
|
||||
"Bash(docker compose:*)"
|
||||
],
|
||||
"deny": [
|
||||
"Bash(git push:*)",
|
||||
"Bash(rm -rf:*)"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Glob matching with `*`**
|
||||
The `*` wildcard can appear at the beginning, middle, or end of a pattern. The following configuration allows any git command targeting main (like `git checkout main`, `git merge main`) and any version check command (like `node --version`, `npm --version`):
|
||||
|
||||
```bash
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(git * main)",
|
||||
"Bash(* --version)"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Bash permission rules use pattern matching and can be bypassed using shell features like command flags, variables, or redirects. For example, `Bash(curl:*)` can be bypassed with `curl -X GET` reordered to `curl http://example.com -X GET`. Do not rely on Bash deny rules as a security boundary.
|
||||
|
||||
For detailed information about tool-specific permission patterns—including Read, Edit, WebFetch, MCP, Task rules, and Bash permission limitations—see [Tool-specific permission rules](/docs/en/iam#tool-specific-permission-rules).
|
||||
|
||||
### [](#sandbox-settings) Sandbox settings
|
||||
|
||||
Configure advanced sandboxing behavior. Sandboxing isolates bash commands from your filesystem and network. See [Sandboxing](/docs/en/sandboxing) for details.
|
||||
**Filesystem and network restrictions** are configured via Read, Edit, and WebFetch permission rules, not via these sandbox settings.
|
||||
|
||||
| Keys | Description | Example |
|
||||
| --- | --- | --- |
|
||||
| `enabled` | Enable bash sandboxing (macOS/Linux only). Default: false | `true` |
|
||||
| `autoAllowBashIfSandboxed` | Auto-approve bash commands when sandboxed. Default: true | `true` |
|
||||
| `excludedCommands` | Commands that should run outside of the sandbox | `["git", "docker"]` |
|
||||
| `allowUnsandboxedCommands` | Allow commands to run outside the sandbox via the `dangerouslyDisableSandbox` parameter. When set to `false`, the `dangerouslyDisableSandbox` escape hatch is completely disabled and all commands must run sandboxed (or be in `excludedCommands`). Useful for enterprise policies that require strict sandboxing. Default: true | `false` |
|
||||
| `network.allowUnixSockets` | Unix socket paths accessible in sandbox (for SSH agents, etc.) | `["~/.ssh/agent-socket"]` |
|
||||
| `network.allowLocalBinding` | Allow binding to localhost ports (macOS only). Default: false | `true` |
|
||||
| `network.httpProxyPort` | HTTP proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8080` |
|
||||
| `network.socksProxyPort` | SOCKS5 proxy port used if you wish to bring your own proxy. If not specified, Claude will run its own proxy. | `8081` |
|
||||
| `enableWeakerNestedSandbox` | Enable weaker sandbox for unprivileged Docker environments (Linux only). **Reduces security.** Default: false | `true` |
|
||||
|
||||
**Configuration example:**
|
||||
|
||||
```bash
|
||||
{
|
||||
"sandbox": {
|
||||
"enabled": true,
|
||||
"autoAllowBashIfSandboxed": true,
|
||||
"excludedCommands": ["docker"],
|
||||
"network": {
|
||||
"allowUnixSockets": [
|
||||
"/var/run/docker.sock"
|
||||
],
|
||||
"allowLocalBinding": true
|
||||
}
|
||||
},
|
||||
"permissions": {
|
||||
"deny": [
|
||||
"Read(.envrc)",
|
||||
"Read(~/.aws/**)"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Filesystem and network restrictions** use standard permission rules:
|
||||
|
||||
- Use `Read` deny rules to block Claude from reading specific files or directories
|
||||
- Use `Edit` allow rules to let Claude write to directories beyond the current working directory
|
||||
- Use `Edit` deny rules to block writes to specific paths
|
||||
- Use `WebFetch` allow/deny rules to control which network domains Claude can access
|
||||
|
||||
### [](#attribution-settings) Attribution settings
|
||||
|
||||
Claude Code adds attribution to git commits and pull requests. These are configured separately:
|
||||
|
||||
- Commits use [git trailers](https://git-scm.com/docs/git-interpret-trailers) (like `Co-Authored-By`) by default, which can be customized or disabled
|
||||
- Pull request descriptions are plain text
|
||||
|
||||
| Keys | Description |
|
||||
| --- | --- |
|
||||
| `commit` | Attribution for git commits, including any trailers. Empty string hides commit attribution |
|
||||
| `pr` | Attribution for pull request descriptions. Empty string hides pull request attribution |
|
||||
|
||||
**Default commit attribution:**
|
||||
|
||||
```bash
|
||||
🤖 Generated with [Claude Code](https://claude.com/claude-code)
|
||||
|
||||
Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
|
||||
```
|
||||
|
||||
**Default pull request attribution:**
|
||||
|
||||
```bash
|
||||
🤖 Generated with [Claude Code](https://claude.com/claude-code)
|
||||
```
|
||||
|
||||
**Example:**
|
||||
|
||||
```bash
|
||||
{
|
||||
"attribution": {
|
||||
"commit": "Generated with AI\n\nCo-Authored-By: AI <[email protected]>",
|
||||
"pr": ""
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `attribution` setting takes precedence over the deprecated `includeCoAuthoredBy` setting. To hide all attribution, set `commit` and `pr` to empty strings.
|
||||
|
||||
### [](#file-suggestion-settings) File suggestion settings
|
||||
|
||||
Configure a custom command for `@` file path autocomplete. The built-in file suggestion uses fast filesystem traversal, but large monorepos may benefit from project-specific indexing such as a pre-built file index or custom tooling.
|
||||
|
||||
```bash
|
||||
{
|
||||
"fileSuggestion": {
|
||||
"type": "command",
|
||||
"command": "~/.claude/file-suggestion.sh"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The command runs with the same environment variables as [hooks](/docs/en/hooks), including `CLAUDE_PROJECT_DIR`. It receives JSON via stdin with a `query` field:
|
||||
|
||||
```bash
|
||||
{"query": "src/comp"}
|
||||
```
|
||||
|
||||
Output newline-separated file paths to stdout (currently limited to 15):
|
||||
|
||||
```bash
|
||||
src/components/Button.tsx
|
||||
src/components/Modal.tsx
|
||||
src/components/Form.tsx
|
||||
```
|
||||
|
||||
**Example:**
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
query=$(cat | jq -r '.query')
|
||||
your-repo-file-index --query "$query" | head -20
|
||||
```
|
||||
|
||||
### [](#hook-configuration) Hook configuration
|
||||
|
||||
**Managed settings only**: Controls which hooks are allowed to run. This setting can only be configured in [managed settings](#settings-files) and provides administrators with strict control over hook execution.
|
||||
**Behavior when `allowManagedHooksOnly` is `true`:**
|
||||
|
||||
- Managed hooks and SDK hooks are loaded
|
||||
- User hooks, project hooks, and plugin hooks are blocked
|
||||
|
||||
**Configuration:**
|
||||
|
||||
```bash
|
||||
{
|
||||
"allowManagedHooksOnly": true
|
||||
}
|
||||
```
|
||||
|
||||
### [](#settings-precedence) Settings precedence
|
||||
|
||||
Settings apply in order of precedence. From highest to lowest:
|
||||
|
||||
1. **Managed settings** (`managed-settings.json`)
|
||||
- Policies deployed by IT/DevOps to system directories
|
||||
- Cannot be overridden by user or project settings
|
||||
2. **Command line arguments**
|
||||
- Temporary overrides for a specific session
|
||||
3. **Local project settings** (`.claude/settings.local.json`)
|
||||
- Personal project-specific settings
|
||||
4. **Shared project settings** (`.claude/settings.json`)
|
||||
- Team-shared project settings in source control
|
||||
5. **User settings** (`~/.claude/settings.json`)
|
||||
- Personal global settings
|
||||
|
||||
This hierarchy ensures that organizational policies are always enforced while still allowing teams and individuals to customize their experience.
|
||||
For example, if your user settings allow `Bash(npm run:*)` but a project’s shared settings deny it, the project setting takes precedence and the command is blocked.
|
||||
|
||||
### [](#key-points-about-the-configuration-system) 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 (Managed) override lower-level ones (User/Project)
|
||||
- **Inheritance**: Settings are merged, with more specific settings adding to or overriding broader ones
|
||||
|
||||
### [](#system-prompt) System prompt
|
||||
|
||||
Claude Code’s internal system prompt is not published. To add custom instructions, use `CLAUDE.md` files or the `--append-system-prompt` flag.
|
||||
|
||||
### [](#excluding-sensitive-files) Excluding sensitive files
|
||||
|
||||
To prevent Claude Code from accessing files containing sensitive information like API keys, secrets, and environment files, use the `permissions.deny` setting in your `.claude/settings.json` file:
|
||||
|
||||
```bash
|
||||
{
|
||||
"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) 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](/docs/en/sub-agents).
|
||||
|
||||
## [](#plugin-configuration) 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 settings
|
||||
|
||||
Plugin-related settings in `settings.json`:
|
||||
|
||||
```bash
|
||||
{
|
||||
"enabledPlugins": {
|
||||
"formatter@acme-tools": true,
|
||||
"deployer@acme-tools": true,
|
||||
"analyzer@security-plugins": false
|
||||
},
|
||||
"extraKnownMarketplaces": {
|
||||
"acme-tools": {
|
||||
"source": "github",
|
||||
"repo": "acme-corp/claude-plugins"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### [](#enabledplugins) `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**:
|
||||
|
||||
```bash
|
||||
{
|
||||
"enabledPlugins": {
|
||||
"code-formatter@team-tools": true,
|
||||
"deployment-tools@team-tools": true,
|
||||
"experimental-features@personal": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### [](#extraknownmarketplaces) `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**:
|
||||
|
||||
```bash
|
||||
{
|
||||
"extraKnownMarketplaces": {
|
||||
"acme-tools": {
|
||||
"source": {
|
||||
"source": "github",
|
||||
"repo": "acme-corp/claude-plugins"
|
||||
}
|
||||
},
|
||||
"security-plugins": {
|
||||
"source": {
|
||||
"source": "git",
|
||||
"url": "https://git.example.com/security/plugins.git"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Marketplace source types**:
|
||||
|
||||
- `github`: GitHub repository (uses `repo`)
|
||||
- `git`: Any git URL (uses `url`)
|
||||
- `directory`: Local filesystem path (uses `path`, for development only)
|
||||
|
||||
#### [](#strictknownmarketplaces) `strictKnownMarketplaces`
|
||||
|
||||
**Managed settings only**: Controls which plugin marketplaces users are allowed to add. This setting can only be configured in [`managed-settings.json`](/docs/en/iam#managed-settings) and provides administrators with strict control over marketplace sources.
|
||||
**Managed settings file locations**:
|
||||
|
||||
- **macOS**: `/Library/Application Support/ClaudeCode/managed-settings.json`
|
||||
- **Linux and WSL**: `/etc/claude-code/managed-settings.json`
|
||||
- **Windows**: `C:\Program Files\ClaudeCode\managed-settings.json`
|
||||
|
||||
**Key characteristics**:
|
||||
|
||||
- Only available in managed settings (`managed-settings.json`)
|
||||
- Cannot be overridden by user or project settings (highest precedence)
|
||||
- Enforced BEFORE network/filesystem operations (blocked sources never execute)
|
||||
- Uses exact matching for source specifications (including `ref`, `path` for git sources)
|
||||
|
||||
**Allowlist behavior**:
|
||||
|
||||
- `undefined` (default): No restrictions - users can add any marketplace
|
||||
- Empty array `[]`: Complete lockdown - users cannot add any new marketplaces
|
||||
- List of sources: Users can only add marketplaces that match exactly
|
||||
|
||||
**All supported source types**:
|
||||
The allowlist supports six marketplace source types. Each source must match exactly for a user’s marketplace addition to be allowed.
|
||||
|
||||
1. **GitHub repositories**:
|
||||
|
||||
```bash
|
||||
{ "source": "github", "repo": "acme-corp/approved-plugins" }
|
||||
{ "source": "github", "repo": "acme-corp/security-tools", "ref": "v2.0" }
|
||||
{ "source": "github", "repo": "acme-corp/plugins", "ref": "main", "path": "marketplace" }
|
||||
```
|
||||
|
||||
Fields: `repo` (required), `ref` (optional: branch/tag/SHA), `path` (optional: subdirectory)
|
||||
|
||||
2. **Git repositories**:
|
||||
|
||||
```bash
|
||||
{ "source": "git", "url": "https://gitlab.example.com/tools/plugins.git" }
|
||||
{ "source": "git", "url": "https://bitbucket.org/acme-corp/plugins.git", "ref": "production" }
|
||||
{ "source": "git", "url": "ssh://[email protected]/plugins.git", "ref": "v3.1", "path": "approved" }
|
||||
```
|
||||
|
||||
Fields: `url` (required), `ref` (optional: branch/tag/SHA), `path` (optional: subdirectory)
|
||||
|
||||
3. **URL-based marketplaces**:
|
||||
|
||||
```bash
|
||||
{ "source": "url", "url": "https://plugins.example.com/marketplace.json" }
|
||||
{ "source": "url", "url": "https://cdn.example.com/marketplace.json", "headers": { "Authorization": "Bearer ${TOKEN}" } }
|
||||
```
|
||||
|
||||
Fields: `url` (required), `headers` (optional: HTTP headers for authenticated access)
|
||||
|
||||
URL-based marketplaces only download the `marketplace.json` file. They do not download plugin files from the server. Plugins in URL-based marketplaces must use external sources (GitHub, npm, or git URLs) rather than relative paths. For plugins with relative paths, use a Git-based marketplace instead. See [Troubleshooting](/docs/en/plugin-marketplaces#plugins-with-relative-paths-fail-in-url-based-marketplaces) for details.
|
||||
|
||||
4. **NPM packages**:
|
||||
|
||||
```bash
|
||||
{ "source": "npm", "package": "@acme-corp/claude-plugins" }
|
||||
{ "source": "npm", "package": "@acme-corp/approved-marketplace" }
|
||||
```
|
||||
|
||||
Fields: `package` (required, supports scoped packages)
|
||||
|
||||
5. **File paths**:
|
||||
|
||||
```bash
|
||||
{ "source": "file", "path": "/usr/local/share/claude/acme-marketplace.json" }
|
||||
{ "source": "file", "path": "/opt/acme-corp/plugins/marketplace.json" }
|
||||
```
|
||||
|
||||
Fields: `path` (required: absolute path to marketplace.json file)
|
||||
|
||||
6. **Directory paths**:
|
||||
|
||||
```bash
|
||||
{ "source": "directory", "path": "/usr/local/share/claude/acme-plugins" }
|
||||
{ "source": "directory", "path": "/opt/acme-corp/approved-marketplaces" }
|
||||
```
|
||||
|
||||
Fields: `path` (required: absolute path to directory containing `.claude-plugin/marketplace.json`)
|
||||
**Configuration examples**:
|
||||
Example - Allow specific marketplaces only:
|
||||
|
||||
```bash
|
||||
{
|
||||
"strictKnownMarketplaces": [
|
||||
{
|
||||
"source": "github",
|
||||
"repo": "acme-corp/approved-plugins"
|
||||
},
|
||||
{
|
||||
"source": "github",
|
||||
"repo": "acme-corp/security-tools",
|
||||
"ref": "v2.0"
|
||||
},
|
||||
{
|
||||
"source": "url",
|
||||
"url": "https://plugins.example.com/marketplace.json"
|
||||
},
|
||||
{
|
||||
"source": "npm",
|
||||
"package": "@acme-corp/compliance-plugins"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Example - Disable all marketplace additions:
|
||||
|
||||
```bash
|
||||
{
|
||||
"strictKnownMarketplaces": []
|
||||
}
|
||||
```
|
||||
|
||||
**Exact matching requirements**:
|
||||
Marketplace sources must match **exactly** for a user’s addition to be allowed. For git-based sources (`github` and `git`), this includes all optional fields:
|
||||
|
||||
- The `repo` or `url` must match exactly
|
||||
- The `ref` field must match exactly (or both be undefined)
|
||||
- The `path` field must match exactly (or both be undefined)
|
||||
|
||||
Examples of sources that **do NOT match**:
|
||||
|
||||
```bash
|
||||
// These are DIFFERENT sources:
|
||||
{ "source": "github", "repo": "acme-corp/plugins" }
|
||||
{ "source": "github", "repo": "acme-corp/plugins", "ref": "main" }
|
||||
|
||||
// These are also DIFFERENT:
|
||||
{ "source": "github", "repo": "acme-corp/plugins", "path": "marketplace" }
|
||||
{ "source": "github", "repo": "acme-corp/plugins" }
|
||||
```
|
||||
|
||||
**Comparison with `extraKnownMarketplaces`**:
|
||||
|
||||
| Aspect | `strictKnownMarketplaces` | `extraKnownMarketplaces` |
|
||||
| --- | --- | --- |
|
||||
| **Purpose** | Organizational policy enforcement | Team convenience |
|
||||
| **Settings file** | `managed-settings.json` only | Any settings file |
|
||||
| **Behavior** | Blocks non-allowlisted additions | Auto-installs missing marketplaces |
|
||||
| **When enforced** | Before network/filesystem operations | After user trust prompt |
|
||||
| **Can be overridden** | No (highest precedence) | Yes (by higher precedence settings) |
|
||||
| **Source format** | Direct source object | Named marketplace with nested source |
|
||||
| **Use case** | Compliance, security restrictions | Onboarding, standardization |
|
||||
|
||||
**Format difference**:
|
||||
`strictKnownMarketplaces` uses direct source objects:
|
||||
|
||||
```bash
|
||||
{
|
||||
"strictKnownMarketplaces": [
|
||||
{ "source": "github", "repo": "acme-corp/plugins" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`extraKnownMarketplaces` requires named marketplaces:
|
||||
|
||||
```bash
|
||||
{
|
||||
"extraKnownMarketplaces": {
|
||||
"acme-tools": {
|
||||
"source": { "source": "github", "repo": "acme-corp/plugins" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Important notes**:
|
||||
|
||||
- Restrictions are checked BEFORE any network requests or filesystem operations
|
||||
- When blocked, users see clear error messages indicating the source is blocked by managed policy
|
||||
- The restriction applies only to adding NEW marketplaces; previously installed marketplaces remain accessible
|
||||
- Managed settings have the highest precedence and cannot be overridden
|
||||
|
||||
See [Managed marketplace restrictions](/docs/en/plugin-marketplaces#managed-marketplace-restrictions) for user-facing documentation.
|
||||
|
||||
### [](#managing-plugins) 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](/docs/en/plugins).
|
||||
|
||||
## [](#environment-variables) Environment variables
|
||||
|
||||
Claude Code supports the following environment variables to control its behavior:
|
||||
|
||||
All environment variables can also be configured in [`settings.json`](#available-settings). This is useful as a way to automatically set environment variables for each session, or to roll out a set of environment variables for your whole team or organization.
|
||||
|
||||
| Variable | Purpose |
|
||||
| --- | --- |
|
||||
| `ANTHROPIC_API_KEY` | API key sent as `X-Api-Key` header, typically for the Claude SDK (for interactive usage, run `/login`) |
|
||||
| `ANTHROPIC_AUTH_TOKEN` | Custom value for the `Authorization` header (the value you set here will be prefixed with `Bearer` ) |
|
||||
| `ANTHROPIC_CUSTOM_HEADERS` | Custom headers you want to add to the request (in `Name: Value` format) |
|
||||
| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | See [Model configuration](/docs/en/model-config#environment-variables) |
|
||||
| `ANTHROPIC_DEFAULT_OPUS_MODEL` | See [Model configuration](/docs/en/model-config#environment-variables) |
|
||||
| `ANTHROPIC_DEFAULT_SONNET_MODEL` | See [Model configuration](/docs/en/model-config#environment-variables) |
|
||||
| `ANTHROPIC_FOUNDRY_API_KEY` | API key for Microsoft Foundry authentication (see [Microsoft Foundry](/docs/en/microsoft-foundry)) |
|
||||
| `ANTHROPIC_MODEL` | Name of the model setting to use (see [Model Configuration](/docs/en/model-config#environment-variables)) |
|
||||
| `ANTHROPIC_SMALL_FAST_MODEL` | [DEPRECATED] Name of [Haiku-class model for background tasks](/docs/en/costs) |
|
||||
| `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION` | Override AWS region for the Haiku-class model when using Bedrock |
|
||||
| `AWS_BEARER_TOKEN_BEDROCK` | Bedrock API key for authentication (see [Bedrock API keys](https://aws.amazon.com/blogs/machine-learning/accelerate-ai-development-with-amazon-bedrock-api-keys/)) |
|
||||
| `BASH_DEFAULT_TIMEOUT_MS` | Default timeout for long-running bash commands |
|
||||
| `BASH_MAX_OUTPUT_LENGTH` | Maximum number of characters in bash outputs before they are middle-truncated |
|
||||
| `BASH_MAX_TIMEOUT_MS` | Maximum timeout the model can set for long-running bash commands |
|
||||
| `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` | Set the percentage of context capacity (1-100) at which auto-compaction triggers. By default, auto-compaction triggers at approximately 95% capacity. Use lower values like `50` to compact earlier. Values above the default threshold have no effect. Applies to both main conversations and subagents. This percentage aligns with the `context_window.used_percentage` field available in [status line](/docs/en/statusline) |
|
||||
| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Return to the original working directory after each Bash command |
|
||||
| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | Interval in milliseconds at which credentials should be refreshed (when using `apiKeyHelper`) |
|
||||
| `CLAUDE_CODE_CLIENT_CERT` | Path to client certificate file for mTLS authentication |
|
||||
| `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE` | Passphrase for encrypted CLAUDE\_CODE\_CLIENT\_KEY (optional) |
|
||||
| `CLAUDE_CODE_CLIENT_KEY` | Path to client private key file for mTLS authentication |
|
||||
| `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` | Set to `1` to disable Anthropic API-specific `anthropic-beta` headers. Use this if experiencing issues like “Unexpected value(s) for the `anthropic-beta` header” when using an LLM gateway with third-party providers |
|
||||
| `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` | Set to `1` to disable all background task functionality, including the `run_in_background` parameter on Bash and subagent tools, auto-backgrounding, and the Ctrl+B shortcut |
|
||||
| `CLAUDE_CODE_EXIT_AFTER_STOP_DELAY` | Time in milliseconds to wait after the query loop becomes idle before automatically exiting. Useful for automated workflows and scripts using SDK mode |
|
||||
| `CLAUDE_CODE_PROXY_RESOLVES_HOSTS` | Set to `true` to allow the proxy to perform DNS resolution instead of the caller. Opt-in for environments where the proxy should handle hostname resolution |
|
||||
| `CLAUDE_CODE_TMPDIR` | Override the temp directory used for internal temp files. Claude Code appends `/claude/` to this path. Default: `/tmp` on Unix/macOS, `os.tmpdir()` on Windows |
|
||||
| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Equivalent of setting `DISABLE_AUTOUPDATER`, `DISABLE_BUG_COMMAND`, `DISABLE_ERROR_REPORTING`, and `DISABLE_TELEMETRY` |
|
||||
| `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | Set to `1` to disable automatic terminal title updates based on conversation context |
|
||||
| `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS` | Override the default token limit for file reads. Useful when you need to read larger files in full |
|
||||
| `CLAUDE_CODE_HIDE_ACCOUNT_INFO` | Set to `1` to hide your email address and organization name from the Claude Code UI. Useful when streaming or recording |
|
||||
| `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL` | Skip auto-installation of IDE extensions |
|
||||
| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | Set the maximum number of output tokens for most requests. Default: 32,000. Maximum: 64,000. Increasing this value reduces the effective context window available before [auto-compaction](/docs/en/costs#reduce-token-usage) triggers. |
|
||||
| `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` | Interval for refreshing dynamic OpenTelemetry headers in milliseconds (default: 1740000 / 29 minutes). See [Dynamic headers](/docs/en/monitoring-usage#dynamic-headers) |
|
||||
| `CLAUDE_CODE_SHELL` | Override automatic shell detection. Useful when your login shell differs from your preferred working shell (for example, `bash` vs `zsh`) |
|
||||
| `CLAUDE_CODE_SHELL_PREFIX` | Command prefix to wrap all bash commands (for example, for logging or auditing). Example: `/path/to/logger.sh` will execute `/path/to/logger.sh <command>` |
|
||||
| `CLAUDE_CODE_SKIP_BEDROCK_AUTH` | Skip AWS authentication for Bedrock (for example, when using an LLM gateway) |
|
||||
| `CLAUDE_CODE_SKIP_FOUNDRY_AUTH` | Skip Azure authentication for Microsoft Foundry (for example, when using an LLM gateway) |
|
||||
| `CLAUDE_CODE_SKIP_VERTEX_AUTH` | Skip Google authentication for Vertex (for example, when using an LLM gateway) |
|
||||
| `CLAUDE_CODE_SUBAGENT_MODEL` | See [Model configuration](/docs/en/model-config) |
|
||||
| `CLAUDE_CODE_USE_BEDROCK` | Use [Bedrock](/docs/en/amazon-bedrock) |
|
||||
| `CLAUDE_CODE_USE_FOUNDRY` | Use [Microsoft Foundry](/docs/en/microsoft-foundry) |
|
||||
| `CLAUDE_CODE_USE_VERTEX` | Use [Vertex](/docs/en/google-vertex-ai) |
|
||||
| `CLAUDE_CONFIG_DIR` | Customize where Claude Code stores its configuration and data files |
|
||||
| `DISABLE_AUTOUPDATER` | Set to `1` to disable automatic updates. |
|
||||
| `DISABLE_BUG_COMMAND` | Set to `1` to disable the `/bug` command |
|
||||
| `DISABLE_COST_WARNINGS` | Set to `1` to disable cost warning messages |
|
||||
| `DISABLE_ERROR_REPORTING` | Set to `1` to opt out of Sentry error reporting |
|
||||
| `DISABLE_NON_ESSENTIAL_MODEL_CALLS` | Set to `1` to disable model calls for non-critical paths like flavor text |
|
||||
| `DISABLE_PROMPT_CACHING` | Set to `1` to disable prompt caching for all models (takes precedence over per-model settings) |
|
||||
| `DISABLE_PROMPT_CACHING_HAIKU` | Set to `1` to disable prompt caching for Haiku models |
|
||||
| `DISABLE_PROMPT_CACHING_OPUS` | Set to `1` to disable prompt caching for Opus models |
|
||||
| `DISABLE_PROMPT_CACHING_SONNET` | Set to `1` to disable prompt caching for Sonnet models |
|
||||
| `DISABLE_TELEMETRY` | Set to `1` to opt out of Statsig telemetry (note that Statsig events do not include user data like code, file paths, or bash commands) |
|
||||
| `ENABLE_TOOL_SEARCH` | Controls [MCP tool search](/docs/en/mcp#scale-with-mcp-tool-search). Values: `auto` (default, enables at 10% context), `auto:N` (custom threshold, e.g., `auto:5` for 5%), `true` (always on), `false` (disabled) |
|
||||
| `FORCE_AUTOUPDATE_PLUGINS` | Set to `true` to force plugin auto-updates even when the main auto-updater is disabled via `DISABLE_AUTOUPDATER` |
|
||||
| `HTTP_PROXY` | Specify HTTP proxy server for network connections |
|
||||
| `HTTPS_PROXY` | Specify HTTPS proxy server for network connections |
|
||||
| `IS_DEMO` | Set to `true` to enable demo mode: hides email and organization from the UI, skips onboarding, and hides internal commands. Useful for streaming or recording sessions |
|
||||
| `MAX_MCP_OUTPUT_TOKENS` | Maximum number of tokens allowed in MCP tool responses. Claude Code displays a warning when output exceeds 10,000 tokens (default: 25000) |
|
||||
| `MAX_THINKING_TOKENS` | Override the [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) token budget. Thinking is enabled at max budget (31,999 tokens) by default. Use this to limit the budget (for example, `MAX_THINKING_TOKENS=10000`) or disable thinking entirely (`MAX_THINKING_TOKENS=0`). Extended thinking improves performance on complex reasoning and coding tasks but impacts [prompt caching efficiency](https://docs.claude.com/en/docs/build-with-claude/prompt-caching#caching-with-thinking-blocks). |
|
||||
| `MCP_TIMEOUT` | Timeout in milliseconds for MCP server startup |
|
||||
| `MCP_TOOL_TIMEOUT` | Timeout in milliseconds for MCP tool execution |
|
||||
| `NO_PROXY` | List of domains and IPs to which requests will be directly issued, bypassing proxy |
|
||||
| `SLASH_COMMAND_TOOL_CHAR_BUDGET` | Maximum number of characters for slash command metadata shown to the [Skill tool](/docs/en/slash-commands#skill-tool) (default: 15000) |
|
||||
| `USE_BUILTIN_RIPGREP` | Set to `0` to use system-installed `rg` instead of `rg` included with Claude Code |
|
||||
| `VERTEX_REGION_CLAUDE_3_5_HAIKU` | Override region for Claude 3.5 Haiku when using Vertex AI |
|
||||
| `VERTEX_REGION_CLAUDE_3_7_SONNET` | Override region for Claude 3.7 Sonnet when using Vertex AI |
|
||||
| `VERTEX_REGION_CLAUDE_4_0_OPUS` | Override region for Claude 4.0 Opus when using Vertex AI |
|
||||
| `VERTEX_REGION_CLAUDE_4_0_SONNET` | Override region for Claude 4.0 Sonnet when using Vertex AI |
|
||||
| `VERTEX_REGION_CLAUDE_4_1_OPUS` | Override region for Claude 4.1 Opus when using Vertex AI |
|
||||
|
||||
## [](#tools-available-to-claude) Tools available to Claude
|
||||
|
||||
Claude Code has access to a set of powerful tools that help it understand and modify your codebase:
|
||||
|
||||
| Tool | Description | Permission Required |
|
||||
| --- | --- | --- |
|
||||
| **AskUserQuestion** | Asks multiple-choice questions to gather requirements or clarify ambiguity | No |
|
||||
| **Bash** | Executes shell commands in your environment (see [Bash tool behavior](#bash-tool-behavior) below) | Yes |
|
||||
| **TaskOutput** | Retrieves output from a background task (bash shell or subagent) | No |
|
||||
| **Edit** | Makes targeted edits to specific files | Yes |
|
||||
| **ExitPlanMode** | Prompts the user to exit plan mode and start coding | Yes |
|
||||
| **Glob** | Finds files based on pattern matching | No |
|
||||
| **Grep** | Searches for patterns in file contents | No |
|
||||
| **KillShell** | Kills a running background bash shell by its ID | No |
|
||||
| **MCPSearch** | Searches for and loads MCP tools when [tool search](/docs/en/mcp#scale-with-mcp-tool-search) is enabled | No |
|
||||
| **NotebookEdit** | Modifies Jupyter notebook cells | Yes |
|
||||
| **Read** | Reads the contents of files | No |
|
||||
| **Skill** | Executes a [skill or slash command](/docs/en/slash-commands#skill-tool) within the main conversation | Yes |
|
||||
| **Task** | Runs a sub-agent to handle complex, multi-step tasks | No |
|
||||
| **TodoWrite** | Creates and manages structured task lists | No |
|
||||
| **WebFetch** | Fetches content from a specified URL | Yes |
|
||||
| **WebSearch** | Performs web searches with domain filtering | Yes |
|
||||
| **Write** | Creates or overwrites files | Yes |
|
||||
|
||||
Permission rules can be configured using `/allowed-tools` or in [permission settings](/docs/en/settings#available-settings). Also see [Tool-specific permission rules](/docs/en/iam#tool-specific-permission-rules).
|
||||
|
||||
### [](#bash-tool-behavior) Bash tool behavior
|
||||
|
||||
The Bash tool executes shell commands with the following persistence behavior:
|
||||
|
||||
- **Working directory persists**: When Claude changes the working directory (for example, `cd /path/to/dir`), subsequent Bash commands will execute in that directory. You can use `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1` to reset to the project directory after each command.
|
||||
- **Environment variables do NOT persist**: Environment variables set in one Bash command (for example, `export MY_VAR=value`) are **not** available in subsequent Bash commands. Each Bash command runs in a fresh shell environment.
|
||||
|
||||
To make environment variables available in Bash commands, you have **three options**:
|
||||
**Option 1: Activate environment before starting Claude Code** (simplest approach)
|
||||
Activate your virtual environment in your terminal before launching Claude Code:
|
||||
|
||||
```bash
|
||||
conda activate myenv
|
||||
# or: source /path/to/venv/bin/activate
|
||||
claude
|
||||
```
|
||||
|
||||
This works for shell environments but environment variables set within Claude’s Bash commands will not persist between commands.
|
||||
**Option 2: Set CLAUDE\_ENV\_FILE before starting Claude Code** (persistent environment setup)
|
||||
Export the path to a shell script containing your environment setup:
|
||||
|
||||
```bash
|
||||
export CLAUDE_ENV_FILE=/path/to/env-setup.sh
|
||||
claude
|
||||
```
|
||||
|
||||
Where `/path/to/env-setup.sh` contains:
|
||||
|
||||
```bash
|
||||
conda activate myenv
|
||||
# or: source /path/to/venv/bin/activate
|
||||
# or: export MY_VAR=value
|
||||
```
|
||||
|
||||
Claude Code will source this file before each Bash command, making the environment persistent across all commands.
|
||||
**Option 3: Use a SessionStart hook** (project-specific configuration)
|
||||
Configure in `.claude/settings.json`:
|
||||
|
||||
```bash
|
||||
{
|
||||
"hooks": {
|
||||
"SessionStart": [{
|
||||
"matcher": "startup",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": "echo 'conda activate myenv' >> \"$CLAUDE_ENV_FILE\""
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The hook writes to `$CLAUDE_ENV_FILE`, which is then sourced before each Bash command. This is ideal for team-shared project configurations.
|
||||
See [SessionStart hooks](/docs/en/hooks#persisting-environment-variables) for more details on Option 3.
|
||||
|
||||
### [](#extending-tools-with-hooks) Extending tools with hooks
|
||||
|
||||
You can run custom commands before or after any tool executes using
|
||||
[Claude Code hooks](/docs/en/hooks-guide).
|
||||
For example, you could automatically run a Python formatter after Claude
|
||||
modifies Python files, or prevent modifications to production configuration
|
||||
files by blocking Write operations to certain paths.
|
||||
|
||||
## [](#see-also) See also
|
||||
|
||||
- [Identity and Access Management](/docs/en/iam#configuring-permissions) - Permission system overview and how allow/ask/deny rules interact
|
||||
- [Tool-specific permission rules](/docs/en/iam#tool-specific-permission-rules) - Detailed patterns for Bash, Read, Edit, WebFetch, MCP, and Task tools, including security limitations
|
||||
- [Managed settings](/docs/en/iam#managed-settings) - Managed policy configuration for organizations
|
||||
- [Troubleshooting](/docs/en/troubleshooting#auto-updater-issues) - Solutions for common configuration issues
|
||||
@@ -0,0 +1,305 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/setup
|
||||
title: Set up Claude Code
|
||||
---
|
||||
|
||||
## [](#system-requirements) System requirements
|
||||
|
||||
- **Operating Systems**: macOS 13.0+, Ubuntu 20.04+/Debian 10+, or Windows 10+ (with WSL 1, WSL 2, or Git for Windows)
|
||||
- **Hardware**: 4 GB+ RAM
|
||||
- **Network**: Internet connection required (see [network configuration](/docs/en/network-config#network-access-requirements))
|
||||
- **Shell**: Works best in Bash or Zsh
|
||||
- **Location**: [Anthropic supported countries](https://www.anthropic.com/supported-countries)
|
||||
|
||||
### [](#additional-dependencies) Additional dependencies
|
||||
|
||||
- **ripgrep**: Usually included with Claude Code. If search fails, see [search troubleshooting](/docs/en/troubleshooting#search-and-discovery-issues).
|
||||
- **[Node.js 18+](https://nodejs.org/en/download)**: Only required for [deprecated npm installation](#npm-installation-deprecated)
|
||||
|
||||
## [](#installation) Installation
|
||||
|
||||
To install Claude Code, use one of the following methods:
|
||||
|
||||
- Native Install (Recommended)
|
||||
- Homebrew
|
||||
- WinGet
|
||||
|
||||
**macOS, Linux, WSL:**
|
||||
|
||||
```bash
|
||||
curl -fsSL https://claude.ai/install.sh | bash
|
||||
```
|
||||
|
||||
**Windows PowerShell:**
|
||||
|
||||
```bash
|
||||
irm https://claude.ai/install.ps1 | iex
|
||||
```
|
||||
|
||||
**Windows CMD:**
|
||||
|
||||
```bash
|
||||
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
|
||||
```
|
||||
|
||||
Native installations automatically update in the background to keep you on the latest version.
|
||||
|
||||
```bash
|
||||
brew install --cask claude-code
|
||||
```
|
||||
|
||||
Homebrew installations do not auto-update. Run `brew upgrade claude-code` periodically to get the latest features and security fixes.
|
||||
|
||||
```bash
|
||||
winget install Anthropic.ClaudeCode
|
||||
```
|
||||
|
||||
WinGet installations do not auto-update. Run `winget upgrade Anthropic.ClaudeCode` periodically to get the latest features and security fixes.
|
||||
|
||||
After the installation process completes, navigate to your project and start Claude Code:
|
||||
|
||||
```bash
|
||||
cd your-awesome-project
|
||||
claude
|
||||
```
|
||||
|
||||
If you encounter any issues during installation, consult the [troubleshooting guide](/docs/en/troubleshooting).
|
||||
|
||||
Run `claude doctor` after installation to check your installation type and version.
|
||||
|
||||
**Alpine Linux and other musl/uClibc-based distributions**: The native installer requires `libgcc`, `libstdc++`, and `ripgrep`. For Alpine: `apk add libgcc libstdc++ ripgrep`. Set `USE_BUILTIN_RIPGREP=0`.
|
||||
|
||||
### [](#authentication) Authentication
|
||||
|
||||
#### [](#for-individuals) For individuals
|
||||
|
||||
1. **Claude Pro or Max plan** (recommended): Subscribe to Claude’s [Pro or Max plan](https://claude.ai/pricing) for a unified subscription that includes both Claude Code and Claude on the web. Manage your account in one place and log in with your Claude.ai account.
|
||||
2. **Claude Console**: Connect through the [Claude Console](https://console.anthropic.com) and complete the OAuth process. Requires active billing in the Anthropic Console. A “Claude Code” workspace is automatically created for usage tracking and cost management. You can’t create API keys for the Claude Code workspace; it’s dedicated exclusively for Claude Code usage.
|
||||
|
||||
#### [](#for-teams-and-organizations) For teams and organizations
|
||||
|
||||
1. **Claude for Teams or Enterprise** (recommended): Subscribe to [Claude for Teams](https://claude.com/pricing#team-&-enterprise) or [Claude for Enterprise](https://anthropic.com/contact-sales) for centralized billing, team management, and access to both Claude Code and Claude on the web. Team members log in with their Claude.ai accounts.
|
||||
2. **Claude Console with team billing**: Set up a shared [Claude Console](https://console.anthropic.com) organization with team billing. Invite team members and assign roles for usage tracking.
|
||||
3. **Cloud providers**: Configure Claude Code to use [Amazon Bedrock, Google Vertex AI, or Microsoft Foundry](/docs/en/third-party-integrations) for deployments with your existing cloud infrastructure.
|
||||
|
||||
### [](#install-a-specific-version) Install a specific version
|
||||
|
||||
The native installer accepts either a specific version number or a release channel (`latest` or `stable`). The channel you choose at install time becomes your default for auto-updates. See [Configure release channel](#configure-release-channel) for more information.
|
||||
To install the latest version (default):
|
||||
|
||||
- macOS, Linux, WSL
|
||||
- Windows PowerShell
|
||||
- Windows CMD
|
||||
|
||||
```bash
|
||||
curl -fsSL https://claude.ai/install.sh | bash
|
||||
```
|
||||
|
||||
```bash
|
||||
irm https://claude.ai/install.ps1 | iex
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
|
||||
```
|
||||
|
||||
To install the stable version:
|
||||
|
||||
- macOS, Linux, WSL
|
||||
- Windows PowerShell
|
||||
- Windows CMD
|
||||
|
||||
```bash
|
||||
curl -fsSL https://claude.ai/install.sh | bash -s stable
|
||||
```
|
||||
|
||||
```bash
|
||||
& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) stable
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd stable && del install.cmd
|
||||
```
|
||||
|
||||
To install a specific version number:
|
||||
|
||||
- macOS, Linux, WSL
|
||||
- Windows PowerShell
|
||||
- Windows CMD
|
||||
|
||||
```bash
|
||||
curl -fsSL https://claude.ai/install.sh | bash -s 1.0.58
|
||||
```
|
||||
|
||||
```bash
|
||||
& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) 1.0.58
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd 1.0.58 && del install.cmd
|
||||
```
|
||||
|
||||
### [](#binary-integrity-and-code-signing) Binary integrity and code signing
|
||||
|
||||
- SHA256 checksums for all platforms are published in the release manifests, currently located at `https://storage.googleapis.com/claude-code-dist-86c565f3-f756-42ad-8dfa-d59b1c096819/claude-code-releases/{VERSION}/manifest.json` (example: replace `{VERSION}` with `2.0.30`)
|
||||
- Signed binaries are distributed for the following platforms:
|
||||
- macOS: Signed by “Anthropic PBC” and notarized by Apple
|
||||
- Windows: Signed by “Anthropic, PBC”
|
||||
|
||||
## [](#npm-installation-deprecated) NPM installation (deprecated)
|
||||
|
||||
NPM installation is deprecated. Use the [native installation](#installation) method when possible. To migrate an existing npm installation to native, run `claude install`.
|
||||
**Global npm installation**
|
||||
|
||||
```bash
|
||||
npm install -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
Do NOT use `sudo npm install -g` as this can lead to permission issues and security risks.
|
||||
If you encounter permission errors, see [configure Claude Code](/docs/en/troubleshooting#linux-permission-issues) for recommended solutions.
|
||||
|
||||
## [](#windows-setup) 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`:
|
||||
|
||||
```bash
|
||||
$env:CLAUDE_CODE_GIT_BASH_PATH="C:\Program Files\Git\bin\bash.exe"
|
||||
```
|
||||
|
||||
## [](#update-claude-code) Update Claude Code
|
||||
|
||||
### [](#auto-updates) Auto updates
|
||||
|
||||
Claude Code automatically keeps itself up to date to ensure you have the latest features and security fixes.
|
||||
|
||||
- **Update checks**: Performed on startup and periodically while running
|
||||
- **Update process**: Downloads and installs automatically in the background
|
||||
- **Notifications**: You’ll see a notification when updates are installed
|
||||
- **Applying updates**: Updates take effect the next time you start Claude Code
|
||||
|
||||
Homebrew and WinGet installations do not auto-update. Use `brew upgrade claude-code` or `winget upgrade Anthropic.ClaudeCode` to update manually.**Known issue:** Claude Code may notify you of updates before the new version is available in these package managers. If an upgrade fails, wait and try again later.
|
||||
|
||||
### [](#configure-release-channel) Configure release channel
|
||||
|
||||
Configure which release channel Claude Code follows for both auto-updates and `claude update` with the `autoUpdatesChannel` setting:
|
||||
|
||||
- `"latest"` (default): Receive new features as soon as they’re released
|
||||
- `"stable"`: Use a version that is typically about one week old, skipping releases with major regressions
|
||||
|
||||
Configure this via `/config` → **Auto-update channel**, or add it to your [settings.json file](/docs/en/settings):
|
||||
|
||||
```bash
|
||||
{
|
||||
"autoUpdatesChannel": "stable"
|
||||
}
|
||||
```
|
||||
|
||||
For enterprise deployments, you can enforce a consistent release channel across your organization using [managed settings](/docs/en/iam#managed-settings).
|
||||
|
||||
### [](#disable-auto-updates) Disable auto-updates
|
||||
|
||||
Set the `DISABLE_AUTOUPDATER` environment variable in your shell or [settings.json file](/docs/en/settings):
|
||||
|
||||
```bash
|
||||
export DISABLE_AUTOUPDATER=1
|
||||
```
|
||||
|
||||
### [](#update-manually) Update manually
|
||||
|
||||
```bash
|
||||
claude update
|
||||
```
|
||||
|
||||
## [](#uninstall-claude-code) Uninstall Claude Code
|
||||
|
||||
If you need to uninstall Claude Code, follow the instructions for your installation method.
|
||||
|
||||
### [](#native-installation) Native installation
|
||||
|
||||
Remove the Claude Code binary and version files:
|
||||
**macOS, Linux, WSL:**
|
||||
|
||||
```bash
|
||||
rm -f ~/.local/bin/claude
|
||||
rm -rf ~/.local/share/claude
|
||||
```
|
||||
|
||||
**Windows PowerShell:**
|
||||
|
||||
```bash
|
||||
Remove-Item -Path "$env:USERPROFILE\.local\bin\claude.exe" -Force
|
||||
Remove-Item -Path "$env:USERPROFILE\.local\share\claude" -Recurse -Force
|
||||
```
|
||||
|
||||
**Windows CMD:**
|
||||
|
||||
```bash
|
||||
del "%USERPROFILE%\.local\bin\claude.exe"
|
||||
rmdir /s /q "%USERPROFILE%\.local\share\claude"
|
||||
```
|
||||
|
||||
### [](#homebrew-installation) Homebrew installation
|
||||
|
||||
```bash
|
||||
brew uninstall --cask claude-code
|
||||
```
|
||||
|
||||
### [](#winget-installation) WinGet installation
|
||||
|
||||
```bash
|
||||
winget uninstall Anthropic.ClaudeCode
|
||||
```
|
||||
|
||||
### [](#npm-installation) NPM installation
|
||||
|
||||
```bash
|
||||
npm uninstall -g @anthropic-ai/claude-code
|
||||
```
|
||||
|
||||
### [](#clean-up-configuration-files-optional) Clean up configuration files (optional)
|
||||
|
||||
Removing configuration files will delete all your settings, allowed tools, MCP server configurations, and session history.
|
||||
|
||||
To remove Claude Code settings and cached data:
|
||||
**macOS, Linux, WSL:**
|
||||
|
||||
```bash
|
||||
# Remove user settings and state
|
||||
rm -rf ~/.claude
|
||||
rm ~/.claude.json
|
||||
|
||||
# Remove project-specific settings (run from your project directory)
|
||||
rm -rf .claude
|
||||
rm -f .mcp.json
|
||||
```
|
||||
|
||||
**Windows PowerShell:**
|
||||
|
||||
```bash
|
||||
# Remove user settings and state
|
||||
Remove-Item -Path "$env:USERPROFILE\.claude" -Recurse -Force
|
||||
Remove-Item -Path "$env:USERPROFILE\.claude.json" -Force
|
||||
|
||||
# Remove project-specific settings (run from your project directory)
|
||||
Remove-Item -Path ".claude" -Recurse -Force
|
||||
Remove-Item -Path ".mcp.json" -Force
|
||||
```
|
||||
|
||||
**Windows CMD:**
|
||||
|
||||
```bash
|
||||
REM Remove user settings and state
|
||||
rmdir /s /q "%USERPROFILE%\.claude"
|
||||
del "%USERPROFILE%\.claude.json"
|
||||
|
||||
REM Remove project-specific settings (run from your project directory)
|
||||
rmdir /s /q ".claude"
|
||||
del ".mcp.json"
|
||||
```
|
||||
@@ -0,0 +1,751 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/skills
|
||||
title: Agent Skills
|
||||
---
|
||||
|
||||
A Skill is a markdown file that teaches Claude how to do something specific, such as reviewing PRs using your team’s standards or generating commit messages in your preferred format. When you ask Claude something that matches a Skill’s purpose, Claude automatically applies it.
|
||||
Skills can also bundle scripts in any language. This means Claude can run Python, Node.js, Bash, or any other scripts you include, giving it capabilities far beyond what’s possible in a single prompt. For example, generate interactive visualizations, query databases, process files, call APIs, or produce reports in any format. See [Generate visual output](#generate-visual-output) for an example Skill that uses a Python script to create an interactive codebase visualization.
|
||||
This guide covers creating Skills, configuring them with metadata and scripts, and sharing them with your team or organization.
|
||||
|
||||
## [](#create-your-first-skill) Create your first Skill
|
||||
|
||||
This example creates a personal Skill that teaches Claude to explain code using visual diagrams and analogies. Unlike Claude’s default explanations, this Skill ensures every explanation includes an ASCII diagram and a real-world analogy.
|
||||
|
||||
1
|
||||
|
||||
Check available Skills
|
||||
|
||||
Before creating a Skill, see what Skills Claude already has access to:
|
||||
|
||||
```bash
|
||||
What Skills are available?
|
||||
```
|
||||
|
||||
Claude will list any Skills currently loaded. You may see none, or you may see Skills from plugins or your organization.
|
||||
|
||||
2
|
||||
|
||||
Create the Skill directory
|
||||
|
||||
Create a directory for the Skill in your personal Skills folder. Personal Skills are available across all your projects. (You can also create [project Skills](#where-skills-live) in `.claude/skills/` to share with your team.)
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.claude/skills/explaining-code
|
||||
```
|
||||
|
||||
3
|
||||
|
||||
Write SKILL.md
|
||||
|
||||
Every Skill needs a `SKILL.md` file. The file starts with YAML metadata between `---` markers and must include a `name` and `description`, followed by Markdown instructions that Claude follows when the Skill is active.The `description` is especially important, because Claude uses it to decide when to apply the Skill.Create `~/.claude/skills/explaining-code/SKILL.md`:
|
||||
|
||||
```bash
|
||||
---
|
||||
name: explaining-code
|
||||
description: Explains code with visual diagrams and analogies. Use when explaining how code works, teaching about a codebase, or when the user asks "how does this work?"
|
||||
---
|
||||
|
||||
When explaining code, always include:
|
||||
|
||||
1. **Start with an analogy**: Compare the code to something from everyday life
|
||||
2. **Draw a diagram**: Use ASCII art to show the flow, structure, or relationships
|
||||
3. **Walk through the code**: Explain step-by-step what happens
|
||||
4. **Highlight a gotcha**: What's a common mistake or misconception?
|
||||
|
||||
Keep explanations conversational. For complex concepts, use multiple analogies.
|
||||
```
|
||||
|
||||
4
|
||||
|
||||
Load and verify the Skill
|
||||
|
||||
Skills are automatically loaded when created or modified. Verify the Skill appears in the list:
|
||||
|
||||
```bash
|
||||
What Skills are available?
|
||||
```
|
||||
|
||||
You should see `explaining-code` in the list with its description.
|
||||
|
||||
5
|
||||
|
||||
Test the Skill
|
||||
|
||||
Open any file in your project and ask Claude a question that matches the Skill’s description:
|
||||
|
||||
```bash
|
||||
How does this code work?
|
||||
```
|
||||
|
||||
Claude should ask to use the `explaining-code` Skill, then include an analogy and ASCII diagram in its explanation. If the Skill doesn’t trigger, try rephrasing to include more keywords from the description, like “explain how this works.”
|
||||
|
||||
The rest of this guide covers how Skills work, configuration options, and troubleshooting.
|
||||
|
||||
## [](#how-skills-work) How Skills work
|
||||
|
||||
Skills are **model-invoked**: Claude decides which Skills to use based on your request. You don’t need to explicitly call a Skill. Claude automatically applies relevant Skills when your request matches their description.
|
||||
When you send a request, Claude follows these steps to find and use relevant Skills:
|
||||
|
||||
1
|
||||
|
||||
Discovery
|
||||
|
||||
At startup, Claude loads only the name and description of each available Skill. This keeps startup fast while giving Claude enough context to know when each Skill might be relevant.
|
||||
|
||||
2
|
||||
|
||||
Activation
|
||||
|
||||
When your request matches a Skill’s description, Claude asks to use the Skill. You’ll see a confirmation prompt before the full `SKILL.md` is loaded into context. Since Claude reads these descriptions to find relevant Skills, [write descriptions](#skill-not-triggering) that include keywords users would naturally say.
|
||||
|
||||
3
|
||||
|
||||
Execution
|
||||
|
||||
Claude follows the Skill’s instructions, loading referenced files or running bundled scripts as needed.
|
||||
|
||||
### [](#where-skills-live) Where Skills live
|
||||
|
||||
Where you store a Skill determines who can use it:
|
||||
|
||||
| Location | Path | Applies to |
|
||||
| --- | --- | --- |
|
||||
| Enterprise | See [managed settings](/docs/en/iam#managed-settings) | All users in your organization |
|
||||
| Personal | `~/.claude/skills/` | You, across all projects |
|
||||
| Project | `.claude/skills/` | Anyone working in this repository |
|
||||
| Plugin | Bundled with [plugins](/docs/en/plugins) | Anyone with the plugin installed |
|
||||
|
||||
If two Skills have the same name, the higher row wins: managed overrides personal, personal overrides project, and project overrides plugin.
|
||||
|
||||
#### [](#automatic-discovery-from-nested-directories) Automatic discovery from nested directories
|
||||
|
||||
When you work with files in subdirectories, Claude Code automatically discovers Skills from nested `.claude/skills/` directories. For example, if you’re editing a file in `packages/frontend/`, Claude Code also looks for Skills in `packages/frontend/.claude/skills/`. This supports monorepo setups where packages have their own Skills.
|
||||
|
||||
### [](#when-to-use-skills-versus-other-options) When to use Skills versus other options
|
||||
|
||||
Claude Code offers several ways to customize behavior. The key difference: **Skills are triggered automatically by Claude** based on your request, while slash commands require you to type `/command` explicitly.
|
||||
|
||||
| Use this | When you want to… | When it runs |
|
||||
| --- | --- | --- |
|
||||
| **Skills** | Give Claude specialized knowledge (e.g., “review PRs using our standards”) | Claude chooses when relevant |
|
||||
| **[Slash commands](/docs/en/slash-commands)** | Create reusable prompts (e.g., `/deploy staging`) | You type `/command` to run it |
|
||||
| **[CLAUDE.md](/docs/en/memory)** | Set project-wide instructions (e.g., “use TypeScript strict mode”) | Loaded into every conversation |
|
||||
| **[Subagents](/docs/en/sub-agents)** | Delegate tasks to a separate context with its own tools | Claude delegates, or you invoke explicitly |
|
||||
| **[Hooks](/docs/en/hooks)** | Run scripts on events (e.g., lint on file save) | Fires on specific tool events |
|
||||
| **[MCP servers](/docs/en/mcp)** | Connect Claude to external tools and data sources | Claude calls MCP tools as needed |
|
||||
|
||||
**Skills vs. subagents**: Skills add knowledge to the current conversation. Subagents run in a separate context with their own tools. Use Skills for guidance and standards; use subagents when you need isolation or different tool access.
|
||||
**Skills vs. MCP**: Skills tell Claude *how* to use tools; MCP *provides* the tools. For example, an MCP server connects Claude to your database, while a Skill teaches Claude your data model and query patterns.
|
||||
|
||||
For a deep dive into the architecture and real-world applications of Agent Skills, read [Equipping agents for the real world with Agent Skills](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills).
|
||||
|
||||
## [](#configure-skills) Configure Skills
|
||||
|
||||
This section covers Skill file structure, supporting files, tool restrictions, and distribution options.
|
||||
|
||||
### [](#write-skill-md) Write SKILL.md
|
||||
|
||||
The `SKILL.md` file is the only required file in a Skill. It has two parts: YAML metadata (the section between `---` markers) at the top, and Markdown instructions that tell Claude how to use the Skill:
|
||||
|
||||
```bash
|
||||
---
|
||||
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.
|
||||
```
|
||||
|
||||
#### [](#available-metadata-fields) Available metadata fields
|
||||
|
||||
You can use the following fields in the YAML frontmatter:
|
||||
|
||||
| Field | Required | Description |
|
||||
| --- | --- | --- |
|
||||
| `name` | Yes | Skill name. Must use lowercase letters, numbers, and hyphens only (max 64 characters). Should match the directory name. |
|
||||
| `description` | Yes | What the Skill does and when to use it (max 1024 characters). Claude uses this to decide when to apply the Skill. |
|
||||
| `allowed-tools` | No | Tools Claude can use without asking permission when this Skill is active. Supports comma-separated values or YAML-style lists. See [Restrict tool access](#restrict-tool-access-with-allowed-tools). |
|
||||
| `model` | No | [Model](https://docs.claude.com/en/docs/about-claude/models/overview) to use when this Skill is active (e.g., `claude-sonnet-4-20250514`). Defaults to the conversation’s model. |
|
||||
| `context` | No | Set to `fork` to run the Skill in a forked sub-agent context with its own conversation history. |
|
||||
| `agent` | No | Specify which [agent type](/docs/en/sub-agents#built-in-subagents) to use when `context: fork` is set (e.g., `Explore`, `Plan`, `general-purpose`, or a custom agent name from `.claude/agents/`). Defaults to `general-purpose` if not specified. Only applicable when combined with `context: fork`. |
|
||||
| `hooks` | No | Define hooks scoped to this Skill’s lifecycle. Supports `PreToolUse`, `PostToolUse`, and `Stop` events. |
|
||||
| `user-invocable` | No | Controls whether the Skill appears in the slash command menu. Does not affect the [`Skill` tool](/docs/en/slash-commands#skill-tool) or automatic discovery. Defaults to `true`. See [Control Skill visibility](#control-skill-visibility). |
|
||||
|
||||
#### [](#available-string-substitutions) Available string substitutions
|
||||
|
||||
Skills support string substitution for dynamic values in the Skill content:
|
||||
|
||||
| Variable | Description |
|
||||
| --- | --- |
|
||||
| `$ARGUMENTS` | All arguments passed when invoking the Skill. If `$ARGUMENTS` is not present in the content, arguments are appended as `ARGUMENTS: <value>`. |
|
||||
| `${CLAUDE_SESSION_ID}` | The current session ID. Useful for logging, creating session-specific files, or correlating Skill output with sessions. |
|
||||
|
||||
**Example using substitutions:**
|
||||
|
||||
```bash
|
||||
---
|
||||
name: session-logger
|
||||
description: Log activity for this session
|
||||
---
|
||||
|
||||
Log the following to logs/${CLAUDE_SESSION_ID}.log:
|
||||
|
||||
$ARGUMENTS
|
||||
```
|
||||
|
||||
See the [best practices guide](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/best-practices) for complete authoring guidance including validation rules.
|
||||
|
||||
### [](#update-or-delete-a-skill) Update or delete a Skill
|
||||
|
||||
To update a Skill, edit its `SKILL.md` file directly. To remove a Skill, delete its directory. Changes take effect immediately.
|
||||
|
||||
### [](#add-supporting-files-with-progressive-disclosure) Add supporting files with progressive disclosure
|
||||
|
||||
Skills share Claude’s context window with conversation history, other Skills, and your request. To keep context focused, use **progressive disclosure**: put essential information in `SKILL.md` and detailed reference material in separate files that Claude reads only when needed.
|
||||
This approach lets you bundle comprehensive documentation, examples, and scripts without consuming context upfront. Claude loads additional files only when the task requires them.
|
||||
|
||||
Keep `SKILL.md` under 500 lines for optimal performance. If your content exceeds this, split detailed reference material into separate files.
|
||||
|
||||
#### [](#example:-multi-file-skill-structure) Example: multi-file Skill structure
|
||||
|
||||
Claude discovers supporting files through links in your `SKILL.md`. The following example shows a Skill with detailed documentation in separate files and utility scripts that Claude can execute without reading:
|
||||
|
||||
```bash
|
||||
my-skill/
|
||||
├── SKILL.md (required - overview and navigation)
|
||||
├── reference.md (detailed API docs - loaded when needed)
|
||||
├── examples.md (usage examples - loaded when needed)
|
||||
└── scripts/
|
||||
└── helper.py (utility script - executed, not loaded)
|
||||
```
|
||||
|
||||
The `SKILL.md` file references these supporting files so Claude knows they exist:
|
||||
|
||||
```bash
|
||||
## Overview
|
||||
|
||||
[Essential instructions here]
|
||||
|
||||
## Additional resources
|
||||
|
||||
- For complete API details, see [reference.md](reference.md)
|
||||
- For usage examples, see [examples.md](examples.md)
|
||||
|
||||
## Utility scripts
|
||||
|
||||
To validate input files, run the helper script. It checks for required fields and returns any validation errors:
|
||||
```bash
|
||||
python scripts/helper.py input.txt
|
||||
```
|
||||
```
|
||||
|
||||
Keep references one level deep. Link directly from `SKILL.md` to reference files. Deeply nested references (file A links to file B which links to file C) may result in Claude partially reading files.
|
||||
|
||||
**Bundle utility scripts for zero-context execution.** Scripts in your Skill directory can be executed without loading their contents into context. Claude runs the script and only the output consumes tokens. This is useful for:
|
||||
|
||||
- Complex validation logic that would be verbose to describe in prose
|
||||
- Data processing that’s more reliable as tested code than generated code
|
||||
- Operations that benefit from consistency across uses
|
||||
|
||||
In `SKILL.md`, tell Claude to run the script rather than read it:
|
||||
|
||||
```bash
|
||||
Run the validation script to check the form:
|
||||
python scripts/validate_form.py input.pdf
|
||||
```
|
||||
|
||||
For complete guidance on structuring Skills, see the [best practices guide](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/best-practices#progressive-disclosure-patterns).
|
||||
|
||||
### [](#restrict-tool-access-with-allowed-tools) Restrict tool access with allowed-tools
|
||||
|
||||
Use the `allowed-tools` frontmatter field to limit which tools Claude can use when a Skill is active. You can specify tools as a comma-separated string or a YAML list:
|
||||
|
||||
```bash
|
||||
---
|
||||
name: reading-files-safely
|
||||
description: Read files without making changes. Use when you need read-only file access.
|
||||
allowed-tools: Read, Grep, Glob
|
||||
---
|
||||
```
|
||||
|
||||
Or use YAML-style lists for better readability:
|
||||
|
||||
```bash
|
||||
---
|
||||
name: reading-files-safely
|
||||
description: Read files without making changes. Use when you need read-only file access.
|
||||
allowed-tools:
|
||||
- Read
|
||||
- Grep
|
||||
- Glob
|
||||
---
|
||||
```
|
||||
|
||||
When this Skill is active, Claude can only use the specified tools (Read, Grep, Glob) without needing to ask for permission. This is useful for:
|
||||
|
||||
- Read-only Skills that shouldn’t modify files
|
||||
- Skills with limited scope: for example, only data analysis, no file writing
|
||||
- Security-sensitive workflows where you want to restrict capabilities
|
||||
|
||||
If `allowed-tools` is omitted, the Skill doesn’t restrict tools. Claude uses its standard permission model and may ask you to approve tool usage.
|
||||
|
||||
`allowed-tools` is only supported for Skills in Claude Code.
|
||||
|
||||
### [](#run-skills-in-a-forked-context) Run Skills in a forked context
|
||||
|
||||
Use `context: fork` to run a Skill in an isolated sub-agent context with its own conversation history. This is useful for Skills that perform complex multi-step operations without cluttering the main conversation:
|
||||
|
||||
```bash
|
||||
---
|
||||
name: code-analysis
|
||||
description: Analyze code quality and generate detailed reports
|
||||
context: fork
|
||||
---
|
||||
```
|
||||
|
||||
### [](#define-hooks-for-skills) Define hooks for Skills
|
||||
|
||||
Skills can define hooks that run during the Skill’s lifecycle. Use the `hooks` field to specify `PreToolUse`, `PostToolUse`, or `Stop` handlers:
|
||||
|
||||
```bash
|
||||
---
|
||||
name: secure-operations
|
||||
description: Perform operations with additional security checks
|
||||
hooks:
|
||||
PreToolUse:
|
||||
- matcher: "Bash"
|
||||
hooks:
|
||||
- type: command
|
||||
command: "./scripts/security-check.sh $TOOL_INPUT"
|
||||
once: true
|
||||
---
|
||||
```
|
||||
|
||||
The `once: true` option runs the hook only once per session. After the first successful execution, the hook is removed.
|
||||
Hooks defined in a Skill are scoped to that Skill’s execution and are automatically cleaned up when the Skill finishes.
|
||||
See [Hooks](/docs/en/hooks) for the complete hook configuration format.
|
||||
|
||||
### [](#control-skill-visibility) Control Skill visibility
|
||||
|
||||
Skills can be invoked in three ways:
|
||||
|
||||
1. **Manual invocation**: You type `/skill-name` in the prompt
|
||||
2. **Programmatic invocation**: Claude calls it via the [`Skill` tool](/docs/en/slash-commands#skill-tool)
|
||||
3. **Automatic discovery**: Claude reads the Skill’s description and loads it when relevant to the conversation
|
||||
|
||||
The `user-invocable` field controls only manual invocation. When set to `false`, the Skill is hidden from the slash command menu but Claude can still invoke it programmatically or discover it automatically.
|
||||
To block programmatic invocation via the `Skill` tool, use `disable-model-invocation: true` instead.
|
||||
|
||||
#### [](#when-to-use-each-setting) When to use each setting
|
||||
|
||||
| Setting | Slash menu | `Skill` tool | Auto-discovery | Use case |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `user-invocable: true` (default) | Visible | Allowed | Yes | Skills you want users to invoke directly |
|
||||
| `user-invocable: false` | Hidden | Allowed | Yes | Skills that Claude can use but users shouldn’t invoke manually |
|
||||
| `disable-model-invocation: true` | Visible | Blocked | Yes | Skills you want users to invoke but not Claude programmatically |
|
||||
|
||||
#### [](#example:-model-only-skill) Example: model-only Skill
|
||||
|
||||
Set `user-invocable: false` to hide a Skill from the slash menu while still allowing Claude to invoke it programmatically:
|
||||
|
||||
```bash
|
||||
---
|
||||
name: internal-review-standards
|
||||
description: Apply internal code review standards when reviewing pull requests
|
||||
user-invocable: false
|
||||
---
|
||||
```
|
||||
|
||||
With this setting, users won’t see the Skill in the `/` menu, but Claude can still invoke it via the `Skill` tool or discover it automatically based on context.
|
||||
|
||||
### [](#skills-and-subagents) Skills and subagents
|
||||
|
||||
There are two ways Skills and subagents can work together:
|
||||
|
||||
#### [](#give-a-subagent-access-to-skills) Give a subagent access to Skills
|
||||
|
||||
[Subagents](/docs/en/sub-agents) do not automatically inherit Skills from the main conversation. To give a custom subagent access to specific Skills, list them in the subagent’s `skills` field:
|
||||
|
||||
```bash
|
||||
# .claude/agents/code-reviewer.md
|
||||
---
|
||||
name: code-reviewer
|
||||
description: Review code for quality and best practices
|
||||
skills: pr-review, security-check
|
||||
---
|
||||
```
|
||||
|
||||
The full content of each listed Skill is injected into the subagent’s context at startup, not just made available for invocation. If the `skills` field is omitted, no Skills are loaded for that subagent.
|
||||
|
||||
Built-in agents (Explore, Plan, general-purpose) do not have access to your Skills. Only custom subagents you define in `.claude/agents/` with an explicit `skills` field can use Skills.
|
||||
|
||||
#### [](#run-a-skill-in-a-subagent-context) Run a Skill in a subagent context
|
||||
|
||||
Use `context: fork` and `agent` to run a Skill in a forked subagent with its own separate context. See [Run Skills in a forked context](#run-skills-in-a-forked-context) for details.
|
||||
|
||||
### [](#distribute-skills) Distribute Skills
|
||||
|
||||
You can share Skills in several ways:
|
||||
|
||||
- **Project Skills**: Commit `.claude/skills/` to version control. Anyone who clones the repository gets the Skills.
|
||||
- **Plugins**: To share Skills across multiple repositories, create a `skills/` directory in your [plugin](/docs/en/plugins) with Skill folders containing `SKILL.md` files. Distribute through a [plugin marketplace](/docs/en/plugin-marketplaces).
|
||||
- **Managed**: Administrators can deploy Skills organization-wide through [managed settings](/docs/en/iam#managed-settings). See [Where Skills live](#where-skills-live) for managed Skill paths.
|
||||
|
||||
## [](#examples) Examples
|
||||
|
||||
These examples show common Skill patterns, from minimal single-file Skills to multi-file Skills with supporting documentation and scripts.
|
||||
|
||||
### [](#simple-skill-single-file) Simple Skill (single file)
|
||||
|
||||
A minimal Skill needs only a `SKILL.md` file with frontmatter and instructions. This example helps Claude generate commit messages by examining staged changes:
|
||||
|
||||
```bash
|
||||
commit-helper/
|
||||
└── SKILL.md
|
||||
```
|
||||
|
||||
```bash
|
||||
---
|
||||
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
|
||||
```
|
||||
|
||||
### [](#use-multiple-files) Use multiple files
|
||||
|
||||
For complex Skills, use progressive disclosure to keep the main `SKILL.md` focused while providing detailed documentation in supporting files. This PDF processing Skill includes reference docs, utility scripts, and uses `allowed-tools` to restrict Claude to specific tools:
|
||||
|
||||
```bash
|
||||
pdf-processing/
|
||||
├── SKILL.md # Overview and quick start
|
||||
├── FORMS.md # Form field mappings and filling instructions
|
||||
├── REFERENCE.md # API details for pypdf and pdfplumber
|
||||
└── scripts/
|
||||
├── fill_form.py # Utility to populate form fields
|
||||
└── validate.py # Checks PDFs for required fields
|
||||
```
|
||||
|
||||
**`SKILL.md`**:
|
||||
|
||||
```bash
|
||||
---
|
||||
name: pdf-processing
|
||||
description: Extract text, fill forms, merge PDFs. Use when working with PDF files, forms, or document extraction. Requires pypdf and pdfplumber packages.
|
||||
allowed-tools: Read, Bash(python:*)
|
||||
---
|
||||
|
||||
# PDF Processing
|
||||
|
||||
## 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
|
||||
```
|
||||
```
|
||||
|
||||
If your Skill requires external packages, list them in the description. Packages must be installed in your environment before Claude can use them.
|
||||
|
||||
### [](#generate-visual-output) Generate visual output
|
||||
|
||||
Skills can bundle and run scripts in any language, giving Claude capabilities beyond what’s possible in a single prompt. One powerful pattern is generating visual output: interactive HTML files that open in your browser for exploring data, debugging, or creating reports.
|
||||
This example creates a codebase explorer: an interactive tree view where you can expand and collapse directories, see file sizes at a glance, and identify file types by color.
|
||||
Create the Skill directory:
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.claude/skills/codebase-visualizer/scripts
|
||||
```
|
||||
|
||||
Create `~/.claude/skills/codebase-visualizer/SKILL.md`. The description tells Claude when to activate this Skill, and the instructions tell Claude to run the bundled script:
|
||||
|
||||
```bash
|
||||
---
|
||||
name: codebase-visualizer
|
||||
description: Generate an interactive collapsible tree visualization of your codebase. Use when exploring a new repo, understanding project structure, or identifying large files.
|
||||
allowed-tools: Bash(python:*)
|
||||
---
|
||||
|
||||
# Codebase Visualizer
|
||||
|
||||
Generate an interactive HTML tree view that shows your project's file structure with collapsible directories.
|
||||
|
||||
## Usage
|
||||
|
||||
Run the visualization script from your project root:
|
||||
|
||||
```bash
|
||||
python ~/.claude/skills/codebase-visualizer/scripts/visualize.py .
|
||||
```
|
||||
|
||||
This creates `codebase-map.html` in the current directory and opens it in your default browser.
|
||||
|
||||
## What the visualization shows
|
||||
|
||||
- **Collapsible directories**: Click folders to expand/collapse
|
||||
- **File sizes**: Displayed next to each file
|
||||
- **Colors**: Different colors for different file types
|
||||
- **Directory totals**: Shows aggregate size of each folder
|
||||
```
|
||||
|
||||
Create `~/.claude/skills/codebase-visualizer/scripts/visualize.py`. This script scans a directory tree and generates a self-contained HTML file with:
|
||||
|
||||
- A **summary sidebar** showing file count, directory count, total size, and number of file types
|
||||
- A **bar chart** breaking down the codebase by file type (top 8 by size)
|
||||
- A **collapsible tree** where you can expand and collapse directories, with color-coded file type indicators
|
||||
|
||||
The script requires Python but uses only built-in libraries, so there are no packages to install:
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env python3
|
||||
"""Generate an interactive collapsible tree visualization of a codebase."""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import webbrowser
|
||||
from pathlib import Path
|
||||
from collections import Counter
|
||||
|
||||
IGNORE = {'.git', 'node_modules', '__pycache__', '.venv', 'venv', 'dist', 'build'}
|
||||
|
||||
def scan(path: Path, stats: dict) -> dict:
|
||||
result = {"name": path.name, "children": [], "size": 0}
|
||||
try:
|
||||
for item in sorted(path.iterdir()):
|
||||
if item.name in IGNORE or item.name.startswith('.'):
|
||||
continue
|
||||
if item.is_file():
|
||||
size = item.stat().st_size
|
||||
ext = item.suffix.lower() or '(no ext)'
|
||||
result["children"].append({"name": item.name, "size": size, "ext": ext})
|
||||
result["size"] += size
|
||||
stats["files"] += 1
|
||||
stats["extensions"][ext] += 1
|
||||
stats["ext_sizes"][ext] += size
|
||||
elif item.is_dir():
|
||||
stats["dirs"] += 1
|
||||
child = scan(item, stats)
|
||||
if child["children"]:
|
||||
result["children"].append(child)
|
||||
result["size"] += child["size"]
|
||||
except PermissionError:
|
||||
pass
|
||||
return result
|
||||
|
||||
def generate_html(data: dict, stats: dict, output: Path) -> None:
|
||||
ext_sizes = stats["ext_sizes"]
|
||||
total_size = sum(ext_sizes.values()) or 1
|
||||
sorted_exts = sorted(ext_sizes.items(), key=lambda x: -x[1])[:8]
|
||||
colors = {
|
||||
'.js': '#f7df1e', '.ts': '#3178c6', '.py': '#3776ab', '.go': '#00add8',
|
||||
'.rs': '#dea584', '.rb': '#cc342d', '.css': '#264de4', '.html': '#e34c26',
|
||||
'.json': '#6b7280', '.md': '#083fa1', '.yaml': '#cb171e', '.yml': '#cb171e',
|
||||
'.mdx': '#083fa1', '.tsx': '#3178c6', '.jsx': '#61dafb', '.sh': '#4eaa25',
|
||||
}
|
||||
lang_bars = "".join(
|
||||
f'<div class="bar-row"><span class="bar-label">{ext}</span>'
|
||||
f'<div class="bar" style="width:{(size/total_size)*100}%;background:{colors.get(ext,"#6b7280")}"></div>'
|
||||
f'<span class="bar-pct">{(size/total_size)*100:.1f}%</span></div>'
|
||||
for ext, size in sorted_exts
|
||||
)
|
||||
def fmt(b):
|
||||
if b < 1024: return f"{b} B"
|
||||
if b < 1048576: return f"{b/1024:.1f} KB"
|
||||
return f"{b/1048576:.1f} MB"
|
||||
|
||||
html = f'''<!DOCTYPE html>
|
||||
<html><head>
|
||||
<meta charset="utf-8"><title>Codebase Explorer</title>
|
||||
<style>
|
||||
body {{ font: 14px/1.5 system-ui, sans-serif; margin: 0; background: #1a1a2e; color: #eee; }}
|
||||
.container {{ display: flex; height: 100vh; }}
|
||||
.sidebar {{ width: 280px; background: #252542; padding: 20px; border-right: 1px solid #3d3d5c; overflow-y: auto; flex-shrink: 0; }}
|
||||
.main {{ flex: 1; padding: 20px; overflow-y: auto; }}
|
||||
h1 {{ margin: 0 0 10px 0; font-size: 18px; }}
|
||||
h2 {{ margin: 20px 0 10px 0; font-size: 14px; color: #888; text-transform: uppercase; }}
|
||||
.stat {{ display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #3d3d5c; }}
|
||||
.stat-value {{ font-weight: bold; }}
|
||||
.bar-row {{ display: flex; align-items: center; margin: 6px 0; }}
|
||||
.bar-label {{ width: 55px; font-size: 12px; color: #aaa; }}
|
||||
.bar {{ height: 18px; border-radius: 3px; }}
|
||||
.bar-pct {{ margin-left: 8px; font-size: 12px; color: #666; }}
|
||||
.tree {{ list-style: none; padding-left: 20px; }}
|
||||
details {{ cursor: pointer; }}
|
||||
summary {{ padding: 4px 8px; border-radius: 4px; }}
|
||||
summary:hover {{ background: #2d2d44; }}
|
||||
.folder {{ color: #ffd700; }}
|
||||
.file {{ display: flex; align-items: center; padding: 4px 8px; border-radius: 4px; }}
|
||||
.file:hover {{ background: #2d2d44; }}
|
||||
.size {{ color: #888; margin-left: auto; font-size: 12px; }}
|
||||
.dot {{ width: 8px; height: 8px; border-radius: 50%; margin-right: 8px; }}
|
||||
</style>
|
||||
</head><body>
|
||||
<div class="container">
|
||||
<div class="sidebar">
|
||||
<h1>📊 Summary</h1>
|
||||
<div class="stat"><span>Files</span><span class="stat-value">{stats["files"]:,}</span></div>
|
||||
<div class="stat"><span>Directories</span><span class="stat-value">{stats["dirs"]:,}</span></div>
|
||||
<div class="stat"><span>Total size</span><span class="stat-value">{fmt(data["size"])}</span></div>
|
||||
<div class="stat"><span>File types</span><span class="stat-value">{len(stats["extensions"])}</span></div>
|
||||
<h2>By file type</h2>
|
||||
{lang_bars}
|
||||
</div>
|
||||
<div class="main">
|
||||
<h1>📁 {data["name"]}</h1>
|
||||
<ul class="tree" id="root"></ul>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
const data = {json.dumps(data)};
|
||||
const colors = {json.dumps(colors)};
|
||||
function fmt(b) {{ if (b < 1024) return b + ' B'; if (b < 1048576) return (b/1024).toFixed(1) + ' KB'; return (b/1048576).toFixed(1) + ' MB'; }}
|
||||
function render(node, parent) {{
|
||||
if (node.children) {{
|
||||
const det = document.createElement('details');
|
||||
det.open = parent === document.getElementById('root');
|
||||
det.innerHTML = `<summary><span class="folder">📁 ${{node.name}}</span><span class="size">${{fmt(node.size)}}</span></summary>`;
|
||||
const ul = document.createElement('ul'); ul.className = 'tree';
|
||||
node.children.sort((a,b) => (b.children?1:0)-(a.children?1:0) || a.name.localeCompare(b.name));
|
||||
node.children.forEach(c => render(c, ul));
|
||||
det.appendChild(ul);
|
||||
const li = document.createElement('li'); li.appendChild(det); parent.appendChild(li);
|
||||
}} else {{
|
||||
const li = document.createElement('li'); li.className = 'file';
|
||||
li.innerHTML = `<span class="dot" style="background:${{colors[node.ext]||'#6b7280'}}"></span>${{node.name}}<span class="size">${{fmt(node.size)}}</span>`;
|
||||
parent.appendChild(li);
|
||||
}}
|
||||
}}
|
||||
data.children.forEach(c => render(c, document.getElementById('root')));
|
||||
</script>
|
||||
</body></html>'''
|
||||
output.write_text(html)
|
||||
|
||||
if __name__ == '__main__':
|
||||
target = Path(sys.argv[1] if len(sys.argv) > 1 else '.').resolve()
|
||||
stats = {"files": 0, "dirs": 0, "extensions": Counter(), "ext_sizes": Counter()}
|
||||
data = scan(target, stats)
|
||||
out = Path('codebase-map.html')
|
||||
generate_html(data, stats, out)
|
||||
print(f'Generated {out.absolute()}')
|
||||
webbrowser.open(f'file://{out.absolute()}')
|
||||
```
|
||||
|
||||
To test, open Claude Code in any project and ask “Visualize this codebase.” Claude runs the script, generates `codebase-map.html`, and opens it in your browser.
|
||||
This pattern works for any visual output: dependency graphs, test coverage reports, API documentation, or database schema visualizations. The bundled script does the heavy lifting while Claude handles orchestration.
|
||||
|
||||
## [](#troubleshooting) Troubleshooting
|
||||
|
||||
### [](#view-and-test-skills) View and test Skills
|
||||
|
||||
To see which Skills Claude has access to, ask Claude a question like “What Skills are available?” Claude loads all available Skill names and descriptions into the context window when a conversation starts, so it can list the Skills it currently has access to.
|
||||
To test a specific Skill, ask Claude to do a task that matches the Skill’s description. For example, if your Skill has the description “Reviews pull requests for code quality”, ask Claude to “Review the changes in my current branch.” Claude automatically uses the Skill when the request matches its description.
|
||||
|
||||
### [](#skill-not-triggering) Skill not triggering
|
||||
|
||||
The description field is how Claude decides whether to use your Skill. Vague descriptions like “Helps with documents” don’t give Claude enough information to match your Skill to relevant requests.
|
||||
A good description answers two questions:
|
||||
|
||||
1. **What does this Skill do?** List the specific capabilities.
|
||||
2. **When should Claude use it?** Include trigger terms users would mention.
|
||||
|
||||
```bash
|
||||
description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.
|
||||
```
|
||||
|
||||
This description works because it names specific actions (extract, fill, merge) and includes keywords users would say (PDF, forms, document extraction).
|
||||
|
||||
### [](#skill-doesn’t-load) Skill doesn’t load
|
||||
|
||||
**Check the file path.** Skills must be in the correct directory with the exact filename `SKILL.md` (case-sensitive):
|
||||
|
||||
| Type | Path |
|
||||
| --- | --- |
|
||||
| Personal | `~/.claude/skills/my-skill/SKILL.md` |
|
||||
| Project | `.claude/skills/my-skill/SKILL.md` |
|
||||
| Enterprise | See [Where Skills live](#where-skills-live) for platform-specific paths |
|
||||
| Plugin | `skills/my-skill/SKILL.md` inside the plugin directory |
|
||||
|
||||
**Check the YAML syntax.** Invalid YAML in the frontmatter prevents the Skill from loading. The frontmatter must start with `---` on line 1 (no blank lines before it), end with `---` before the Markdown content, and use spaces for indentation (not tabs).
|
||||
**Run debug mode.** Use `claude --debug` to see Skill loading errors.
|
||||
|
||||
### [](#skill-has-errors) Skill has errors
|
||||
|
||||
**Check dependencies are installed.** If your Skill uses external packages, they must be installed in your environment before Claude can use them.
|
||||
**Check script permissions.** Scripts need execute permissions: `chmod +x scripts/*.py`
|
||||
**Check file paths.** Use forward slashes (Unix style) in all paths. Use `scripts/helper.py`, not `scripts\helper.py`.
|
||||
|
||||
### [](#multiple-skills-conflict) Multiple Skills conflict
|
||||
|
||||
If Claude uses the wrong Skill or seems confused between similar Skills, the descriptions are probably too similar. Make each description distinct by using specific trigger terms.
|
||||
For example, instead of two Skills with “data analysis” in both descriptions, differentiate them: one for “sales data in Excel files and CRM exports” and another for “log files and system metrics”. The more specific your trigger terms, the easier it is for Claude to match the right Skill to your request.
|
||||
|
||||
### [](#plugin-skills-not-appearing) Plugin Skills not appearing
|
||||
|
||||
**Symptom**: You installed a plugin from a marketplace, but its Skills don’t appear when you ask Claude “What Skills are available?”
|
||||
**Solution**: Clear the plugin cache and reinstall:
|
||||
|
||||
```bash
|
||||
rm -rf ~/.claude/plugins/cache
|
||||
```
|
||||
|
||||
Then restart Claude Code and reinstall the plugin:
|
||||
|
||||
```bash
|
||||
/plugin install plugin-name@marketplace-name
|
||||
```
|
||||
|
||||
This forces Claude Code to re-download and re-register the plugin’s Skills.
|
||||
**If Skills still don’t appear**, verify the plugin’s directory structure is correct. Skills must be in a `skills/` directory at the plugin root:
|
||||
|
||||
```bash
|
||||
my-plugin/
|
||||
├── .claude-plugin/
|
||||
│ └── plugin.json
|
||||
└── skills/
|
||||
└── my-skill/
|
||||
└── SKILL.md
|
||||
```
|
||||
|
||||
## [](#next-steps) Next steps
|
||||
|
||||
[## Authoring best practices
|
||||
|
||||
Write Skills that Claude can use effectively](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/best-practices)[## Agent Skills overview
|
||||
|
||||
Learn how Skills work across Claude products](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview)[## Use Skills in the Agent SDK
|
||||
|
||||
Use Skills programmatically with TypeScript and Python](https://docs.claude.com/en/docs/agent-sdk/skills)[## Get started with Agent Skills
|
||||
|
||||
Create your first Skill](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/quickstart)
|
||||
@@ -0,0 +1,193 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/slack
|
||||
title: Claude Code in Slack
|
||||
---
|
||||
|
||||
Claude Code in Slack brings the power of Claude Code directly into your Slack workspace. When you mention `@Claude` with a coding task, Claude automatically detects the intent and creates a Claude Code session on the web, allowing you to delegate development work without leaving your team conversations.
|
||||
This integration is built on the existing Claude for Slack app but adds intelligent routing to Claude Code on the web for coding-related requests.
|
||||
|
||||
## [](#use-cases) Use cases
|
||||
|
||||
- **Bug investigation and fixes**: Ask Claude to investigate and fix bugs as soon as they’re reported in Slack channels.
|
||||
- **Quick code reviews and modifications**: Have Claude implement small features or refactor code based on team feedback.
|
||||
- **Collaborative debugging**: When team discussions provide crucial context (e.g., error reproductions or user reports), Claude can use that information to inform its debugging approach.
|
||||
- **Parallel task execution**: Kick off coding tasks in Slack while you continue other work, receiving notifications when complete.
|
||||
|
||||
## [](#prerequisites) Prerequisites
|
||||
|
||||
Before using Claude Code in Slack, ensure you have the following:
|
||||
|
||||
| Requirement | Details |
|
||||
| --- | --- |
|
||||
| Claude Plan | Pro, Max, Team, or Enterprise with Claude Code access (premium seats) |
|
||||
| Claude Code on the web | Access to [Claude Code on the web](/docs/en/claude-code-on-the-web) must be enabled |
|
||||
| GitHub Account | Connected to Claude Code on the web with at least one repository authenticated |
|
||||
| Slack Authentication | Your Slack account linked to your Claude account via the Claude app |
|
||||
|
||||
## [](#setting-up-claude-code-in-slack) Setting up Claude Code in Slack
|
||||
|
||||
1
|
||||
|
||||
Install the Claude App in Slack
|
||||
|
||||
A workspace administrator must install the Claude app from the Slack App Marketplace. Visit the [Slack App Marketplace](https://slack.com/marketplace/A08SF47R6P4) and click “Add to Slack” to begin the installation process.
|
||||
|
||||
2
|
||||
|
||||
Connect your Claude account
|
||||
|
||||
After the app is installed, authenticate your individual Claude account:
|
||||
|
||||
1. Open the Claude app in Slack by clicking on “Claude” in your Apps section
|
||||
2. Navigate to the App Home tab
|
||||
3. Click “Connect” to link your Slack account with your Claude account
|
||||
4. Complete the authentication flow in your browser
|
||||
|
||||
3
|
||||
|
||||
Configure Claude Code on the web
|
||||
|
||||
Ensure your Claude Code on the web is properly configured:
|
||||
|
||||
- Visit [claude.ai/code](https://claude.ai/code) and sign in with the same account you connected to Slack
|
||||
- Connect your GitHub account if not already connected
|
||||
- Authenticate at least one repository that you want Claude to work with
|
||||
|
||||
4
|
||||
|
||||
Choose your routing mode
|
||||
|
||||
After connecting your accounts, configure how Claude handles your messages in Slack. Navigate to the Claude App Home in Slack to find the **Routing Mode** setting.
|
||||
|
||||
| Mode | Behavior |
|
||||
| --- | --- |
|
||||
| **Code only** | Claude routes all @mentions to Claude Code sessions. Best for teams using Claude in Slack exclusively for development tasks. |
|
||||
| **Code + Chat** | Claude analyzes each message and intelligently routes between Claude Code (for coding tasks) and Claude Chat (for writing, analysis, and general questions). Best for teams who want a single @Claude entry point for all types of work. |
|
||||
|
||||
In Code + Chat mode, if Claude routes a message to Chat but you wanted a coding session, you can click “Retry as Code” to create a Claude Code session instead. Similarly, if it’s routed to Code but you wanted a Chat session, you can choose that option in that thread.
|
||||
|
||||
## [](#how-it-works) How it works
|
||||
|
||||
### [](#automatic-detection) Automatic detection
|
||||
|
||||
When you mention @Claude in a Slack channel or thread, Claude automatically analyzes your message to determine if it’s a coding task. If Claude detects coding intent, it will route your request to Claude Code on the web instead of responding as a regular chat assistant.
|
||||
You can also explicitly tell Claude to handle a request as a coding task, even if it doesn’t automatically detect it.
|
||||
|
||||
Claude Code in Slack only works in channels (public or private). It does not work in direct messages (DMs).
|
||||
|
||||
### [](#context-gathering) Context gathering
|
||||
|
||||
**From threads**: When you @mention Claude in a thread, it gathers context from all messages in that thread to understand the full conversation.
|
||||
**From channels**: When mentioned directly in a channel, Claude looks at recent channel messages for relevant context.
|
||||
This context helps Claude understand the problem, select the appropriate repository, and inform its approach to the task.
|
||||
|
||||
When @Claude is invoked in Slack, Claude is given access to the conversation context to better understand your request. Claude may follow directions from other messages in the context, so users should make sure to only use Claude in trusted Slack conversations.
|
||||
|
||||
### [](#session-flow) Session flow
|
||||
|
||||
1. **Initiation**: You @mention Claude with a coding request
|
||||
2. **Detection**: Claude analyzes your message and detects coding intent
|
||||
3. **Session creation**: A new Claude Code session is created on claude.ai/code
|
||||
4. **Progress updates**: Claude posts status updates to your Slack thread as work progresses
|
||||
5. **Completion**: When finished, Claude @mentions you with a summary and action buttons
|
||||
6. **Review**: Click “View Session” to see the full transcript, or “Create PR” to open a pull request
|
||||
|
||||
## [](#user-interface-elements) User interface elements
|
||||
|
||||
### [](#app-home) App Home
|
||||
|
||||
The App Home tab shows your connection status and allows you to connect or disconnect your Claude account from Slack.
|
||||
|
||||
### [](#message-actions) Message actions
|
||||
|
||||
- **View Session**: Opens the full Claude Code session in your browser where you can see all work performed, continue the session, or make additional requests.
|
||||
- **Create PR**: Creates a pull request directly from the session’s changes.
|
||||
- **Retry as Code**: If Claude initially responds as a chat assistant but you wanted a coding session, click this button to retry the request as a Claude Code task.
|
||||
- **Change Repo**: Allows you to select a different repository if Claude chose incorrectly.
|
||||
|
||||
### [](#repository-selection) Repository selection
|
||||
|
||||
Claude automatically selects a repository based on context from your Slack conversation. If multiple repositories could apply, Claude may display a dropdown allowing you to choose the correct one.
|
||||
|
||||
## [](#access-and-permissions) Access and permissions
|
||||
|
||||
### [](#user-level-access) User-level access
|
||||
|
||||
| Access Type | Requirement |
|
||||
| --- | --- |
|
||||
| Claude Code Sessions | Each user runs sessions under their own Claude account |
|
||||
| Usage & Rate Limits | Sessions count against the individual user’s plan limits |
|
||||
| Repository Access | Users can only access repositories they’ve personally connected |
|
||||
| Session History | Sessions appear in your Claude Code history on claude.ai/code |
|
||||
|
||||
### [](#workspace-admin-permissions) Workspace admin permissions
|
||||
|
||||
Slack workspace administrators control whether the Claude app can be installed in the workspace. Individual users then authenticate with their own Claude accounts to use the integration.
|
||||
|
||||
## [](#what’s-accessible-where) What’s accessible where
|
||||
|
||||
**In Slack**: You’ll see status updates, completion summaries, and action buttons. The full transcript is preserved and always accessible.
|
||||
**On the web**: The complete Claude Code session with full conversation history, all code changes, file operations, and the ability to continue the session or create pull requests.
|
||||
|
||||
## [](#best-practices) Best practices
|
||||
|
||||
### [](#writing-effective-requests) Writing effective requests
|
||||
|
||||
- **Be specific**: Include file names, function names, or error messages when relevant.
|
||||
- **Provide context**: Mention the repository or project if it’s not clear from the conversation.
|
||||
- **Define success**: Explain what “done” looks like—should Claude write tests? Update documentation? Create a PR?
|
||||
- **Use threads**: Reply in threads when discussing bugs or features so Claude can gather the full context.
|
||||
|
||||
### [](#when-to-use-slack-vs-web) When to use Slack vs. web
|
||||
|
||||
**Use Slack when**: Context already exists in a Slack discussion, you want to kick off a task asynchronously, or you’re collaborating with teammates who need visibility.
|
||||
**Use the web directly when**: You need to upload files, want real-time interaction during development, or are working on longer, more complex tasks.
|
||||
|
||||
## [](#troubleshooting) Troubleshooting
|
||||
|
||||
### [](#sessions-not-starting) Sessions not starting
|
||||
|
||||
1. Verify your Claude account is connected in the Claude App Home
|
||||
2. Check that you have Claude Code on the web access enabled
|
||||
3. Ensure you have at least one GitHub repository connected to Claude Code
|
||||
|
||||
### [](#repository-not-showing) Repository not showing
|
||||
|
||||
1. Connect the repository in Claude Code on the web at [claude.ai/code](https://claude.ai/code)
|
||||
2. Verify your GitHub permissions for that repository
|
||||
3. Try disconnecting and reconnecting your GitHub account
|
||||
|
||||
### [](#wrong-repository-selected) Wrong repository selected
|
||||
|
||||
1. Click the “Change Repo” button to select a different repository
|
||||
2. Include the repository name in your request for more accurate selection
|
||||
|
||||
### [](#authentication-errors) Authentication errors
|
||||
|
||||
1. Disconnect and reconnect your Claude account in the App Home
|
||||
2. Ensure you’re signed into the correct Claude account in your browser
|
||||
3. Check that your Claude plan includes Claude Code access
|
||||
|
||||
### [](#session-expiration) Session expiration
|
||||
|
||||
1. Sessions remain accessible in your Claude Code history on the web
|
||||
2. You can continue or reference past sessions from [claude.ai/code](https://claude.ai/code)
|
||||
|
||||
## [](#current-limitations) Current limitations
|
||||
|
||||
- **GitHub only**: Currently supports repositories on GitHub.
|
||||
- **One PR at a time**: Each session can create one pull request.
|
||||
- **Rate limits apply**: Sessions use your individual Claude plan’s rate limits.
|
||||
- **Web access required**: Users must have Claude Code on the web access; those without it will only get standard Claude chat responses.
|
||||
|
||||
## [](#related-resources) Related resources
|
||||
|
||||
[## Claude Code on the web
|
||||
|
||||
Learn more about Claude Code on the web](/docs/en/claude-code-on-the-web)[## Claude for Slack
|
||||
|
||||
General Claude for Slack documentation](https://claude.com/claude-and-slack)[## Slack App Marketplace
|
||||
|
||||
Install the Claude app from the Slack Marketplace](https://slack.com/marketplace/A08SF47R6P4)[## Claude Help Center
|
||||
|
||||
Get additional support](https://support.claude.com)
|
||||
@@ -0,0 +1,536 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/slash-commands
|
||||
title: Slash commands
|
||||
---
|
||||
|
||||
## [](#built-in-slash-commands) Built-in slash commands
|
||||
|
||||
| Command | Purpose |
|
||||
| --- | --- |
|
||||
| `/add-dir` | Add additional working directories |
|
||||
| `/agents` | Manage custom AI subagents for specialized tasks |
|
||||
| `/bashes` | List and manage background tasks |
|
||||
| `/bug` | Report bugs (sends conversation to Anthropic) |
|
||||
| `/clear` | Clear conversation history |
|
||||
| `/compact [instructions]` | Compact conversation with optional focus instructions |
|
||||
| `/config` | Open the Settings interface (Config tab). Type to search and filter settings |
|
||||
| `/context` | Visualize current context usage as a colored grid |
|
||||
| `/cost` | Show token usage statistics. See [cost tracking guide](/docs/en/costs#using-the-cost-command) for subscription-specific details. |
|
||||
| `/doctor` | Run diagnostics to check installation health, detect configuration issues (invalid settings, MCP errors, keybinding problems), and identify context usage warnings (large CLAUDE.md files, high MCP token usage) |
|
||||
| `/exit` | Exit the REPL |
|
||||
| `/export [filename]` | Export the current conversation to a file or clipboard |
|
||||
| `/help` | Get usage help |
|
||||
| `/hooks` | Manage hook configurations for tool events |
|
||||
| `/ide` | Manage IDE integrations and show status |
|
||||
| `/init` | Initialize project with `CLAUDE.md` guide |
|
||||
| `/install-github-app` | Set up Claude GitHub Actions for a repository |
|
||||
| `/login` | Switch Anthropic accounts |
|
||||
| `/logout` | Sign out from your Anthropic account |
|
||||
| `/mcp` | Manage MCP server connections and OAuth authentication |
|
||||
| `/memory` | Edit `CLAUDE.md` memory files |
|
||||
| `/model` | Select or change the AI model |
|
||||
| `/output-style [style]` | Set the output style directly or from a selection menu |
|
||||
| `/permissions` | View or update [permissions](/docs/en/iam#configuring-permissions) |
|
||||
| `/plan` | Enter plan mode directly from the prompt |
|
||||
| `/plugin` | Manage Claude Code plugins |
|
||||
| `/pr-comments` | View pull request comments |
|
||||
| `/privacy-settings` | View and update your privacy settings |
|
||||
| `/release-notes` | View release notes |
|
||||
| `/rename <name>` | Rename the current session for easier identification |
|
||||
| `/remote-env` | Configure remote session environment (claude.ai subscribers) |
|
||||
| `/resume [session]` | Resume a conversation by ID or name, or open the session picker |
|
||||
| `/review` | Request code review |
|
||||
| `/rewind` | Rewind the conversation and/or code |
|
||||
| `/sandbox` | Enable sandboxed bash tool with filesystem and network isolation for safer, more autonomous execution |
|
||||
| `/security-review` | Complete a security review of pending changes on the current branch |
|
||||
| `/stats` | Visualize daily usage, session history, streaks, and model preferences. Press `r` to cycle date ranges (Last 7 days, Last 30 days, All time) |
|
||||
| `/status` | Open the Settings interface (Status tab) showing version, model, account, and connectivity |
|
||||
| `/statusline` | Set up Claude Code’s status line UI |
|
||||
| `/teleport` | Resume a remote session from claude.ai by session ID, or open a picker (claude.ai subscribers) |
|
||||
| `/terminal-setup` | Install Shift+Enter key binding for newlines (VS Code, Alacritty, Zed, Warp) |
|
||||
| `/theme` | Change the color theme |
|
||||
| `/todos` | List current TODO items |
|
||||
| `/usage` | For subscription plans only: show plan usage limits and rate limit status |
|
||||
| `/vim` | Enter vim mode for alternating insert and command modes |
|
||||
|
||||
## [](#custom-slash-commands) Custom slash commands
|
||||
|
||||
Custom slash commands allow you to define frequently used prompts as Markdown files that Claude Code can execute. Commands are organized by scope (project-specific or personal) and support namespacing through directory structures.
|
||||
|
||||
Slash command autocomplete works anywhere in your input, not just at the beginning. Type `/` at any position to see available commands.
|
||||
|
||||
### [](#syntax) Syntax
|
||||
|
||||
```bash
|
||||
/<command-name> [arguments]
|
||||
```
|
||||
|
||||
#### [](#parameters) Parameters
|
||||
|
||||
| Parameter | Description |
|
||||
| --- | --- |
|
||||
| `<command-name>` | Name derived from the Markdown filename (without `.md` extension) |
|
||||
| `[arguments]` | Optional arguments passed to the command |
|
||||
|
||||
### [](#command-types) Command types
|
||||
|
||||
#### [](#project-commands) Project commands
|
||||
|
||||
Commands stored in your repository and shared with your team. When listed in `/help`, these commands show “(project)” after their description.
|
||||
**Location**: `.claude/commands/`
|
||||
The following example creates the `/optimize` command:
|
||||
|
||||
```bash
|
||||
# Create a project command
|
||||
mkdir -p .claude/commands
|
||||
echo "Analyze this code for performance issues and suggest optimizations:" > .claude/commands/optimize.md
|
||||
```
|
||||
|
||||
#### [](#personal-commands) Personal commands
|
||||
|
||||
Commands available across all your projects. When listed in `/help`, these commands show “(user)” after their description.
|
||||
**Location**: `~/.claude/commands/`
|
||||
The following example creates the `/security-review` command:
|
||||
|
||||
```bash
|
||||
# Create a personal command
|
||||
mkdir -p ~/.claude/commands
|
||||
echo "Review this code for security vulnerabilities:" > ~/.claude/commands/security-review.md
|
||||
```
|
||||
|
||||
### [](#features) Features
|
||||
|
||||
#### [](#namespacing) Namespacing
|
||||
|
||||
Use subdirectories to group related commands. Subdirectories appear in the command description but don’t affect the command name.
|
||||
For example:
|
||||
|
||||
- `.claude/commands/frontend/component.md` creates `/component` with description “(project:frontend)”
|
||||
- `~/.claude/commands/component.md` creates `/component` with description “(user)”
|
||||
|
||||
If a project command and user command share the same name, the project command takes precedence and the user command is silently ignored. For example, if both `.claude/commands/deploy.md` and `~/.claude/commands/deploy.md` exist, `/deploy` runs the project version.
|
||||
Commands in different subdirectories can share names since the subdirectory appears in the description to distinguish them. For example, `.claude/commands/frontend/test.md` and `.claude/commands/backend/test.md` both create `/test`, but show as “(project:frontend)” and “(project:backend)” respectively.
|
||||
|
||||
#### [](#arguments) Arguments
|
||||
|
||||
Pass dynamic values to commands using argument placeholders:
|
||||
|
||||
##### All arguments with `$ARGUMENTS`
|
||||
|
||||
The `$ARGUMENTS` placeholder captures all arguments passed to the command:
|
||||
|
||||
```bash
|
||||
# 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
|
||||
# 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) 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:
|
||||
|
||||
```bash
|
||||
---
|
||||
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) File references
|
||||
|
||||
Include file contents in commands using the `@` prefix to [reference files](/docs/en/common-workflows#reference-files-and-directories).
|
||||
For example:
|
||||
|
||||
```bash
|
||||
# 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) Thinking mode
|
||||
|
||||
Slash commands can trigger extended thinking by including [extended thinking keywords](/docs/en/common-workflows#use-extended-thinking).
|
||||
|
||||
### [](#frontmatter) 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 |
|
||||
| `context` | Set to `fork` to run the command in a forked sub-agent context with its own conversation history. | Inline (no fork) |
|
||||
| `agent` | Specify which [agent type](/docs/en/sub-agents#built-in-subagents) to use when `context: fork` is set. Only applicable when combined with `context: fork`. | `general-purpose` |
|
||||
| `description` | Brief description of the command | Uses the first line from the prompt |
|
||||
| `model` | Specific model string (see [Models overview](https://docs.claude.com/en/docs/about-claude/models/overview)) | Inherits from the conversation |
|
||||
| `disable-model-invocation` | Whether to prevent the `Skill` tool from calling this command | false |
|
||||
| `hooks` | Define hooks scoped to this command’s execution. See [Define hooks for commands](#define-hooks-for-commands). | None |
|
||||
|
||||
For example:
|
||||
|
||||
```bash
|
||||
---
|
||||
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:
|
||||
|
||||
```bash
|
||||
---
|
||||
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.
|
||||
```
|
||||
|
||||
#### [](#define-hooks-for-commands) Define hooks for commands
|
||||
|
||||
Slash commands can define hooks that run during the command’s execution. Use the `hooks` field to specify `PreToolUse`, `PostToolUse`, or `Stop` handlers:
|
||||
|
||||
```bash
|
||||
---
|
||||
description: Deploy to staging with validation
|
||||
hooks:
|
||||
PreToolUse:
|
||||
- matcher: "Bash"
|
||||
hooks:
|
||||
- type: command
|
||||
command: "./scripts/validate-deploy.sh"
|
||||
once: true
|
||||
---
|
||||
|
||||
Deploy the current branch to staging environment.
|
||||
```
|
||||
|
||||
The `once: true` option runs the hook only once per session. After the first successful execution, the hook is removed.
|
||||
Hooks defined in a command are scoped to that command’s execution and are automatically cleaned up when the command finishes.
|
||||
See [Hooks](/docs/en/hooks) for the complete hook configuration format.
|
||||
|
||||
## [](#plugin-commands) Plugin commands
|
||||
|
||||
[Plugins](/docs/en/plugins) can provide custom slash commands that integrate seamlessly with Claude Code. Plugin commands work exactly like user-defined commands but are distributed through [plugin marketplaces](/docs/en/plugin-marketplaces).
|
||||
|
||||
### [](#how-plugin-commands-work) 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) Plugin command structure
|
||||
|
||||
**Location**: `commands/` directory in plugin root
|
||||
**File format**: Markdown files with frontmatter
|
||||
**Basic command structure**:
|
||||
|
||||
```bash
|
||||
---
|
||||
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) Invocation patterns
|
||||
|
||||
Direct command (when no conflicts)
|
||||
|
||||
```bash
|
||||
/command-name
|
||||
```
|
||||
|
||||
Plugin-prefixed (when needed for disambiguation)
|
||||
|
||||
```bash
|
||||
/plugin-name:command-name
|
||||
```
|
||||
|
||||
With arguments (if command supports them)
|
||||
|
||||
```bash
|
||||
/command-name arg1 arg2
|
||||
```
|
||||
|
||||
## [](#mcp-slash-commands) 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) Command format
|
||||
|
||||
MCP commands follow the pattern:
|
||||
|
||||
```bash
|
||||
/mcp__<server-name>__<prompt-name> [arguments]
|
||||
```
|
||||
|
||||
### [](#features-2) Features
|
||||
|
||||
#### [](#dynamic-discovery) 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-2) Arguments
|
||||
|
||||
MCP prompts can accept arguments defined by the server:
|
||||
|
||||
```bash
|
||||
# Without arguments
|
||||
> /mcp__github__list_prs
|
||||
|
||||
# With arguments
|
||||
> /mcp__github__pr_review 456
|
||||
> /mcp__jira__create_issue "Bug title" high
|
||||
```
|
||||
|
||||
#### [](#naming-conventions) Naming conventions
|
||||
|
||||
Server and prompt names are normalized:
|
||||
|
||||
- Spaces and special characters become underscores
|
||||
- Names are lowercase for consistency
|
||||
|
||||
### [](#managing-mcp-connections) 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) MCP permissions and wildcards
|
||||
|
||||
To approve all tools from an MCP server, use either the server name alone or wildcard syntax:
|
||||
|
||||
- `mcp__github` (approves all GitHub tools)
|
||||
- `mcp__github__*` (wildcard syntax, also approves all GitHub tools)
|
||||
|
||||
To approve specific tools, list each one explicitly:
|
||||
|
||||
- `mcp__github__get_issue`
|
||||
- `mcp__github__list_issues`
|
||||
|
||||
See [MCP permission rules](/docs/en/iam#tool-specific-permission-rules) for more details.
|
||||
|
||||
## [](#skill-tool) `Skill` tool
|
||||
|
||||
In earlier versions of Claude Code, slash command invocation was provided by a separate `SlashCommand` tool. This has been merged into the `Skill` tool.
|
||||
|
||||
The `Skill` tool allows Claude to programmatically invoke both [custom slash commands](/docs/en/slash-commands#custom-slash-commands) and [Agent Skills](/docs/en/skills) during a conversation. This gives Claude the ability to use these capabilities on your behalf when appropriate.
|
||||
|
||||
### [](#what-the-skill-tool-can-invoke) What the `Skill` tool can invoke
|
||||
|
||||
The `Skill` tool provides access to:
|
||||
|
||||
| Type | Location | Requirements |
|
||||
| --- | --- | --- |
|
||||
| Custom slash commands | `.claude/commands/` or `~/.claude/commands/` | Must have `description` frontmatter |
|
||||
| Agent Skills | `.claude/skills/` or `~/.claude/skills/` | Must not have `disable-model-invocation: true` |
|
||||
|
||||
Built-in commands like `/compact` and `/init` are *not* available through this tool.
|
||||
|
||||
### [](#encourage-claude-to-use-specific-commands) Encourage Claude to use specific commands
|
||||
|
||||
To encourage Claude to use the `Skill` tool, reference the command by name, including the slash, in your prompts or `CLAUDE.md` file:
|
||||
|
||||
```bash
|
||||
> Run /write-unit-test when you are about to start writing tests.
|
||||
```
|
||||
|
||||
This tool puts each available command’s metadata into context up to the character budget limit. Use `/context` to monitor token usage.
|
||||
To see which commands and Skills are available to the `Skill` tool, run `claude --debug` and trigger a query.
|
||||
|
||||
### [](#disable-the-skill-tool) Disable the `Skill` tool
|
||||
|
||||
To prevent Claude from programmatically invoking any commands or Skills:
|
||||
|
||||
```bash
|
||||
/permissions
|
||||
# Add to deny rules: Skill
|
||||
```
|
||||
|
||||
This removes the `Skill` tool and all command/Skill descriptions from context.
|
||||
|
||||
### [](#disable-specific-commands-or-skills) Disable specific commands or Skills
|
||||
|
||||
To prevent a specific command or Skill from being invoked programmatically via the `Skill` tool, add `disable-model-invocation: true` to its frontmatter. This also removes the item’s metadata from context.
|
||||
|
||||
The `user-invocable` field in Skills only controls menu visibility, not `Skill` tool access. Use `disable-model-invocation: true` to block programmatic invocation. See [Control Skill visibility](/docs/en/skills#control-skill-visibility) for details.
|
||||
|
||||
### [](#skill-permission-rules) `Skill` permission rules
|
||||
|
||||
The permission rules support:
|
||||
|
||||
- **Exact match**: `Skill(commit)` (allows only `commit` with no arguments)
|
||||
- **Prefix match**: `Skill(review-pr:*)` (allows `review-pr` with any arguments)
|
||||
|
||||
### [](#character-budget-limit) Character budget limit
|
||||
|
||||
The `Skill` tool includes a character budget to limit context usage. This prevents token overflow when many commands and Skills are available.
|
||||
The budget includes each item’s name, arguments, and description.
|
||||
|
||||
- **Default limit**: 15,000 characters
|
||||
- **Custom limit**: Set via `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable. The name is retained for backwards compatibility.
|
||||
|
||||
When the budget is exceeded, Claude sees only a subset of available items. In `/context`, a warning shows how many are included.
|
||||
|
||||
## [](#skills-vs-slash-commands) Skills vs slash commands
|
||||
|
||||
**Slash commands** and **Agent Skills** serve different purposes in Claude Code:
|
||||
|
||||
### [](#use-slash-commands-for) 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) 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) 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) Example comparison
|
||||
|
||||
**As a slash command**:
|
||||
|
||||
```bash
|
||||
# .claude/commands/review.md
|
||||
Review this code for:
|
||||
- Security vulnerabilities
|
||||
- Performance issues
|
||||
- Code style violations
|
||||
```
|
||||
|
||||
Usage: `/review` (manual invocation)
|
||||
**As a Skill**:
|
||||
|
||||
```bash
|
||||
.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) 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](/docs/en/skills).
|
||||
|
||||
## [](#see-also) See also
|
||||
|
||||
- [Plugins](/docs/en/plugins) - Extend Claude Code with custom commands through plugins
|
||||
- [Identity and Access Management](/docs/en/iam) - Complete guide to permissions, including MCP tool permissions
|
||||
- [Interactive mode](/docs/en/interactive-mode) - Shortcuts, input modes, and interactive features
|
||||
- [CLI reference](/docs/en/cli-reference) - Command-line flags and options
|
||||
- [Settings](/docs/en/settings) - Configuration options
|
||||
- [Memory management](/docs/en/memory) - Managing Claude’s memory across sessions
|
||||
@@ -0,0 +1,264 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/statusline
|
||||
title: Status line configuration
|
||||
---
|
||||
|
||||
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) 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`:
|
||||
|
||||
```bash
|
||||
{
|
||||
"statusLine": {
|
||||
"type": "command",
|
||||
"command": "~/.claude/statusline.sh",
|
||||
"padding": 0 // Optional: set to 0 to let status line go to edge
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## [](#how-it-works) How it Works
|
||||
|
||||
- The status line is updated when the conversation messages update
|
||||
- Updates run at most every 300 ms
|
||||
- The first line of stdout from your command becomes the status line text
|
||||
- ANSI color codes are supported for styling your status line
|
||||
- Claude Code passes contextual information about the current session (model, directories, etc.) as JSON to your script via stdin
|
||||
|
||||
## [](#json-input-structure) JSON Input Structure
|
||||
|
||||
Your status line command receives structured data via stdin in JSON format:
|
||||
|
||||
```bash
|
||||
{
|
||||
"hook_event_name": "Status",
|
||||
"session_id": "abc123...",
|
||||
"transcript_path": "/path/to/transcript.json",
|
||||
"cwd": "/current/working/directory",
|
||||
"model": {
|
||||
"id": "claude-opus-4-1",
|
||||
"display_name": "Opus"
|
||||
},
|
||||
"workspace": {
|
||||
"current_dir": "/current/working/directory",
|
||||
"project_dir": "/original/project/directory"
|
||||
},
|
||||
"version": "1.0.80",
|
||||
"output_style": {
|
||||
"name": "default"
|
||||
},
|
||||
"cost": {
|
||||
"total_cost_usd": 0.01234,
|
||||
"total_duration_ms": 45000,
|
||||
"total_api_duration_ms": 2300,
|
||||
"total_lines_added": 156,
|
||||
"total_lines_removed": 23
|
||||
},
|
||||
"context_window": {
|
||||
"total_input_tokens": 15234,
|
||||
"total_output_tokens": 4521,
|
||||
"context_window_size": 200000,
|
||||
"used_percentage": 42.5,
|
||||
"remaining_percentage": 57.5,
|
||||
"current_usage": {
|
||||
"input_tokens": 8500,
|
||||
"output_tokens": 1200,
|
||||
"cache_creation_input_tokens": 5000,
|
||||
"cache_read_input_tokens": 2000
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## [](#example-scripts) Example Scripts
|
||||
|
||||
### [](#simple-status-line) Simple Status Line
|
||||
|
||||
```bash
|
||||
#!/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) Git-Aware Status Line
|
||||
|
||||
```bash
|
||||
#!/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 Example
|
||||
|
||||
```bash
|
||||
#!/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) Node.js Example
|
||||
|
||||
```bash
|
||||
#!/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) Helper Function Approach
|
||||
|
||||
For more complex bash scripts, you can create helper functions:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# Read JSON input once
|
||||
input=$(cat)
|
||||
|
||||
# Helper functions for common extractions
|
||||
get_model_name() { echo "$input" | jq -r '.model.display_name'; }
|
||||
get_current_dir() { echo "$input" | jq -r '.workspace.current_dir'; }
|
||||
get_project_dir() { echo "$input" | jq -r '.workspace.project_dir'; }
|
||||
get_version() { echo "$input" | jq -r '.version'; }
|
||||
get_cost() { echo "$input" | jq -r '.cost.total_cost_usd'; }
|
||||
get_duration() { echo "$input" | jq -r '.cost.total_duration_ms'; }
|
||||
get_lines_added() { echo "$input" | jq -r '.cost.total_lines_added'; }
|
||||
get_lines_removed() { echo "$input" | jq -r '.cost.total_lines_removed'; }
|
||||
get_input_tokens() { echo "$input" | jq -r '.context_window.total_input_tokens'; }
|
||||
get_output_tokens() { echo "$input" | jq -r '.context_window.total_output_tokens'; }
|
||||
get_context_window_size() { echo "$input" | jq -r '.context_window.context_window_size'; }
|
||||
|
||||
# Use the helpers
|
||||
MODEL=$(get_model_name)
|
||||
DIR=$(get_current_dir)
|
||||
echo "[$MODEL] 📁 ${DIR##*/}"
|
||||
```
|
||||
|
||||
### [](#context-window-usage) Context Window Usage
|
||||
|
||||
Display the percentage of context window consumed. The `context_window` object contains:
|
||||
|
||||
- `total_input_tokens` / `total_output_tokens`: Cumulative totals across the entire session
|
||||
- `used_percentage`: Pre-calculated percentage of context window used (0-100)
|
||||
- `remaining_percentage`: Pre-calculated percentage of context window remaining (0-100)
|
||||
- `current_usage`: Current context window usage from the last API call (may be `null` if no messages yet)
|
||||
- `input_tokens`: Input tokens in current context
|
||||
- `output_tokens`: Output tokens generated
|
||||
- `cache_creation_input_tokens`: Tokens written to cache
|
||||
- `cache_read_input_tokens`: Tokens read from cache
|
||||
|
||||
You can use the pre-calculated `used_percentage` and `remaining_percentage` fields directly, or calculate from `current_usage` for more control.
|
||||
**Simple approach using pre-calculated percentages:**
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
input=$(cat)
|
||||
|
||||
MODEL=$(echo "$input" | jq -r '.model.display_name')
|
||||
PERCENT_USED=$(echo "$input" | jq -r '.context_window.used_percentage // 0')
|
||||
|
||||
echo "[$MODEL] Context: ${PERCENT_USED}%"
|
||||
```
|
||||
|
||||
**Advanced approach with manual calculation:**
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
input=$(cat)
|
||||
|
||||
MODEL=$(echo "$input" | jq -r '.model.display_name')
|
||||
CONTEXT_SIZE=$(echo "$input" | jq -r '.context_window.context_window_size')
|
||||
USAGE=$(echo "$input" | jq '.context_window.current_usage')
|
||||
|
||||
if [ "$USAGE" != "null" ]; then
|
||||
# Calculate current context from current_usage fields
|
||||
CURRENT_TOKENS=$(echo "$USAGE" | jq '.input_tokens + .cache_creation_input_tokens + .cache_read_input_tokens')
|
||||
PERCENT_USED=$((CURRENT_TOKENS * 100 / CONTEXT_SIZE))
|
||||
echo "[$MODEL] Context: ${PERCENT_USED}%"
|
||||
else
|
||||
echo "[$MODEL] Context: 0%"
|
||||
fi
|
||||
```
|
||||
|
||||
## [](#tips) 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) Troubleshooting
|
||||
|
||||
- If your status line doesn’t appear, check that your script is executable (`chmod +x`)
|
||||
- Ensure your script outputs to stdout (not stderr)
|
||||
@@ -0,0 +1,690 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/sub-agents
|
||||
title: Create custom subagents
|
||||
---
|
||||
|
||||
Subagents are specialized AI assistants that handle specific types of tasks. Each subagent runs in its own context window with a custom system prompt, specific tool access, and independent permissions. When Claude encounters a task that matches a subagent’s description, it delegates to that subagent, which works independently and returns results.
|
||||
Subagents help you:
|
||||
|
||||
- **Preserve context** by keeping exploration and implementation out of your main conversation
|
||||
- **Enforce constraints** by limiting which tools a subagent can use
|
||||
- **Reuse configurations** across projects with user-level subagents
|
||||
- **Specialize behavior** with focused system prompts for specific domains
|
||||
- **Control costs** by routing tasks to faster, cheaper models like Haiku
|
||||
|
||||
Claude uses each subagent’s description to decide when to delegate tasks. When you create a subagent, write a clear description so Claude knows when to use it.
|
||||
Claude Code includes several built-in subagents like **Explore**, **Plan**, and **general-purpose**. You can also create custom subagents to handle specific tasks. This page covers the [built-in subagents](#built-in-subagents), [how to create your own](#quickstart-create-your-first-subagent), [full configuration options](#configure-subagents), [patterns for working with subagents](#work-with-subagents), and [example subagents](#example-subagents).
|
||||
|
||||
## [](#built-in-subagents) Built-in subagents
|
||||
|
||||
Claude Code includes built-in subagents that Claude automatically uses when appropriate. Each inherits the parent conversation’s permissions with additional tool restrictions.
|
||||
|
||||
- Explore
|
||||
- Plan
|
||||
- General-purpose
|
||||
- Other
|
||||
|
||||
A fast, read-only agent optimized for searching and analyzing codebases.
|
||||
|
||||
- **Model**: Haiku (fast, low-latency)
|
||||
- **Tools**: Read-only tools (denied access to Write and Edit tools)
|
||||
- **Purpose**: File discovery, code search, codebase exploration
|
||||
|
||||
Claude delegates to Explore when it needs to search or understand a codebase without making changes. This keeps exploration results out of your main conversation context.When invoking Explore, Claude specifies a thoroughness level: **quick** for targeted lookups, **medium** for balanced exploration, or **very thorough** for comprehensive analysis.
|
||||
|
||||
A research agent used during [plan mode](/docs/en/common-workflows#use-plan-mode-for-safe-code-analysis) to gather context before presenting a plan.
|
||||
|
||||
- **Model**: Inherits from main conversation
|
||||
- **Tools**: Read-only tools (denied access to Write and Edit tools)
|
||||
- **Purpose**: Codebase research for planning
|
||||
|
||||
When you’re in plan mode and Claude needs to understand your codebase, it delegates research to the Plan subagent. This prevents infinite nesting (subagents cannot spawn other subagents) while still gathering necessary context.
|
||||
|
||||
A capable agent for complex, multi-step tasks that require both exploration and action.
|
||||
|
||||
- **Model**: Inherits from main conversation
|
||||
- **Tools**: All tools
|
||||
- **Purpose**: Complex research, multi-step operations, code modifications
|
||||
|
||||
Claude delegates to general-purpose when the task requires both exploration and modification, complex reasoning to interpret results, or multiple dependent steps.
|
||||
|
||||
Claude Code includes additional helper agents for specific tasks. These are typically invoked automatically, so you don’t need to use them directly.
|
||||
|
||||
| Agent | Model | When Claude uses it |
|
||||
| --- | --- | --- |
|
||||
| Bash | Inherits | Running terminal commands in a separate context |
|
||||
| statusline-setup | Sonnet | When you run `/statusline` to configure your status line |
|
||||
| Claude Code Guide | Haiku | When you ask questions about Claude Code features |
|
||||
|
||||
Beyond these built-in subagents, you can create your own with custom prompts, tool restrictions, permission modes, hooks, and skills. The following sections show how to get started and customize subagents.
|
||||
|
||||
## [](#quickstart:-create-your-first-subagent) Quickstart: create your first subagent
|
||||
|
||||
Subagents are defined in Markdown files with YAML frontmatter. You can [create them manually](#write-subagent-files) or use the `/agents` slash command.
|
||||
This walkthrough guides you through creating a user-level subagent with the `/agent` command. The subagent reviews code and suggests improvements for the codebase.
|
||||
|
||||
1
|
||||
|
||||
Open the subagents interface
|
||||
|
||||
In Claude Code, run:
|
||||
|
||||
```bash
|
||||
/agents
|
||||
```
|
||||
|
||||
2
|
||||
|
||||
Create a new user-level agent
|
||||
|
||||
Select **Create new agent**, then choose **User-level**. This saves the subagent to `~/.claude/agents/` so it’s available in all your projects.
|
||||
|
||||
3
|
||||
|
||||
Generate with Claude
|
||||
|
||||
Select **Generate with Claude**. When prompted, describe the subagent:
|
||||
|
||||
```bash
|
||||
A code improvement agent that scans files and suggests improvements
|
||||
for readability, performance, and best practices. It should explain
|
||||
each issue, show the current code, and provide an improved version.
|
||||
```
|
||||
|
||||
Claude generates the system prompt and configuration. Press `e` to open it in your editor if you want to customize it.
|
||||
|
||||
4
|
||||
|
||||
Select tools
|
||||
|
||||
For a read-only reviewer, deselect everything except **Read-only tools**. If you keep all tools selected, the subagent inherits all tools available to the main conversation.
|
||||
|
||||
5
|
||||
|
||||
Select model
|
||||
|
||||
Choose which model the subagent uses. For this example agent, select **Sonnet**, which balances capability and speed for analyzing code patterns.
|
||||
|
||||
6
|
||||
|
||||
Choose a color
|
||||
|
||||
Pick a background color for the subagent. This helps you identify which subagent is running in the UI.
|
||||
|
||||
7
|
||||
|
||||
Save and try it out
|
||||
|
||||
Save the subagent. It’s available immediately (no restart needed). Try it:
|
||||
|
||||
```bash
|
||||
Use the code-improver agent to suggest improvements in this project
|
||||
```
|
||||
|
||||
Claude delegates to your new subagent, which scans the codebase and returns improvement suggestions.
|
||||
|
||||
You now have a subagent you can use in any project on your machine to analyze codebases and suggest improvements.
|
||||
You can also create subagents manually as Markdown files, define them via CLI flags, or distribute them through plugins. The following sections cover all configuration options.
|
||||
|
||||
## [](#configure-subagents) Configure subagents
|
||||
|
||||
### [](#use-the-/agents-command) Use the /agents command
|
||||
|
||||
The `/agents` command provides an interactive interface for managing subagents. Run `/agents` to:
|
||||
|
||||
- View all available subagents (built-in, user, project, and plugin)
|
||||
- Create new subagents with guided setup or Claude generation
|
||||
- Edit existing subagent configuration and tool access
|
||||
- Delete custom subagents
|
||||
- See which subagents are active when duplicates exist
|
||||
|
||||
This is the recommended way to create and manage subagents. For manual creation or automation, you can also add subagent files directly.
|
||||
|
||||
### [](#choose-the-subagent-scope) Choose the subagent scope
|
||||
|
||||
Subagents are Markdown files with YAML frontmatter. Store them in different locations depending on scope. When multiple subagents share the same name, the higher-priority location wins.
|
||||
|
||||
| Location | Scope | Priority | How to create |
|
||||
| --- | --- | --- | --- |
|
||||
| `--agents` CLI flag | Current session | 1 (highest) | Pass JSON when launching Claude Code |
|
||||
| `.claude/agents/` | Current project | 2 | Interactive or manual |
|
||||
| `~/.claude/agents/` | All your projects | 3 | Interactive or manual |
|
||||
| Plugin’s `agents/` directory | Where plugin is enabled | 4 (lowest) | Installed with [plugins](/docs/en/plugins) |
|
||||
|
||||
**Project subagents** (`.claude/agents/`) are ideal for subagents specific to a codebase. Check them into version control so your team can use and improve them collaboratively.
|
||||
**User subagents** (`~/.claude/agents/`) are personal subagents available in all your projects.
|
||||
**CLI-defined subagents** are passed as JSON when launching Claude Code. They exist only for that session and aren’t saved to disk, making them useful for quick testing or automation scripts:
|
||||
|
||||
```bash
|
||||
claude --agents '{
|
||||
"code-reviewer": {
|
||||
"description": "Expert code reviewer. Use proactively after code changes.",
|
||||
"prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
|
||||
"tools": ["Read", "Grep", "Glob", "Bash"],
|
||||
"model": "sonnet"
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
The `--agents` flag accepts JSON with the same fields as [frontmatter](#supported-frontmatter-fields). Use `prompt` for the system prompt (equivalent to the markdown body in file-based subagents). See the [CLI reference](/docs/en/cli-reference#agents-flag-format) for the full JSON format.
|
||||
**Plugin subagents** come from [plugins](/docs/en/plugins) you’ve installed. They appear in `/agents` alongside your custom subagents. See the [plugin components reference](/docs/en/plugins-reference#agents) for details on creating plugin subagents.
|
||||
|
||||
### [](#write-subagent-files) Write subagent files
|
||||
|
||||
Subagent files use YAML frontmatter for configuration, followed by the system prompt in Markdown:
|
||||
|
||||
Subagents are loaded at session start. If you create a subagent by manually adding a file, restart your session or use `/agents` to load it immediately.
|
||||
|
||||
```bash
|
||||
---
|
||||
name: code-reviewer
|
||||
description: Reviews code for quality and best practices
|
||||
tools: Read, Glob, Grep
|
||||
model: sonnet
|
||||
---
|
||||
|
||||
You are a code reviewer. When invoked, analyze the code and provide
|
||||
specific, actionable feedback on quality, security, and best practices.
|
||||
```
|
||||
|
||||
The frontmatter defines the subagent’s metadata and configuration. The body becomes the system prompt that guides the subagent’s behavior. Subagents receive only this system prompt (plus basic environment details like working directory), not the full Claude Code system prompt.
|
||||
|
||||
#### [](#supported-frontmatter-fields) Supported frontmatter fields
|
||||
|
||||
The following fields can be used in the YAML frontmatter. Only `name` and `description` are required.
|
||||
|
||||
| Field | Required | Description |
|
||||
| --- | --- | --- |
|
||||
| `name` | Yes | Unique identifier using lowercase letters and hyphens |
|
||||
| `description` | Yes | When Claude should delegate to this subagent |
|
||||
| `tools` | No | [Tools](#available-tools) the subagent can use. Inherits all tools if omitted |
|
||||
| `disallowedTools` | No | Tools to deny, removed from inherited or specified list |
|
||||
| `model` | No | [Model](#choose-a-model) to use: `sonnet`, `opus`, `haiku`, or `inherit`. Defaults to `sonnet` |
|
||||
| `permissionMode` | No | [Permission mode](#permission-modes): `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, or `plan` |
|
||||
| `skills` | No | [Skills](/docs/en/skills) to load into the subagent’s context at startup. The full skill content is injected, not just made available for invocation. Subagents don’t inherit skills from the parent conversation |
|
||||
| `hooks` | No | [Lifecycle hooks](#define-hooks-for-subagents) scoped to this subagent |
|
||||
|
||||
### [](#choose-a-model) Choose a model
|
||||
|
||||
The `model` field controls which [AI model](/docs/en/model-config) the subagent uses:
|
||||
|
||||
- **Model alias**: Use one of the available aliases: `sonnet`, `opus`, or `haiku`
|
||||
- **inherit**: Use the same model as the main conversation (useful for consistency)
|
||||
- **Omitted**: If not specified, uses the default model configured for subagents (`sonnet`)
|
||||
|
||||
### [](#control-subagent-capabilities) Control subagent capabilities
|
||||
|
||||
You can control what subagents can do through tool access, permission modes, and conditional rules.
|
||||
|
||||
#### [](#available-tools) Available tools
|
||||
|
||||
Subagents can use any of Claude Code’s [internal tools](/docs/en/settings#tools-available-to-claude). By default, subagents inherit all tools from the main conversation, including MCP tools.
|
||||
To restrict tools, use the `tools` field (allowlist) or `disallowedTools` field (denylist):
|
||||
|
||||
```bash
|
||||
---
|
||||
name: safe-researcher
|
||||
description: Research agent with restricted capabilities
|
||||
tools: Read, Grep, Glob, Bash
|
||||
disallowedTools: Write, Edit
|
||||
---
|
||||
```
|
||||
|
||||
#### [](#permission-modes) Permission modes
|
||||
|
||||
The `permissionMode` field controls how the subagent handles permission prompts. Subagents inherit the permission context from the main conversation but can override the mode.
|
||||
|
||||
| Mode | Behavior |
|
||||
| --- | --- |
|
||||
| `default` | Standard permission checking with prompts |
|
||||
| `acceptEdits` | Auto-accept file edits |
|
||||
| `dontAsk` | Auto-deny permission prompts (explicitly allowed tools still work) |
|
||||
| `bypassPermissions` | Skip all permission checks |
|
||||
| `plan` | Plan mode (read-only exploration) |
|
||||
|
||||
Use `bypassPermissions` with caution. It skips all permission checks, allowing the subagent to execute any operation without approval.
|
||||
|
||||
If the parent uses `bypassPermissions`, this takes precedence and cannot be overridden.
|
||||
|
||||
#### [](#conditional-rules-with-hooks) Conditional rules with hooks
|
||||
|
||||
For more dynamic control over tool usage, use `PreToolUse` hooks to validate operations before they execute. This is useful when you need to allow some operations of a tool while blocking others.
|
||||
This example creates a subagent that only allows read-only database queries. The `PreToolUse` hook runs the script specified in `command` before each Bash command executes:
|
||||
|
||||
```bash
|
||||
---
|
||||
name: db-reader
|
||||
description: Execute read-only database queries
|
||||
tools: Bash
|
||||
hooks:
|
||||
PreToolUse:
|
||||
- matcher: "Bash"
|
||||
hooks:
|
||||
- type: command
|
||||
command: "./scripts/validate-readonly-query.sh"
|
||||
---
|
||||
```
|
||||
|
||||
Claude Code [passes hook input as JSON](/docs/en/hooks#pretooluse-input) via stdin to hook commands. The validation script reads this JSON, extracts the Bash command, and [exits with code 2](/docs/en/hooks#exit-code-2-behavior) to block write operations:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# ./scripts/validate-readonly-query.sh
|
||||
|
||||
INPUT=$(cat)
|
||||
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
|
||||
|
||||
# Block SQL write operations (case-insensitive)
|
||||
if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE)\b' > /dev/null; then
|
||||
echo "Blocked: Only SELECT queries are allowed" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
exit 0
|
||||
```
|
||||
|
||||
See [Hook input](/docs/en/hooks#pretooluse-input) for the complete input schema and [exit codes](/docs/en/hooks#exit-codes) for how exit codes affect behavior.
|
||||
|
||||
#### [](#disable-specific-subagents) Disable specific subagents
|
||||
|
||||
You can prevent Claude from using specific subagents by adding them to the `deny` array in your [settings](/docs/en/settings#permission-settings). Use the format `Task(subagent-name)` where `subagent-name` matches the subagent’s name field.
|
||||
|
||||
```bash
|
||||
{
|
||||
"permissions": {
|
||||
"deny": ["Task(Explore)", "Task(my-custom-agent)"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This works for both built-in and custom subagents. You can also use the `--disallowedTools` CLI flag:
|
||||
|
||||
```bash
|
||||
claude --disallowedTools "Task(Explore)"
|
||||
```
|
||||
|
||||
See [IAM documentation](/docs/en/iam#tool-specific-permission-rules) for more details on permission rules.
|
||||
|
||||
### [](#define-hooks-for-subagents) Define hooks for subagents
|
||||
|
||||
Subagents can define [hooks](/docs/en/hooks) that run during the subagent’s lifecycle. There are two ways to configure hooks:
|
||||
|
||||
1. **In the subagent’s frontmatter**: Define hooks that run only while that subagent is active
|
||||
2. **In `settings.json`**: Define hooks that run in the main session when subagents start or stop
|
||||
|
||||
#### [](#hooks-in-subagent-frontmatter) Hooks in subagent frontmatter
|
||||
|
||||
Define hooks directly in the subagent’s markdown file. These hooks only run while that specific subagent is active and are cleaned up when it finishes.
|
||||
|
||||
| Event | Matcher input | When it fires |
|
||||
| --- | --- | --- |
|
||||
| `PreToolUse` | Tool name | Before the subagent uses a tool |
|
||||
| `PostToolUse` | Tool name | After the subagent uses a tool |
|
||||
| `Stop` | (none) | When the subagent finishes |
|
||||
|
||||
This example validates Bash commands with the `PreToolUse` hook and runs a linter after file edits with `PostToolUse`:
|
||||
|
||||
```bash
|
||||
---
|
||||
name: code-reviewer
|
||||
description: Review code changes with automatic linting
|
||||
hooks:
|
||||
PreToolUse:
|
||||
- matcher: "Bash"
|
||||
hooks:
|
||||
- type: command
|
||||
command: "./scripts/validate-command.sh $TOOL_INPUT"
|
||||
PostToolUse:
|
||||
- matcher: "Edit|Write"
|
||||
hooks:
|
||||
- type: command
|
||||
command: "./scripts/run-linter.sh"
|
||||
---
|
||||
```
|
||||
|
||||
`Stop` hooks in frontmatter are automatically converted to `SubagentStop` events.
|
||||
|
||||
#### [](#project-level-hooks-for-subagent-events) Project-level hooks for subagent events
|
||||
|
||||
Configure hooks in `settings.json` that respond to subagent lifecycle events in the main session. Use the `matcher` field to target specific agent types by name.
|
||||
|
||||
| Event | Matcher input | When it fires |
|
||||
| --- | --- | --- |
|
||||
| `SubagentStart` | Agent type name | When a subagent begins execution |
|
||||
| `SubagentStop` | Agent type name | When a subagent completes |
|
||||
|
||||
This example runs setup and cleanup scripts only when the `db-agent` subagent starts and stops:
|
||||
|
||||
```bash
|
||||
{
|
||||
"hooks": {
|
||||
"SubagentStart": [
|
||||
{
|
||||
"matcher": "db-agent",
|
||||
"hooks": [
|
||||
{ "type": "command", "command": "./scripts/setup-db-connection.sh" }
|
||||
]
|
||||
}
|
||||
],
|
||||
"SubagentStop": [
|
||||
{
|
||||
"matcher": "db-agent",
|
||||
"hooks": [
|
||||
{ "type": "command", "command": "./scripts/cleanup-db-connection.sh" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See [Hooks](/docs/en/hooks) for the complete hook configuration format.
|
||||
|
||||
## [](#work-with-subagents) Work with subagents
|
||||
|
||||
### [](#understand-automatic-delegation) Understand automatic delegation
|
||||
|
||||
Claude automatically delegates tasks based on the task description in your request, the `description` field in subagent configurations, and current context. To encourage proactive delegation, include phrases like “use proactively” in your subagent’s description field.
|
||||
You can also request a specific subagent explicitly:
|
||||
|
||||
```bash
|
||||
Use the test-runner subagent to fix failing tests
|
||||
Have the code-reviewer subagent look at my recent changes
|
||||
```
|
||||
|
||||
### [](#run-subagents-in-foreground-or-background) Run subagents in foreground or background
|
||||
|
||||
Subagents can run in the foreground (blocking) or background (concurrent):
|
||||
|
||||
- **Foreground subagents** block the main conversation until complete. Permission prompts and clarifying questions (like [`AskUserQuestion`](/docs/en/settings#tools-available-to-claude)) are passed through to you.
|
||||
- **Background subagents** run concurrently while you continue working. They inherit the parent’s permissions and auto-deny anything not pre-approved. If a background subagent needs a permission it doesn’t have or needs to ask clarifying questions, that tool call fails but the subagent continues. MCP tools are not available in background subagents.
|
||||
|
||||
If a background subagent fails due to missing permissions, you can [resume it](#resume-subagents) in the foreground to retry with interactive prompts.
|
||||
Claude decides whether to run subagents in the foreground or background based on the task. You can also:
|
||||
|
||||
- Ask Claude to “run this in the background”
|
||||
- Press **Ctrl+B** to background a running task
|
||||
|
||||
To disable all background task functionality, set the `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` environment variable to `1`. See [Environment variables](/docs/en/settings#environment-variables).
|
||||
|
||||
### [](#common-patterns) Common patterns
|
||||
|
||||
#### [](#isolate-high-volume-operations) Isolate high-volume operations
|
||||
|
||||
One of the most effective uses for subagents is isolating operations that produce large amounts of output. Running tests, fetching documentation, or processing log files can consume significant context. By delegating these to a subagent, the verbose output stays in the subagent’s context while only the relevant summary returns to your main conversation.
|
||||
|
||||
```bash
|
||||
Use a subagent to run the test suite and report only the failing tests with their error messages
|
||||
```
|
||||
|
||||
#### [](#run-parallel-research) Run parallel research
|
||||
|
||||
For independent investigations, spawn multiple subagents to work simultaneously:
|
||||
|
||||
```bash
|
||||
Research the authentication, database, and API modules in parallel using separate subagents
|
||||
```
|
||||
|
||||
Each subagent explores its area independently, then Claude synthesizes the findings. This works best when the research paths don’t depend on each other.
|
||||
|
||||
When subagents complete, their results return to your main conversation. Running many subagents that each return detailed results can consume significant context.
|
||||
|
||||
#### [](#chain-subagents) Chain subagents
|
||||
|
||||
For multi-step workflows, ask Claude to use subagents in sequence. Each subagent completes its task and returns results to Claude, which then passes relevant context to the next subagent.
|
||||
|
||||
```bash
|
||||
Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them
|
||||
```
|
||||
|
||||
### [](#choose-between-subagents-and-main-conversation) Choose between subagents and main conversation
|
||||
|
||||
Use the **main conversation** when:
|
||||
|
||||
- The task needs frequent back-and-forth or iterative refinement
|
||||
- Multiple phases share significant context (planning → implementation → testing)
|
||||
- You’re making a quick, targeted change
|
||||
- Latency matters. Subagents start fresh and may need time to gather context
|
||||
|
||||
Use **subagents** when:
|
||||
|
||||
- The task produces verbose output you don’t need in your main context
|
||||
- You want to enforce specific tool restrictions or permissions
|
||||
- The work is self-contained and can return a summary
|
||||
|
||||
Consider [Skills](/docs/en/skills) instead when you want reusable prompts or workflows that run in the main conversation context rather than isolated subagent context.
|
||||
|
||||
Subagents cannot spawn other subagents. If your workflow requires nested delegation, use [Skills](/docs/en/skills) or [chain subagents](#chain-subagents) from the main conversation.
|
||||
|
||||
### [](#manage-subagent-context) Manage subagent context
|
||||
|
||||
#### [](#resume-subagents) Resume subagents
|
||||
|
||||
Each subagent invocation creates a new instance with fresh context. To continue an existing subagent’s work instead of starting over, ask Claude to resume it.
|
||||
Resumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. The subagent picks up exactly where it stopped rather than starting fresh.
|
||||
When a subagent completes, Claude receives its agent ID. To resume a subagent, ask Claude to continue the previous work:
|
||||
|
||||
```bash
|
||||
Use the code-reviewer subagent to review the authentication module
|
||||
[Agent completes]
|
||||
|
||||
Continue that code review and now analyze the authorization logic
|
||||
[Claude resumes the subagent with full context from previous conversation]
|
||||
```
|
||||
|
||||
You can also ask Claude for the agent ID if you want to reference it explicitly, or find IDs in the transcript files at `~/.claude/projects/{project}/{sessionId}/subagents/`. Each transcript is stored as `agent-{agentId}.jsonl`.
|
||||
For programmatic usage, see [Subagents in the Agent SDK](/docs/en/agent-sdk/subagents).
|
||||
Subagent transcripts persist independently of the main conversation:
|
||||
|
||||
- **Main conversation compaction**: When the main conversation compacts, subagent transcripts are unaffected. They’re stored in separate files.
|
||||
- **Session persistence**: Subagent transcripts persist within their session. You can [resume a subagent](#resume-subagents) after restarting Claude Code by resuming the same session.
|
||||
- **Automatic cleanup**: Transcripts are cleaned up based on the `cleanupPeriodDays` setting (default: 30 days).
|
||||
|
||||
#### [](#auto-compaction) Auto-compaction
|
||||
|
||||
Subagents support automatic compaction using the same logic as the main conversation. By default, auto-compaction triggers at approximately 95% capacity. To trigger compaction earlier, set `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` to a lower percentage (for example, `50`). See [environment variables](/docs/en/settings#environment-variables) for details.
|
||||
Compaction events are logged in subagent transcript files:
|
||||
|
||||
```bash
|
||||
{
|
||||
"type": "system",
|
||||
"subtype": "compact_boundary",
|
||||
"compactMetadata": {
|
||||
"trigger": "auto",
|
||||
"preTokens": 167189
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `preTokens` value shows how many tokens were used before compaction occurred.
|
||||
|
||||
## [](#example-subagents) Example subagents
|
||||
|
||||
These examples demonstrate effective patterns for building subagents. Use them as starting points, or generate a customized version with Claude.
|
||||
|
||||
**Best practices:**
|
||||
|
||||
- **Design focused subagents:** each subagent should excel at one specific task
|
||||
- **Write detailed descriptions:** Claude uses the description to decide when to delegate
|
||||
- **Limit tool access:** grant only necessary permissions for security and focus
|
||||
- **Check into version control:** share project subagents with your team
|
||||
|
||||
### [](#code-reviewer) Code reviewer
|
||||
|
||||
A read-only subagent that reviews code without modifying it. This example shows how to design a focused subagent with limited tool access (no Edit or Write) and a detailed prompt that specifies exactly what to look for and how to format output.
|
||||
|
||||
```bash
|
||||
---
|
||||
name: code-reviewer
|
||||
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
|
||||
tools: Read, Grep, Glob, Bash
|
||||
model: inherit
|
||||
---
|
||||
|
||||
You are a senior code reviewer ensuring high standards of code quality and security.
|
||||
|
||||
When invoked:
|
||||
1. Run git diff to see recent changes
|
||||
2. Focus on modified files
|
||||
3. Begin review immediately
|
||||
|
||||
Review checklist:
|
||||
- Code is clear and readable
|
||||
- Functions and variables are well-named
|
||||
- No duplicated code
|
||||
- Proper error handling
|
||||
- No exposed secrets or API keys
|
||||
- Input validation implemented
|
||||
- Good test coverage
|
||||
- Performance considerations addressed
|
||||
|
||||
Provide feedback organized by priority:
|
||||
- Critical issues (must fix)
|
||||
- Warnings (should fix)
|
||||
- Suggestions (consider improving)
|
||||
|
||||
Include specific examples of how to fix issues.
|
||||
```
|
||||
|
||||
### [](#debugger) Debugger
|
||||
|
||||
A subagent that can both analyze and fix issues. Unlike the code reviewer, this one includes Edit because fixing bugs requires modifying code. The prompt provides a clear workflow from diagnosis to verification.
|
||||
|
||||
```bash
|
||||
---
|
||||
name: debugger
|
||||
description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
|
||||
tools: Read, Edit, Bash, Grep, Glob
|
||||
---
|
||||
|
||||
You are an expert debugger specializing in root cause analysis.
|
||||
|
||||
When invoked:
|
||||
1. Capture error message and stack trace
|
||||
2. Identify reproduction steps
|
||||
3. Isolate the failure location
|
||||
4. Implement minimal fix
|
||||
5. Verify solution works
|
||||
|
||||
Debugging process:
|
||||
- Analyze error messages and logs
|
||||
- Check recent code changes
|
||||
- Form and test hypotheses
|
||||
- Add strategic debug logging
|
||||
- Inspect variable states
|
||||
|
||||
For each issue, provide:
|
||||
- Root cause explanation
|
||||
- Evidence supporting the diagnosis
|
||||
- Specific code fix
|
||||
- Testing approach
|
||||
- Prevention recommendations
|
||||
|
||||
Focus on fixing the underlying issue, not the symptoms.
|
||||
```
|
||||
|
||||
### [](#data-scientist) Data scientist
|
||||
|
||||
A domain-specific subagent for data analysis work. This example shows how to create subagents for specialized workflows outside of typical coding tasks. It explicitly sets `model: sonnet` for more capable analysis.
|
||||
|
||||
```bash
|
||||
---
|
||||
name: data-scientist
|
||||
description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries.
|
||||
tools: Bash, Read, Write
|
||||
model: sonnet
|
||||
---
|
||||
|
||||
You are a data scientist specializing in SQL and BigQuery analysis.
|
||||
|
||||
When invoked:
|
||||
1. Understand the data analysis requirement
|
||||
2. Write efficient SQL queries
|
||||
3. Use BigQuery command line tools (bq) when appropriate
|
||||
4. Analyze and summarize results
|
||||
5. Present findings clearly
|
||||
|
||||
Key practices:
|
||||
- Write optimized SQL queries with proper filters
|
||||
- Use appropriate aggregations and joins
|
||||
- Include comments explaining complex logic
|
||||
- Format results for readability
|
||||
- Provide data-driven recommendations
|
||||
|
||||
For each analysis:
|
||||
- Explain the query approach
|
||||
- Document any assumptions
|
||||
- Highlight key findings
|
||||
- Suggest next steps based on data
|
||||
|
||||
Always ensure queries are efficient and cost-effective.
|
||||
```
|
||||
|
||||
### [](#database-query-validator) Database query validator
|
||||
|
||||
A subagent that allows Bash access but validates commands to permit only read-only SQL queries. This example shows how to use `PreToolUse` hooks for conditional validation when you need finer control than the `tools` field provides.
|
||||
|
||||
```bash
|
||||
---
|
||||
name: db-reader
|
||||
description: Execute read-only database queries. Use when analyzing data or generating reports.
|
||||
tools: Bash
|
||||
hooks:
|
||||
PreToolUse:
|
||||
- matcher: "Bash"
|
||||
hooks:
|
||||
- type: command
|
||||
command: "./scripts/validate-readonly-query.sh"
|
||||
---
|
||||
|
||||
You are a database analyst with read-only access. Execute SELECT queries to answer questions about the data.
|
||||
|
||||
When asked to analyze data:
|
||||
1. Identify which tables contain the relevant data
|
||||
2. Write efficient SELECT queries with appropriate filters
|
||||
3. Present results clearly with context
|
||||
|
||||
You cannot modify data. If asked to INSERT, UPDATE, DELETE, or modify schema, explain that you only have read access.
|
||||
```
|
||||
|
||||
Claude Code [passes hook input as JSON](/docs/en/hooks#pretooluse-input) via stdin to hook commands. The validation script reads this JSON, extracts the command being executed, and checks it against a list of SQL write operations. If a write operation is detected, the script [exits with code 2](/docs/en/hooks#exit-code-2-behavior) to block execution and returns an error message to Claude via stderr.
|
||||
Create the validation script anywhere in your project. The path must match the `command` field in your hook configuration:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# Blocks SQL write operations, allows SELECT queries
|
||||
|
||||
# Read JSON input from stdin
|
||||
INPUT=$(cat)
|
||||
|
||||
# Extract the command field from tool_input using jq
|
||||
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
|
||||
|
||||
if [ -z "$COMMAND" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Block write operations (case-insensitive)
|
||||
if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE|REPLACE|MERGE)\b' > /dev/null; then
|
||||
echo "Blocked: Write operations not allowed. Use SELECT queries only." >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
exit 0
|
||||
```
|
||||
|
||||
Make the script executable:
|
||||
|
||||
```bash
|
||||
chmod +x ./scripts/validate-readonly-query.sh
|
||||
```
|
||||
|
||||
The hook receives JSON via stdin with the Bash command in `tool_input.command`. Exit code 2 blocks the operation and feeds the error message back to Claude. See [Hooks](/docs/en/hooks#exit-codes) for details on exit codes and [Hook input](/docs/en/hooks#pretooluse-input) for the complete input schema.
|
||||
|
||||
## [](#next-steps) Next steps
|
||||
|
||||
Now that you understand subagents, explore these related features:
|
||||
|
||||
- [Distribute subagents with plugins](/docs/en/plugins) to share subagents across teams or projects
|
||||
- [Run Claude Code programmatically](/docs/en/headless) with the Agent SDK for CI/CD and automation
|
||||
- [Use MCP servers](/docs/en/mcp) to give subagents access to external tools and data
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/terminal-config
|
||||
title: Optimize your terminal setup
|
||||
---
|
||||
|
||||
### [](#themes-and-appearance) 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](/docs/en/statusline) to display contextual information like the current model, working directory, or git branch at the bottom of your terminal.
|
||||
|
||||
### [](#line-breaks) Line breaks
|
||||
|
||||
You have several options for entering line breaks into Claude Code:
|
||||
|
||||
- **Quick escape**: Type `\` followed by Enter to create a newline
|
||||
- **Shift+Enter**: Works out of the box in iTerm2, WezTerm, Ghostty, and Kitty
|
||||
- **Keyboard shortcut**: Set up a keybinding to insert a newline in other terminals
|
||||
|
||||
**Set up Shift+Enter for other terminals**
|
||||
Run `/terminal-setup` within Claude Code to automatically configure Shift+Enter for VS Code, Alacritty, Zed, and Warp.
|
||||
|
||||
The `/terminal-setup` command is only visible in terminals that require manual configuration. If you’re using iTerm2, WezTerm, Ghostty, or Kitty, you won’t see this command because Shift+Enter already works natively.
|
||||
|
||||
**Set up Option+Enter (VS Code, iTerm2 or macOS Terminal.app)**
|
||||
**For Mac Terminal.app:**
|
||||
|
||||
1. Open Settings → Profiles → Keyboard
|
||||
2. Check “Use Option as Meta Key”
|
||||
|
||||
**For iTerm2 and VS Code terminal:**
|
||||
|
||||
1. Open Settings → Profiles → Keys
|
||||
2. Under General, set Left/Right Option key to “Esc+“
|
||||
|
||||
### [](#notification-setup) Notification setup
|
||||
|
||||
Never miss when Claude completes a task with proper notification configuration:
|
||||
|
||||
#### [](#iterm-2-system-notifications) 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) Custom notification hooks
|
||||
|
||||
For advanced notification handling, you can create [notification hooks](/docs/en/hooks#notification) to run your own logic.
|
||||
|
||||
### [](#handling-large-inputs) 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) Vim Mode
|
||||
|
||||
Claude Code supports a subset of Vim keybindings that can be enabled with `/vim` or configured via `/config`.
|
||||
The supported subset includes:
|
||||
|
||||
- Mode switching: `Esc` (to NORMAL), `i`/`I`, `a`/`A`, `o`/`O` (to INSERT)
|
||||
- Navigation: `h`/`j`/`k`/`l`, `w`/`e`/`b`, `0`/`$`/`^`, `gg`/`G`, `f`/`F`/`t`/`T` with `;`/`,` repeat
|
||||
- Editing: `x`, `dw`/`de`/`db`/`dd`/`D`, `cw`/`ce`/`cb`/`cc`/`C`, `.` (repeat)
|
||||
- Yank/paste: `yy`/`Y`, `yw`/`ye`/`yb`, `p`/`P`
|
||||
- Text objects: `iw`/`aw`, `iW`/`aW`, `i"`/`a"`, `i'`/`a'`, `i(`/`a(`, `i[`/`a[`, `i{`/`a{`
|
||||
- Indentation: `>>`/`<<`
|
||||
- Line operations: `J` (join lines)
|
||||
|
||||
See [Interactive mode](/docs/en/interactive-mode#vim-editor-mode) for the complete reference.
|
||||
@@ -0,0 +1,163 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/third-party-integrations
|
||||
title: Enterprise deployment overview
|
||||
---
|
||||
|
||||
Organizations can deploy Claude Code through Anthropic directly or through a cloud provider. This page helps you choose the right configuration.
|
||||
|
||||
## [](#compare-deployment-options) Compare deployment options
|
||||
|
||||
For most organizations, Claude for Teams or Claude for Enterprise provides the best experience. Team members get access to both Claude Code and Claude on the web with a single subscription, centralized billing, and no infrastructure setup required.
|
||||
**Claude for Teams** is self-service and includes collaboration features, admin tools, and billing management. Best for smaller teams that need to get started quickly.
|
||||
**Claude for Enterprise** adds SSO and domain capture, role-based permissions, compliance API access, and managed policy settings for deploying organization-wide Claude Code configurations. Best for larger organizations with security and compliance requirements.
|
||||
Learn more about [Team plans](https://support.claude.com/en/articles/9266767-what-is-the-team-plan) and [Enterprise plans](https://support.claude.com/en/articles/9797531-what-is-the-enterprise-plan).
|
||||
If your organization has specific infrastructure requirements, compare the options below:
|
||||
|
||||
| Feature | Claude for Teams/Enterprise | Anthropic Console | Amazon Bedrock | Google Vertex AI | Microsoft Foundry |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| Best for | Most organizations (recommended) | Individual developers | AWS-native deployments | GCP-native deployments | Azure-native deployments |
|
||||
| Billing | **Teams:** $150/seat (Premium) with PAYG available **Enterprise:** [Contact Sales](https://claude.com/contact-sales) | PAYG | PAYG through AWS | PAYG through GCP | PAYG through Azure |
|
||||
| Regions | Supported [countries](https://www.anthropic.com/supported-countries) | Supported [countries](https://www.anthropic.com/supported-countries) | Multiple AWS [regions](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html) | Multiple GCP [regions](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations) | Multiple Azure [regions](https://azure.microsoft.com/en-us/explore/global-infrastructure/products-by-region/) |
|
||||
| Prompt caching | Enabled by default | Enabled by default | Enabled by default | Enabled by default | Enabled by default |
|
||||
| Authentication | Claude.ai SSO or email | API key | API key or AWS credentials | GCP credentials | API key or Microsoft Entra ID |
|
||||
| Cost tracking | Usage dashboard | Usage dashboard | AWS Cost Explorer | GCP Billing | Azure Cost Management |
|
||||
| Includes Claude on web | Yes | No | No | No | No |
|
||||
| Enterprise features | Team management, SSO, usage monitoring | None | IAM policies, CloudTrail | IAM roles, Cloud Audit Logs | RBAC policies, Azure Monitor |
|
||||
|
||||
Select a deployment option to view setup instructions:
|
||||
|
||||
- [Claude for Teams or Enterprise](/docs/en/iam#claude-for-teams-or-enterprise-recommended)
|
||||
- [Anthropic Console](/docs/en/iam#claude-console-authentication)
|
||||
- [Amazon Bedrock](/docs/en/amazon-bedrock)
|
||||
- [Google Vertex AI](/docs/en/google-vertex-ai)
|
||||
- [Microsoft Foundry](/docs/en/microsoft-foundry)
|
||||
|
||||
## [](#configure-proxies-and-gateways) Configure proxies and gateways
|
||||
|
||||
Most organizations can use a cloud provider directly without additional configuration. However, you may need to configure a corporate proxy or LLM gateway if your organization has specific network or management requirements. These are different configurations that can be used together:
|
||||
|
||||
- **Corporate proxy**: Routes traffic through an HTTP/HTTPS proxy. Use this if your organization requires all outbound traffic to pass through a proxy server for security monitoring, compliance, or network policy enforcement. Configure with the `HTTPS_PROXY` or `HTTP_PROXY` environment variables. Learn more in [Enterprise network configuration](/docs/en/network-config).
|
||||
- **LLM Gateway**: A service that sits between Claude Code and the cloud provider to handle authentication and routing. Use this if you need centralized usage tracking across teams, custom rate limiting or budgets, or centralized authentication management. Configure with the `ANTHROPIC_BASE_URL`, `ANTHROPIC_BEDROCK_BASE_URL`, or `ANTHROPIC_VERTEX_BASE_URL` environment variables. Learn more in [LLM gateway configuration](/docs/en/llm-gateway).
|
||||
|
||||
The following examples show the environment variables to set in your shell or shell profile (`.bashrc`, `.zshrc`). See [Settings](/docs/en/settings) for other configuration methods.
|
||||
|
||||
### [](#amazon-bedrock) Amazon Bedrock
|
||||
|
||||
- Corporate proxy
|
||||
- LLM Gateway
|
||||
|
||||
Route Bedrock traffic through your corporate proxy by setting the following [environment variables](/docs/en/settings#environment-variables):
|
||||
|
||||
```bash
|
||||
# Enable Bedrock
|
||||
export CLAUDE_CODE_USE_BEDROCK=1
|
||||
export AWS_REGION=us-east-1
|
||||
|
||||
# Configure corporate proxy
|
||||
export HTTPS_PROXY='https://proxy.example.com:8080'
|
||||
```
|
||||
|
||||
Route Bedrock traffic through your LLM gateway by setting the following [environment variables](/docs/en/settings#environment-variables):
|
||||
|
||||
```bash
|
||||
# Enable Bedrock
|
||||
export CLAUDE_CODE_USE_BEDROCK=1
|
||||
|
||||
# Configure LLM gateway
|
||||
export ANTHROPIC_BEDROCK_BASE_URL='https://your-llm-gateway.com/bedrock'
|
||||
export CLAUDE_CODE_SKIP_BEDROCK_AUTH=1 # If gateway handles AWS auth
|
||||
```
|
||||
|
||||
### [](#microsoft-foundry) Microsoft Foundry
|
||||
|
||||
- Corporate proxy
|
||||
- LLM Gateway
|
||||
|
||||
Route Foundry traffic through your corporate proxy by setting the following [environment variables](/docs/en/settings#environment-variables):
|
||||
|
||||
```bash
|
||||
# Enable Microsoft Foundry
|
||||
export CLAUDE_CODE_USE_FOUNDRY=1
|
||||
export ANTHROPIC_FOUNDRY_RESOURCE=your-resource
|
||||
export ANTHROPIC_FOUNDRY_API_KEY=your-api-key # Or omit for Entra ID auth
|
||||
|
||||
# Configure corporate proxy
|
||||
export HTTPS_PROXY='https://proxy.example.com:8080'
|
||||
```
|
||||
|
||||
Route Foundry traffic through your LLM gateway by setting the following [environment variables](/docs/en/settings#environment-variables):
|
||||
|
||||
```bash
|
||||
# Enable Microsoft Foundry
|
||||
export CLAUDE_CODE_USE_FOUNDRY=1
|
||||
|
||||
# Configure LLM gateway
|
||||
export ANTHROPIC_FOUNDRY_BASE_URL='https://your-llm-gateway.com'
|
||||
export CLAUDE_CODE_SKIP_FOUNDRY_AUTH=1 # If gateway handles Azure auth
|
||||
```
|
||||
|
||||
### [](#google-vertex-ai) Google Vertex AI
|
||||
|
||||
- Corporate proxy
|
||||
- LLM Gateway
|
||||
|
||||
Route Vertex AI traffic through your corporate proxy by setting the following [environment variables](/docs/en/settings#environment-variables):
|
||||
|
||||
```bash
|
||||
# Enable Vertex
|
||||
export CLAUDE_CODE_USE_VERTEX=1
|
||||
export CLOUD_ML_REGION=us-east5
|
||||
export ANTHROPIC_VERTEX_PROJECT_ID=your-project-id
|
||||
|
||||
# Configure corporate proxy
|
||||
export HTTPS_PROXY='https://proxy.example.com:8080'
|
||||
```
|
||||
|
||||
Route Vertex AI traffic through your LLM gateway by setting the following [environment variables](/docs/en/settings#environment-variables):
|
||||
|
||||
```bash
|
||||
# Enable Vertex
|
||||
export CLAUDE_CODE_USE_VERTEX=1
|
||||
|
||||
# Configure LLM gateway
|
||||
export ANTHROPIC_VERTEX_BASE_URL='https://your-llm-gateway.com/vertex'
|
||||
export CLAUDE_CODE_SKIP_VERTEX_AUTH=1 # If gateway handles GCP auth
|
||||
```
|
||||
|
||||
Use `/status` in Claude Code to verify your proxy and gateway configuration is applied correctly.
|
||||
|
||||
## [](#best-practices-for-organizations) Best practices for organizations
|
||||
|
||||
### [](#invest-in-documentation-and-memory) Invest in documentation and memory
|
||||
|
||||
We strongly recommend investing in documentation so that Claude Code understands your codebase. Organizations can deploy CLAUDE.md files at multiple levels:
|
||||
|
||||
- **Organization-wide**: Deploy to system directories like `/Library/Application Support/ClaudeCode/CLAUDE.md` (macOS) for company-wide standards
|
||||
- **Repository-level**: Create `CLAUDE.md` files in repository roots containing project architecture, build commands, and contribution guidelines. Check these into source control so all users benefit
|
||||
|
||||
Learn more in [Memory and CLAUDE.md files](/docs/en/memory).
|
||||
|
||||
### [](#simplify-deployment) Simplify deployment
|
||||
|
||||
If you have a custom development environment, we find that creating a “one click” way to install Claude Code is key to growing adoption across an organization.
|
||||
|
||||
### [](#start-with-guided-usage) Start with guided usage
|
||||
|
||||
Encourage new users to try Claude Code for codebase Q&A, or on smaller bug fixes or feature requests. Ask Claude Code to make a plan. Check Claude’s suggestions and give feedback if it’s off-track. Over time, as users understand this new paradigm better, then they’ll be more effective at letting Claude Code run more agentically.
|
||||
|
||||
### [](#configure-security-policies) Configure security policies
|
||||
|
||||
Security teams can configure managed permissions for what Claude Code is and is not allowed to do, which cannot be overwritten by local configuration. [Learn more](/docs/en/security).
|
||||
|
||||
### [](#leverage-mcp-for-integrations) Leverage MCP for integrations
|
||||
|
||||
MCP is a great way to give Claude Code more information, such as connecting to ticket management systems or error logs. We recommend that one central team configures MCP servers and checks a `.mcp.json` configuration into the codebase so that all users benefit. [Learn more](/docs/en/mcp).
|
||||
At Anthropic, we trust Claude Code to power development across every Anthropic codebase. We hope you enjoy using Claude Code as much as we do.
|
||||
|
||||
## [](#next-steps) Next steps
|
||||
|
||||
Once you’ve chosen a deployment option and configured access for your team:
|
||||
|
||||
1. **Roll out to your team**: Share installation instructions and have team members [install Claude Code](/docs/en/setup) and authenticate with their credentials.
|
||||
2. **Set up shared configuration**: Create a [CLAUDE.md file](/docs/en/memory) in your repositories to help Claude Code understand your codebase and coding standards.
|
||||
3. **Configure permissions**: Review [security settings](/docs/en/security) to define what Claude Code can and cannot do in your environment.
|
||||
@@ -0,0 +1,374 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/troubleshooting
|
||||
title: Troubleshooting
|
||||
---
|
||||
|
||||
## [](#common-installation-issues) Common installation issues
|
||||
|
||||
### [](#windows-installation-issues:-errors-in-wsl) 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
|
||||
# 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
|
||||
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
|
||||
export PATH="$HOME/.nvm/versions/node/$(node -v)/bin:$PATH"
|
||||
```
|
||||
|
||||
Avoid disabling Windows PATH importing (`appendWindowsPath = false`) as this breaks the ability to call Windows executables from WSL. Similarly, avoid uninstalling Node.js from Windows if you use it for Windows development.
|
||||
|
||||
### [](#linux-and-mac-installation-issues:-permission-or-command-not-found-errors) Linux and Mac installation issues: permission or command not found errors
|
||||
|
||||
When installing Claude Code with npm, `PATH` problems may prevent access to `claude`.
|
||||
You may also encounter permission errors if your npm global prefix is not user writable (for example, `/usr`, or `/usr/local`).
|
||||
|
||||
#### [](#recommended-solution:-native-claude-code-installation) Recommended solution: Native Claude Code installation
|
||||
|
||||
Claude Code has a native installation that doesn’t depend on npm or Node.js.
|
||||
Use the following command to run the native installer.
|
||||
**macOS, Linux, WSL:**
|
||||
|
||||
```bash
|
||||
# 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:**
|
||||
|
||||
```bash
|
||||
# Install stable version (default)
|
||||
irm https://claude.ai/install.ps1 | iex
|
||||
|
||||
# Install latest version
|
||||
& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) latest
|
||||
|
||||
# Install specific version number
|
||||
& ([scriptblock]::Create((irm https://claude.ai/install.ps1))) 1.0.58
|
||||
```
|
||||
|
||||
This command installs the appropriate build of Claude Code for your operating system and architecture and adds a symlink to the installation at `~/.local/bin/claude` (or `%USERPROFILE%\.local\bin\claude.exe` on Windows).
|
||||
|
||||
Make sure that you have the installation directory in your system PATH.
|
||||
|
||||
### [](#windows:-“claude-code-on-windows-requires-git-bash”) Windows: “Claude Code on Windows requires git-bash”
|
||||
|
||||
Claude Code on native Windows requires [Git for Windows](https://git-scm.com/downloads/win) which includes Git Bash. If Git is installed but not detected:
|
||||
|
||||
1. Set the path explicitly in PowerShell before running Claude:
|
||||
|
||||
```bash
|
||||
$env:CLAUDE_CODE_GIT_BASH_PATH="C:\Program Files\Git\bin\bash.exe"
|
||||
```
|
||||
2. Or add it to your system environment variables permanently through System Properties → Environment Variables.
|
||||
|
||||
If Git is installed in a non-standard location, adjust the path accordingly.
|
||||
|
||||
### [](#windows:-“installmethod-is-native,-but-claude-command-not-found”) Windows: “installMethod is native, but claude command not found”
|
||||
|
||||
If you see this error after installation, the `claude` command isn’t in your PATH. Add it manually:
|
||||
|
||||
1
|
||||
|
||||
Open Environment Variables
|
||||
|
||||
Press `Win + R`, type `sysdm.cpl`, and press Enter. Click **Advanced** → **Environment Variables**.
|
||||
|
||||
2
|
||||
|
||||
Edit User PATH
|
||||
|
||||
Under “User variables”, select **Path** and click **Edit**. Click **New** and add:
|
||||
|
||||
```bash
|
||||
%USERPROFILE%\.local\bin
|
||||
```
|
||||
|
||||
3
|
||||
|
||||
Restart your terminal
|
||||
|
||||
Close and reopen PowerShell or CMD for changes to take effect.
|
||||
|
||||
Verify installation:
|
||||
|
||||
```bash
|
||||
claude doctor # Check installation health
|
||||
```
|
||||
|
||||
## [](#permissions-and-authentication) Permissions and authentication
|
||||
|
||||
### [](#repeated-permission-prompts) 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](/docs/en/iam#configuring-permissions).
|
||||
|
||||
### [](#authentication-issues) 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
|
||||
rm -rf ~/.config/claude-code/auth.json
|
||||
claude
|
||||
```
|
||||
|
||||
This removes your stored authentication information and forces a clean login.
|
||||
|
||||
## [](#configuration-file-locations) Configuration file locations
|
||||
|
||||
Claude Code stores configuration in several locations:
|
||||
|
||||
| File | Purpose |
|
||||
| --- | --- |
|
||||
| `~/.claude/settings.json` | User settings (permissions, hooks, model overrides) |
|
||||
| `.claude/settings.json` | Project settings (checked into source control) |
|
||||
| `.claude/settings.local.json` | Local project settings (not committed) |
|
||||
| `~/.claude.json` | Global state (theme, OAuth, MCP servers, allowed tools) |
|
||||
| `.mcp.json` | Project MCP servers (checked into source control) |
|
||||
| `managed-settings.json` | [Managed settings](/docs/en/settings#settings-files) |
|
||||
| `managed-mcp.json` | [Managed MCP servers](/docs/en/mcp#managed-mcp-configuration) |
|
||||
|
||||
On Windows, `~` refers to your user home directory, such as `C:\Users\YourName`.
|
||||
**Managed file locations:**
|
||||
|
||||
- macOS: `/Library/Application Support/ClaudeCode/`
|
||||
- Linux/WSL: `/etc/claude-code/`
|
||||
- Windows: `C:\Program Files\ClaudeCode\`
|
||||
|
||||
For details on configuring these files, see [Settings](/docs/en/settings) and [MCP](/docs/en/mcp).
|
||||
|
||||
### [](#resetting-configuration) Resetting configuration
|
||||
|
||||
To reset Claude Code to default settings, you can remove the configuration files:
|
||||
|
||||
```bash
|
||||
# Reset all user settings and state
|
||||
rm ~/.claude.json
|
||||
rm -rf ~/.claude/
|
||||
|
||||
# Reset project-specific settings
|
||||
rm -rf .claude/
|
||||
rm .mcp.json
|
||||
```
|
||||
|
||||
This will remove all your settings, allowed tools, MCP server configurations, and session history.
|
||||
|
||||
## [](#performance-and-stability) Performance and stability
|
||||
|
||||
### [](#high-cpu-or-memory-usage) 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) 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) Search and discovery issues
|
||||
|
||||
If Search tool, `@file` mentions, custom agents, and custom slash commands aren’t working, install system `ripgrep`:
|
||||
|
||||
```bash
|
||||
# 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](/docs/en/settings#environment-variables).
|
||||
|
||||
### [](#slow-or-incomplete-search-results-on-wsl) Slow or incomplete search results on WSL
|
||||
|
||||
Disk read performance penalties when [working across file systems on WSL](https://learn.microsoft.com/en-us/windows/wsl/filesystems) may result in fewer-than-expected matches (but not a complete lack of search functionality) when using Claude Code on WSL.
|
||||
|
||||
`/doctor` will show Search as OK in this case.
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. **Submit more specific searches**: Reduce the number of files searched by specifying directories or file types: “Search for JWT validation logic in the auth-service package” or “Find use of md5 hash in JS files”.
|
||||
2. **Move project to Linux filesystem**: If possible, ensure your project is located on the Linux filesystem (`/home/`) rather than the Windows filesystem (`/mnt/c/`).
|
||||
3. **Use native Windows instead**: Consider running Claude Code natively on Windows instead of through WSL, for better file system performance.
|
||||
|
||||
## [](#ide-integration-issues) IDE integration issues
|
||||
|
||||
### [](#jetbrains-ide-not-detected-on-wsl2) 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 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
|
||||
wsl hostname -I
|
||||
# Example output: 172.21.123.456
|
||||
```
|
||||
2. Open PowerShell as Administrator and create a firewall rule:
|
||||
|
||||
```bash
|
||||
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:
|
||||
|
||||
```bash
|
||||
[wsl2]
|
||||
networkingMode=mirrored
|
||||
```
|
||||
|
||||
Then restart WSL with `wsl --shutdown` from PowerShell.
|
||||
|
||||
These networking issues only affect WSL2. WSL1 uses the host’s network directly and doesn’t require these configurations.
|
||||
|
||||
For additional JetBrains configuration tips, see our [JetBrains IDE guide](/docs/en/jetbrains#plugin-settings).
|
||||
|
||||
### [](#reporting-windows-ide-integration-issues-both-native-and-wsl) Reporting Windows IDE integration issues (both native and WSL)
|
||||
|
||||
If you’re experiencing IDE integration problems on Windows, [create an issue](https://github.com/anthropics/claude-code/issues) with the following information:
|
||||
|
||||
- Environment type: native Windows (Git Bash) or WSL1/WSL2
|
||||
- WSL networking mode (if applicable): NAT or mirrored
|
||||
- IDE name and version
|
||||
- Claude Code extension/plugin version
|
||||
- Shell type: Bash, Zsh, PowerShell, etc.
|
||||
|
||||
### [](#escape-key-not-working-in-jetbrains-intellij,-pycharm,-etc-terminals) Escape key not working in JetBrains (IntelliJ, PyCharm, etc.) terminals
|
||||
|
||||
If you’re using Claude Code in JetBrains terminals and the `Esc` key doesn’t interrupt the agent as expected, this is likely due to a keybinding clash with JetBrains’ default shortcuts.
|
||||
To fix this issue:
|
||||
|
||||
1. Go to Settings → Tools → Terminal
|
||||
2. Either:
|
||||
- Uncheck “Move focus to the editor with Escape”, or
|
||||
- Click “Configure terminal keybindings” and delete the “Switch focus to Editor” shortcut
|
||||
3. Apply the changes
|
||||
|
||||
This allows the `Esc` key to properly interrupt Claude Code operations.
|
||||
|
||||
## [](#markdown-formatting-issues) 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) Missing language tags in code blocks
|
||||
|
||||
If you notice code blocks like this in generated markdown:
|
||||
|
||||
```bash
|
||||
```
|
||||
function example() {
|
||||
return "hello";
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
Instead of properly tagged blocks like:
|
||||
|
||||
```bash
|
||||
```javascript
|
||||
function example() {
|
||||
return "hello";
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. **Ask Claude to add language tags**: Request “Add appropriate language tags to all code blocks in this markdown file.”
|
||||
2. **Use post-processing hooks**: Set up automatic formatting hooks to detect and add missing language tags. See the [markdown formatting hook example](/docs/en/hooks-guide#markdown-formatting-hook) for implementation details.
|
||||
3. **Manual verification**: After generating markdown files, review them for proper code block formatting and request corrections if needed.
|
||||
|
||||
### [](#inconsistent-spacing-and-formatting) 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](/docs/en/memory) files.
|
||||
|
||||
### [](#best-practices-for-markdown-generation) 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`](/docs/en/memory)
|
||||
- **Set up validation hooks**: Use post-processing hooks to automatically verify and fix common formatting issues
|
||||
|
||||
## [](#getting-more-help) Getting more help
|
||||
|
||||
If you’re experiencing issues not covered here:
|
||||
|
||||
1. Use the `/bug` command within Claude Code to report problems directly to Anthropic
|
||||
2. Check the [GitHub repository](https://github.com/anthropics/claude-code) for known issues
|
||||
3. Run `/doctor` to diagnose issues. It checks:
|
||||
- Installation type, version, and search functionality
|
||||
- Auto-update status and available versions
|
||||
- Invalid settings files (malformed JSON, incorrect types)
|
||||
- MCP server configuration errors
|
||||
- Keybinding configuration problems
|
||||
- Context usage warnings (large CLAUDE.md files, high MCP token usage, unreachable permission rules)
|
||||
- Plugin and agent loading errors
|
||||
4. Ask Claude directly about its capabilities and features - Claude has built-in access to its documentation
|
||||
@@ -0,0 +1,235 @@
|
||||
---
|
||||
source: https://code.claude.com/docs/en/vs-code
|
||||
title: Use Claude Code in VS Code
|
||||
---
|
||||
|
||||

|
||||
The VS Code extension provides a native graphical interface for Claude Code, integrated directly into your IDE. This is the recommended way to use Claude Code in VS Code.
|
||||
With the extension, you can review and edit Claude’s plans before accepting them, auto-accept edits as they’re made, @-mention files with specific line ranges from your selection, access conversation history, and open multiple conversations in separate tabs or windows.
|
||||
|
||||
## [](#prerequisites) Prerequisites
|
||||
|
||||
- VS Code 1.98.0 or higher
|
||||
- An Anthropic account (you’ll sign in when you first open the extension). If you’re using a third-party provider like Amazon Bedrock or Google Vertex AI, see [Use third-party providers](#use-third-party-providers) instead.
|
||||
|
||||
You don’t need to install the Claude Code CLI first. However, some features like MCP server configuration require the CLI. See [VS Code extension vs. Claude Code CLI](#vs-code-extension-vs-claude-code-cli) for details.
|
||||
|
||||
## [](#install-the-extension) Install the extension
|
||||
|
||||
Click the link for your IDE to install directly:
|
||||
|
||||
- [Install for VS Code](vscode:extension/anthropic.claude-code)
|
||||
- [Install for Cursor](cursor:extension/anthropic.claude-code)
|
||||
|
||||
Or in VS Code, press `Cmd+Shift+X` (Mac) or `Ctrl+Shift+X` (Windows/Linux) to open the Extensions view, search for “Claude Code”, and click **Install**.
|
||||
|
||||
You may need to restart VS Code or run “Developer: Reload Window” from the Command Palette after installation.
|
||||
|
||||
## [](#get-started) Get started
|
||||
|
||||
Once installed, you can start using Claude Code through the VS Code interface:
|
||||
|
||||
1
|
||||
|
||||
Open the Claude Code panel
|
||||
|
||||
Throughout VS Code, the Spark icon indicates Claude Code: The quickest way to open Claude is to click the Spark icon in the **Editor Toolbar** (top-right corner of the editor). The icon only appears when you have a file open.Other ways to open Claude Code:
|
||||
|
||||
- **Command Palette**: `Cmd+Shift+P` (Mac) or `Ctrl+Shift+P` (Windows/Linux), type “Claude Code”, and select an option like “Open in New Tab”
|
||||
- **Status Bar**: Click **✱ Claude Code** in the bottom-right corner of the window. This works even when no file is open.
|
||||
|
||||
You can drag the Claude panel to reposition it anywhere in VS Code. See [Customize your workflow](#customize-your-workflow) for details.
|
||||
|
||||
2
|
||||
|
||||
Send a prompt
|
||||
|
||||
Ask Claude to help with your code or files, whether that’s explaining how something works, debugging an issue, or making changes.
|
||||
|
||||
Select text in the editor and press `Alt+K` to insert an @-mention with the file path and line numbers directly into your prompt.
|
||||
|
||||
Here’s an example of asking about a particular line in a file:
|
||||
|
||||
3
|
||||
|
||||
Review changes
|
||||
|
||||
When Claude wants to edit a file, it shows you a diff and asks for permission. You can accept, reject, or tell Claude what to do instead.
|
||||
|
||||
For more ideas on what you can do with Claude Code, see [Common workflows](/docs/en/common-workflows).
|
||||
|
||||
## [](#customize-your-workflow) Customize your workflow
|
||||
|
||||
Once you’re up and running, you can reposition the Claude panel or switch to terminal mode.
|
||||
|
||||
### [](#change-the-layout) Change the layout
|
||||
|
||||
You can drag the Claude panel to reposition it anywhere in VS Code. Grab the panel’s tab or title bar and drag it to:
|
||||
|
||||
- **Secondary sidebar** (default): The right side of the window
|
||||
- **Primary sidebar**: The left sidebar with icons for Explorer, Search, etc.
|
||||
- **Editor area**: Opens Claude as a tab alongside your files
|
||||
|
||||
The Spark icon only appears in the Activity Bar (left sidebar icons) when the Claude panel is docked to the left. Since Claude defaults to the right side, use the Editor Toolbar icon to open Claude.
|
||||
|
||||
### [](#switch-to-terminal-mode) Switch to terminal mode
|
||||
|
||||
By default, the extension opens a graphical chat panel. If you prefer the CLI-style interface, open the [Use Terminal setting](vscode://settings/claudeCode.useTerminal) and check the box.
|
||||
You can also open VS Code settings (`Cmd+,` on Mac or `Ctrl+,` on Windows/Linux), go to Extensions → Claude Code, and check **Use Terminal**.
|
||||
|
||||
## [](#vs-code-commands-and-shortcuts) VS Code commands and shortcuts
|
||||
|
||||
Open the Command Palette (`Cmd+Shift+P` on Mac or `Ctrl+Shift+P` on Windows/Linux) and type “Claude Code” to see all available VS Code commands for the Claude Code extension:
|
||||
|
||||
These are VS Code commands for controlling the extension. For Claude Code slash commands (like `/help` or `/compact`), not all CLI commands are available in the extension yet. See [VS Code extension vs. Claude Code CLI](#vs-code-extension-vs-claude-code-cli) for details.
|
||||
|
||||
| Command | Shortcut | Description |
|
||||
| --- | --- | --- |
|
||||
| Focus Input | `Cmd+Esc` (Mac) / `Ctrl+Esc` (Windows/Linux) | Toggle focus between editor and Claude |
|
||||
| Open in Side Bar | — | Open Claude in the left sidebar |
|
||||
| Open in Terminal | — | Open Claude in terminal mode |
|
||||
| Open in New Tab | `Cmd+Shift+Esc` (Mac) / `Ctrl+Shift+Esc` (Windows/Linux) | Open a new conversation as an editor tab |
|
||||
| Open in New Window | — | Open a new conversation in a separate window |
|
||||
| New Conversation | `Cmd+N` (Mac) / `Ctrl+N` (Windows/Linux) | Start a new conversation (when Claude is focused) |
|
||||
| Insert @-Mention Reference | `Alt+K` | Insert a reference to the current file (includes line numbers if text is selected) |
|
||||
| Show Logs | — | View extension debug logs |
|
||||
| Logout | — | Sign out of your Anthropic account |
|
||||
|
||||
Use **Open in New Tab** or **Open in New Window** to run multiple conversations simultaneously. Each tab or window maintains its own conversation history and context.
|
||||
|
||||
## [](#configure-settings) Configure settings
|
||||
|
||||
The extension has two types of settings:
|
||||
|
||||
- **Extension settings**: Open with `Cmd+,` (Mac) or `Ctrl+,` (Windows/Linux), then go to Extensions → Claude Code.
|
||||
|
||||
| Setting | Description |
|
||||
| --- | --- |
|
||||
| Selected Model | Default model for new conversations. Change per-session with `/model`. |
|
||||
| Use Terminal | Launch Claude in terminal mode instead of graphical panel |
|
||||
| Initial Permission Mode | Controls approval prompts for file edits and commands. Defaults to `default` (ask before each action). |
|
||||
| Preferred Location | Default location: sidebar (right) or panel (new tab) |
|
||||
| Autosave | Auto-save files before Claude reads or writes them |
|
||||
| Use Ctrl+Enter to Send | Use Ctrl/Cmd+Enter instead of Enter to send prompts |
|
||||
| Enable New Conversation Shortcut | Enable Cmd/Ctrl+N to start a new conversation |
|
||||
| Respect Git Ignore | Exclude .gitignore patterns from file searches |
|
||||
| Environment Variables | Set environment variables for the Claude process. **Not recommended**—use [Claude Code settings](/docs/en/settings) instead so configuration is shared between extension and CLI. |
|
||||
| Disable Login Prompt | Skip authentication prompts (for third-party provider setups) |
|
||||
| Allow Dangerously Skip Permissions | Bypass all permission prompts. **Use with extreme caution**—recommended only for isolated sandboxes with no internet access. |
|
||||
| Claude Process Wrapper | Executable path used to launch the Claude process |
|
||||
- **Claude Code settings** (`~/.claude/settings.json`): These settings are shared between the VS Code extension and the CLI. Use this file for allowed commands and directories, environment variables, hooks, and MCP servers. See the [settings documentation](/docs/en/settings) for details.
|
||||
|
||||
## [](#use-third-party-providers) Use third-party providers
|
||||
|
||||
By default, Claude Code connects directly to Anthropic’s API. If your organization uses Amazon Bedrock, Google Vertex AI, or Microsoft Foundry to access Claude, configure the extension to use your provider instead:
|
||||
|
||||
1
|
||||
|
||||
Disable login prompt
|
||||
|
||||
Open the [Disable Login Prompt setting](vscode://settings/claudeCode.disableLoginPrompt) and check the box.You can also open VS Code settings (`Cmd+,` on Mac or `Ctrl+,` on Windows/Linux), search for “Claude Code login”, and check **Disable Login Prompt**.
|
||||
|
||||
2
|
||||
|
||||
Configure your provider
|
||||
|
||||
Follow the setup guide for your provider:
|
||||
|
||||
- [Claude Code on Amazon Bedrock](/docs/en/amazon-bedrock)
|
||||
- [Claude Code on Google Vertex AI](/docs/en/google-vertex-ai)
|
||||
- [Claude Code on Microsoft Foundry](/docs/en/microsoft-foundry)
|
||||
|
||||
These guides cover configuring your provider in `~/.claude/settings.json`, which ensures your settings are shared between the VS Code extension and the CLI.
|
||||
|
||||
## [](#vs-code-extension-vs-claude-code-cli) VS Code extension vs. Claude Code CLI
|
||||
|
||||
The extension doesn’t yet have full feature parity with the CLI. If you need CLI-only features, you can run `claude` directly in VS Code’s integrated terminal.
|
||||
|
||||
| Feature | CLI | VS Code Extension |
|
||||
| --- | --- | --- |
|
||||
| Slash commands | [Full set](/docs/en/slash-commands) | Subset (type `/` to see available) |
|
||||
| MCP server config | Yes | No (configure via CLI, use in extension) |
|
||||
| Checkpoints | Yes | Coming soon |
|
||||
| `!` bash shortcut | Yes | No |
|
||||
| Tab completion | Yes | No |
|
||||
|
||||
### [](#run-cli-in-vs-code) Run CLI in VS Code
|
||||
|
||||
To use the CLI while staying in VS Code, open the integrated terminal (`` Ctrl+` `` on Windows/Linux or `` Cmd+` `` on Mac) and run `claude`. The CLI automatically integrates with your IDE for features like diff viewing and diagnostic sharing.
|
||||
If using an external terminal, run `/ide` inside Claude Code to connect it to VS Code.
|
||||
|
||||
### [](#switch-between-extension-and-cli) Switch between extension and CLI
|
||||
|
||||
The extension and CLI share the same conversation history. To continue an extension conversation in the CLI, run `claude --resume` in the terminal. This opens an interactive picker where you can search for and select your conversation.
|
||||
|
||||
## [](#security-considerations) Security considerations
|
||||
|
||||
With auto-edit permissions enabled, Claude Code can modify VS Code configuration files (like `settings.json` or `tasks.json`) that VS Code may execute automatically. This could potentially bypass Claude Code’s normal permission prompts.
|
||||
To reduce risk when working with untrusted code:
|
||||
|
||||
- Enable [VS Code Restricted Mode](https://code.visualstudio.com/docs/editor/workspace-trust#_restricted-mode) for untrusted workspaces
|
||||
- Use manual approval mode instead of auto-accept for edits
|
||||
- Review changes carefully before accepting them
|
||||
|
||||
## [](#fix-common-issues) Fix common issues
|
||||
|
||||
### [](#extension-won’t-install) Extension won’t install
|
||||
|
||||
- Ensure you have a compatible version of VS Code (1.98.0 or later)
|
||||
- Check that VS Code has permission to install extensions
|
||||
- Try installing directly from the Marketplace website
|
||||
|
||||
### [](#spark-icon-not-visible) Spark icon not visible
|
||||
|
||||
The Spark icon appears in the **Editor Toolbar** (top-right of editor) when you have a file open. If you don’t see it:
|
||||
|
||||
1. **Open a file**: The icon requires a file to be open—having just a folder open isn’t enough
|
||||
2. **Check VS Code version**: Requires 1.98.0 or higher (Help → About)
|
||||
3. **Restart VS Code**: Run “Developer: Reload Window” from the Command Palette
|
||||
4. **Disable conflicting extensions**: Temporarily disable other AI extensions (Cline, Continue, etc.)
|
||||
5. **Check workspace trust**: The extension doesn’t work in Restricted Mode
|
||||
|
||||
Alternatively, click ”✱ Claude Code” in the **Status Bar** (bottom-right corner)—this works even without a file open. You can also use the **Command Palette** (`Cmd+Shift+P` / `Ctrl+Shift+P`) and type “Claude Code”.
|
||||
|
||||
### [](#claude-code-never-responds) Claude Code never responds
|
||||
|
||||
If Claude Code isn’t responding to your prompts:
|
||||
|
||||
1. **Check your internet connection**: Ensure you have a stable internet connection
|
||||
2. **Start a new conversation**: Try starting a fresh conversation to see if the issue persists
|
||||
3. **Try the CLI**: Run `claude` from the terminal to see if you get more detailed error messages
|
||||
4. **File a bug report**: If the problem continues, [file an issue on GitHub](https://github.com/anthropics/claude-code/issues) with details about the error
|
||||
|
||||
### [](#standalone-cli-not-connecting-to-ide) Standalone CLI not connecting to IDE
|
||||
|
||||
- Ensure you’re running Claude Code from VS Code’s integrated terminal (not an external terminal)
|
||||
- Ensure the CLI for your IDE variant is installed:
|
||||
- VS Code: `code` command should be available
|
||||
- Cursor: `cursor` command should be available
|
||||
- Windsurf: `windsurf` command should be available
|
||||
- VSCodium: `codium` command should be available
|
||||
- If the command isn’t available, install it from the Command Palette → “Shell Command: Install ‘code’ command in PATH”
|
||||
|
||||
## [](#uninstall-the-extension) Uninstall the extension
|
||||
|
||||
To uninstall the Claude Code extension:
|
||||
|
||||
1. Open the Extensions view (`Cmd+Shift+X` on Mac or `Ctrl+Shift+X` on Windows/Linux)
|
||||
2. Search for “Claude Code”
|
||||
3. Click **Uninstall**
|
||||
|
||||
To also remove extension data and reset all settings:
|
||||
|
||||
```bash
|
||||
rm -rf ~/.vscode/globalStorage/anthropic.claude-code
|
||||
```
|
||||
|
||||
For additional help, see the [troubleshooting guide](/docs/en/troubleshooting).
|
||||
|
||||
## [](#next-steps) Next steps
|
||||
|
||||
Now that you have Claude Code set up in VS Code:
|
||||
|
||||
- [Explore common workflows](/docs/en/common-workflows) to get the most out of Claude Code
|
||||
- [Set up MCP servers](/docs/en/mcp) to extend Claude’s capabilities with external tools. Configure servers using the CLI, then use them in the extension.
|
||||
- [Configure Claude Code settings](/docs/en/settings) to customize allowed commands, hooks, and more. These settings are shared between the extension and CLI.
|
||||
@@ -0,0 +1,3 @@
|
||||
requests>=2.28.0
|
||||
beautifulsoup4>=4.12.0
|
||||
markdownify>=0.11.0
|
||||
Reference in New Issue
Block a user