# Creating Components
Source: https://davila7-claude-code-templates-86.mintlify.app/advanced/creating-components
Build custom agents, commands, MCPs, hooks, and settings for Claude Code
# Creating Components
Extend Claude Code with custom components tailored to your workflow.
## Component Types
Claude Code supports five component types:
| Type | Format | Purpose | Examples |
| ------------ | ------- | ----------------------------------- | ------------------------------------ |
| **Agents** | `.md` | AI specialists for specific domains | `react-expert`, `security-auditor` |
| **Commands** | `.md` | Custom slash commands | `/deploy`, `/test-coverage` |
| **MCPs** | `.json` | External service integrations | GitHub, PostgreSQL, AWS |
| **Hooks** | `.json` | Automation triggers | Pre-commit checks, notifications |
| **Settings** | `.json` | Claude Code configuration | Performance tuning, UI customization |
## Agent Components
Agents are AI specialists with focused expertise.
### Agent File Structure
Agents use Markdown with YAML frontmatter:
````markdown theme={null}
---
name: react-performance-expert
description: React performance optimization specialist. Expert in React.memo, useMemo, useCallback, code splitting, and bundle optimization.
tools: Read, Write, Grep, Bash
model: opus
---
You are a React Performance Expert specializing in optimizing React applications for speed and efficiency.
## Core Expertise
### Performance Optimization Techniques
- **Memoization**: React.memo, useMemo, useCallback
- **Code Splitting**: Dynamic imports, lazy loading
- **Bundle Optimization**: Tree shaking, chunk splitting
- **Rendering Optimization**: Virtual scrolling, windowing
### Analysis Process
1. **Identify Bottlenecks**
- Profile component render times
- Analyze bundle size
- Check for unnecessary re-renders
2. **Apply Optimizations**
```jsx
// Memoize expensive computations
const sortedItems = useMemo(
() => items.sort((a, b) => a.value - b.value),
[items]
);
````
3. **Measure Impact**
* Before/after benchmarks
* Bundle size reduction
* Lighthouse scores
## Guidelines
When optimizing React applications:
* Profile first, optimize second
* Focus on measurable improvements
* Balance performance with code readability
* Document optimization decisions
````
### YAML Frontmatter Fields
```yaml
---
name: agent-name # Hyphenated identifier
description: Brief description of agent expertise and use cases
tools: Read, Write, Grep # Available tools (optional)
model: opus # Preferred model: opus, sonnet, haiku (optional)
---
````
**Required fields:**
* `name` - Unique identifier (kebab-case)
* `description` - Clear, concise expertise description
**Optional fields:**
* `tools` - Comma-separated list of allowed tools
* `model` - Preferred Claude model variant
Use `model: opus` for complex reasoning tasks, `model: sonnet` for balanced performance, or `model: haiku` for speed.
### Agent Categories
Organize agents by domain:
```
components/agents/
├── development-team/ # Full-stack developers, architects
├── domain-experts/ # Security, performance, accessibility
├── creative-team/ # Content, design, UX specialists
├── business-team/ # Product managers, analysts
└── development-tools/ # Tool specialists, DevOps
```
Create new categories as needed:
```bash theme={null}
mkdir -p components/agents/data-science
touch components/agents/data-science/ml-engineer.md
```
### Example: Security Auditor Agent
````markdown theme={null}
---
name: security-auditor
description: Security specialist for vulnerability detection, code review, and compliance. Expert in OWASP Top 10, secure coding practices, and penetration testing.
tools: Read, Grep, Bash, WebSearch
model: opus
---
You are a Security Auditor specializing in application security, vulnerability assessment, and secure development practices.
## Security Framework
### OWASP Top 10 Coverage
1. **Injection Flaws**
- SQL injection detection
- Command injection prevention
- XSS vulnerability scanning
2. **Authentication Issues**
- Weak password policies
- Session management flaws
- Multi-factor authentication gaps
3. **Sensitive Data Exposure**
- Hardcoded secrets detection
- Encryption at rest/transit
- API key exposure
### Audit Process
**Reconnaissance** - Map attack surface
**Static Analysis** - Scan code for vulnerabilities
**Dynamic Testing** - Runtime security testing
**Reporting** - Document findings with severity ratings
### Code Review Checklist
```javascript
// ❌ Bad: SQL Injection vulnerability
const query = `SELECT * FROM users WHERE id = ${userId}`;
// ✅ Good: Parameterized query
const query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [userId]);
````
## Security Tools
* **Static Analysis**: ESLint security plugins, Semgrep
* **Dependency Scanning**: npm audit, Snyk
* **Secret Detection**: git-secrets, TruffleHog
* **Penetration Testing**: Burp Suite, OWASP ZAP
Provide actionable security recommendations with code examples and remediation steps.
````
## Command Components
Commands add custom slash commands to Claude Code.
### Command File Structure
Commands also use Markdown format:
```markdown
# /performance-audit
Run comprehensive performance audit on the current project.
## Purpose
Analyzes application performance across multiple dimensions:
- Bundle size and composition
- Runtime performance metrics
- Network waterfall analysis
- Core Web Vitals assessment
## Usage
```bash
/performance-audit
/performance-audit --target build/
/performance-audit --format json
````
## Implementation
1. **Bundle Analysis**
```bash theme={null}
npx webpack-bundle-analyzer build/stats.json
```
2. **Lighthouse Audit**
```bash theme={null}
npx lighthouse https://localhost:3000 --output=json
```
3. **Generate Report**
* Bundle size breakdown
* Performance score
* Optimization recommendations
## Output Format
```json theme={null}
{
"performance": {
"score": 87,
"metrics": {
"fcp": 1.2,
"lcp": 2.1,
"cls": 0.05
}
},
"bundle": {
"size": "245KB",
"gzipped": "89KB"
}
}
```
## Recommendations
Based on audit results, suggest:
* Code splitting opportunities
* Lazy loading strategies
* Image optimization
* Caching improvements
```
### Command Categories
```
components/commands/
├── code-generation/ # Generate code, tests, docs
├── analysis/ # Code analysis, optimization
├── project-management/ # File operations, structure
├── testing/ # Test generation, validation
└── deployment/ # Build, deploy, CI/CD
````
## MCP Components
MCPs (Model Context Protocol) integrate external services.
### MCP File Structure
MCPs use JSON format:
```json
{
"description": "PostgreSQL database integration for Claude Code",
"mcpServers": {
"postgresql": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "postgresql://user:password@localhost:5432/dbname"
}
}
}
}
````
### Required Fields
```json theme={null}
{
"description": "Clear description of MCP functionality",
"mcpServers": {
"server-name": {
"command": "executable-path",
"args": ["array", "of", "arguments"],
"env": {
"ENV_VAR": ""
}
}
}
}
```
**Never hardcode secrets in MCP files.** Always use placeholder values like `` or ``.
### Environment Variables
Use placeholders for sensitive data:
```json theme={null}
{
"env": {
"API_KEY": "",
"API_SECRET": "",
"DATABASE_URL": ""
}
}
```
Users replace placeholders after installation:
```bash theme={null}
# After installing MCP
export API_KEY=actual_key_value
export DATABASE_URL=postgresql://localhost:5432/mydb
```
### Example: GitHub MCP
```json theme={null}
{
"description": "GitHub integration for repository management, issue tracking, and PR operations",
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "",
"GITHUB_OWNER": "",
"GITHUB_REPO": ""
}
}
}
}
```
### MCP Categories
```
components/mcps/
├── integration/ # GitHub, GitLab, Jira
├── database/ # PostgreSQL, MySQL, MongoDB
├── cloud/ # AWS, Azure, GCP
├── devtools/ # Build tools, testing frameworks
└── ai-services/ # OpenAI, Anthropic, other AI APIs
```
## Hook Components
Hooks automate actions based on events.
### Hook File Structure
```json theme={null}
{
"description": "Send desktop notifications when Claude Code operations complete",
"hooks": {
"PostToolUse": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "if command -v osascript >/dev/null 2>&1; then osascript -e 'display notification \"Tool: $CLAUDE_TOOL_NAME completed\" with title \"Claude Code\"'; elif command -v notify-send >/dev/null 2>&1; then notify-send 'Claude Code' \"Tool: $CLAUDE_TOOL_NAME completed\"; fi"
}
]
}
]
}
}
```
### Hook Types
* **PreToolUse** - Before tool execution
* **PostToolUse** - After tool execution
* **PreConversation** - Before conversation starts
* **PostConversation** - After conversation ends
### Example: Git Auto-Add Hook
```json theme={null}
{
"description": "Automatically stage modified files after Claude Code edits them",
"hooks": {
"PostToolUse": [
{
"matcher": "Edit",
"hooks": [
{
"type": "command",
"command": "git add $CLAUDE_EDITED_FILE"
}
]
}
]
}
}
```
### Available Variables
* `$CLAUDE_TOOL_NAME` - Name of tool executed
* `$CLAUDE_EDITED_FILE` - Path to edited file
* `$CLAUDE_PROJECT_PATH` - Current project directory
* `$CLAUDE_CONVERSATION_ID` - Active conversation ID
### Hook Categories
```
components/hooks/
├── automation/ # Deployment, notifications
├── git-workflow/ # Git operations, commits
├── development-tools/ # Linting, formatting
├── testing/ # Test runners, coverage
└── monitoring/ # Logging, analytics
```
## Settings Components
Settings configure Claude Code behavior.
### Settings File Structure
```json theme={null}
{
"description": "Enable read-only mode to prevent file modifications",
"allowedTools": ["Read", "Grep", "Glob", "Bash"],
"deniedTools": ["Write", "Edit"],
"showDenialMessage": true,
"denialMessage": "Read-only mode is active. File modifications are disabled."
}
```
### Common Settings
**Performance:**
```json theme={null}
{
"description": "High-performance configuration for large codebases",
"cacheSize": 1024,
"maxConcurrentTools": 5,
"timeout": 120000
}
```
**UI Customization:**
```json theme={null}
{
"description": "Dark theme with custom syntax highlighting",
"theme": "dark",
"syntaxHighlighting": true,
"fontFamily": "JetBrains Mono",
"fontSize": 14
}
```
## Component Review Process
**CRITICAL: Use the component-reviewer agent for ALL component changes**
Before submitting any component, use:
```bash theme={null}
Use the component-reviewer agent to review [component-path]
```
### Validation Checklist
The `component-reviewer` agent checks:
* ✅ Valid YAML frontmatter (for agents/commands)
* ✅ Valid JSON structure (for MCPs/hooks/settings)
* ✅ Required fields present
* ✅ Kebab-case naming conventions
* ✅ No hardcoded secrets or API keys
* ✅ Relative paths only (no absolute paths)
* ✅ Clear, specific descriptions
* ✅ Correct category placement
### Example Review
```bash theme={null}
# After creating an agent
Use the component-reviewer agent to review cli-tool/components/agents/development-team/react-expert.md
```
**Reviewer output:**
```
✅ PASSED: Valid YAML frontmatter
✅ PASSED: Required fields present (name, description)
✅ PASSED: Kebab-case naming convention
⚠️ WARNING: Consider adding specific use cases to description
📋 SUGGESTION: Add code examples for common patterns
✅ Component is ready for submission
```
## Publishing Components
Write component file in appropriate category directory
```bash theme={null}
Use the component-reviewer agent to review [path]
```
Address critical issues and warnings
```bash theme={null}
python scripts/generate_components_json.py
```
```bash theme={null}
npx claude-code-templates@latest --agent your-agent --dry-run
```
Open pull request with clear description and examples
### Catalog Generation
After creating/modifying components:
```bash theme={null}
python scripts/generate_components_json.py
```
This updates `docs/components.json` with:
* Component metadata
* File contents
* Installation instructions
* Search indexes
## Best Practices
### Naming Conventions
**DO:**
* ✅ `react-performance-expert` (kebab-case)
* ✅ `security-auditor` (descriptive)
* ✅ `github-integration` (clear purpose)
**DON'T:**
* ❌ `ReactExpert` (PascalCase)
* ❌ `expert_agent` (snake\_case)
* ❌ `myagent` (vague)
### Descriptions
**Good descriptions:**
```yaml theme={null}
description: React performance optimization specialist. Expert in React.memo, useMemo, useCallback, code splitting, and bundle optimization.
```
**Poor descriptions:**
```yaml theme={null}
description: Helps with React # Too vague
```
### Security
**Never include:**
* API keys or tokens
* Passwords or credentials
* Absolute file paths (`/Users/you/...`)
* Personal information
* Proprietary code or business logic
**Use placeholders:**
```json theme={null}
{
"env": {
"API_KEY": ""
}
}
```
## Next Steps
Full contribution guidelines and workflow
Browse 900+ existing components for inspiration
# Remote Access
Source: https://davila7-claude-code-templates-86.mintlify.app/advanced/remote-access
Access Claude Code analytics and chat dashboards remotely using Cloudflare Tunnel
# Remote Access
Monitor Claude Code sessions from anywhere using secure Cloudflare Tunnels.
## Overview
Cloudflare Tunnel creates secure, temporary public URLs for local Claude Code dashboards:
* **Analytics Dashboard** - Real-time session monitoring
* **Chat Interface** - Mobile-optimized conversation viewer
* **2025 Year in Review** - Usage statistics dashboard
Tunnels are **temporary and private** - they expire when you close the dashboard and require the full URL to access.
## Setup
### Install Cloudflared
```bash theme={null}
brew install cloudflared
```
```bash theme={null}
winget install --id Cloudflare.cloudflared
```
```bash theme={null}
# Debian/Ubuntu
wget -q https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb
sudo dpkg -i cloudflared-linux-amd64.deb
# Or via package manager
sudo apt-get install cloudflared
```
Verify installation:
```bash theme={null}
cloudflared version
# cloudflared version 2024.2.1
```
## Using Remote Access
### Analytics Dashboard
Launch analytics with remote access:
```bash theme={null}
npx claude-code-templates@latest --analytics --tunnel
```
**Output:**
```
🚀 Starting Claude Code Analytics Dashboard...
🚀 Creating secure tunnel...
╔════════════════════════════════════════════════════════════╗
║ ║
║ 🌍 CLOUDFLARE TUNNEL ACTIVE ║
║ ║
║ 🔗 https://abc-def-ghi.trycloudflare.com ║
║ ║
║ 🔒 This tunnel is private and secure - only ║
║ accessible by you ║
║ ║
╚════════════════════════════════════════════════════════════╝
📊 Analytics running locally: http://localhost:3333
```
Share the `trycloudflare.com` URL to access from:
* Mobile devices
* Remote machines
* Team members (temporary access)
### Chat Interface
Mobile-optimized chat viewer with tunnel:
```bash theme={null}
npx claude-code-templates@latest --chats --tunnel
```
**Output:**
```
💬 Starting Claude Code Chat Interface...
☁️ Cloudflare Tunnel ready: https://xyz-123-abc.trycloudflare.com
📱 Local access: http://localhost:3334
☁️ Remote access: https://xyz-123-abc.trycloudflare.com
🌐 Opening remote URL: https://xyz-123-abc.trycloudflare.com
```
The remote URL opens automatically in your default browser.
### 2025 Year in Review
Share your usage statistics:
```bash theme={null}
npx claude-code-templates@latest --2025 --tunnel
```
## How It Works
### Tunnel Architecture
Cloudflare Tunnel creates a secure connection:
```
Your Machine Cloudflare Edge Internet
┌─────────────────┐ ┌────────────────┐ ┌─────────┐
│ Dashboard │ │ │ │ │
│ localhost:3333 │<─────────>│ Tunnel Proxy │<─────>│ Browser │
│ │ WebSocket│ │ HTTPS │ │
└─────────────────┘ └────────────────┘ └─────────┘
```
**Key features:**
* **No port forwarding** required
* **No firewall changes** needed
* **Automatic HTTPS** with valid certificates
* **WebSocket support** for real-time updates
### Implementation
The tunnel launcher (from `src/analytics.js` and `src/chats-mobile.js`):
```javascript theme={null}
async startCloudflareTunnel() {
// Check if cloudflared is installed
const checkProcess = spawn('cloudflared', ['version'], { stdio: 'pipe' });
// Start tunnel
this.cloudflareProcess = spawn('cloudflared', [
'tunnel',
'--url', `http://localhost:${this.port}`,
'--no-autoupdate'
]);
// Parse tunnel URL from output
this.cloudflareProcess.stderr.on('data', (data) => {
const output = data.toString();
const urlMatch = output.match(/https:\/\/[a-zA-Z0-9.-]+\.trycloudflare\.com/);
if (urlMatch) {
const tunnelUrl = urlMatch[0];
console.log(`☁️ Cloudflare Tunnel ready: ${tunnelUrl}`);
}
});
}
```
### URL Format
Tunnel URLs follow the pattern:
```
https://{random-slug}.trycloudflare.com
```
Examples:
* `https://abc-def-ghi.trycloudflare.com`
* `https://xyz-123-abc.trycloudflare.com`
* `https://quick-fire-light.trycloudflare.com`
Tunnel URLs are **randomly generated** each time. Don't bookmark them - they won't work after the tunnel closes.
## Mobile Access
Access dashboards from your phone or tablet:
```bash theme={null}
npx claude-code-templates@latest --chats --tunnel
```
```
☁️ Remote access: https://xyz-123-abc.trycloudflare.com
```
* Send URL to yourself (Slack, email, SMS)
* Scan QR code (if using `--qr` flag)
* Type URL directly in mobile browser
### Mobile Optimization
The chat interface is optimized for mobile:
```css theme={null}
/* From chats-mobile.js */
@media (max-width: 768px) {
.conversation-card {
padding: 1rem;
font-size: 0.9rem;
}
.message-content {
max-width: 100%;
overflow-x: auto;
}
}
```
**Mobile features:**
* Responsive layouts
* Touch-optimized controls
* Swipe gestures
* Auto-scrolling conversations
## Security
### Tunnel Privacy
**Free Cloudflare Tunnels are:**
* Private (require full random URL)
* Temporary (expire when you close the tunnel)
* Not indexed by search engines
* Not guessable (URLs have high entropy)
However, anyone with the URL can access the dashboard while the tunnel is active.
### Best Practices
**DO:**
* ✅ Use tunnels for temporary access
* ✅ Share URLs through private channels (Slack DM, encrypted email)
* ✅ Close tunnel when done (`Ctrl+C` in terminal)
* ✅ Use local access (`localhost`) when possible
**DON'T:**
* ❌ Share tunnel URLs publicly
* ❌ Post tunnel URLs on social media
* ❌ Leave tunnels running indefinitely
* ❌ Use tunnels for sensitive production data
### Protecting Sensitive Data
If dashboards show sensitive information:
```bash theme={null}
# 1. Don't use --tunnel flag
npx claude-code-templates@latest --analytics
# 2. Access via localhost only
# Open: http://localhost:3333
# 3. Or use SSH tunneling for secure remote access
ssh -L 3333:localhost:3333 user@remote-machine
```
## Advanced Usage
### Custom Tunnel Configuration
Cloudflared supports additional options:
```bash theme={null}
# Custom tunnel with specific hostname
cloudflared tunnel --url http://localhost:3333 --hostname custom-name.trycloudflare.com
# With authentication
cloudflared tunnel --url http://localhost:3333 --credentials-file /path/to/credentials.json
```
Modify the launcher in `src/analytics.js` to add custom flags:
```javascript theme={null}
this.cloudflareProcess = spawn('cloudflared', [
'tunnel',
'--url', `http://localhost:${this.port}`,
'--no-autoupdate',
// Add custom flags here
'--protocol', 'http2',
'--compression-quality', '5'
]);
```
### Persistent Named Tunnels
For longer-term access, create a named tunnel:
```bash theme={null}
# Login to Cloudflare
cloudflared login
# Create named tunnel
cloudflared tunnel create claude-analytics
# Configure tunnel
cat > ~/.cloudflared/config.yml <
Named tunnels require a Cloudflare account and domain. Free tier is sufficient for personal use.
### Tunnel Monitoring
Monitor tunnel status:
```bash theme={null}
# Check tunnel process
ps aux | grep cloudflared
# View tunnel logs
cloudflared tunnel info claude-analytics
# List active tunnels
cloudflared tunnel list
```
## Troubleshooting
### Tunnel Not Starting
```
❌ Error: cloudflared command not found
```
**Solutions:**
1. Install cloudflared (see Setup section)
2. Add to PATH:
```bash theme={null}
export PATH="$PATH:/path/to/cloudflared"
```
3. Use full path in scripts
### No Tunnel URL Displayed
```
🚀 Creating secure tunnel...
[cloudflared] ... (output but no URL)
```
**Debugging:**
```bash theme={null}
# Test cloudflared manually
cloudflared tunnel --url http://localhost:3333
# Check for errors in output
# Look for firewall/network issues
```
### Tunnel Disconnects Frequently
**Causes:**
* Network instability
* Firewall blocking WebSocket connections
* ISP restrictions
**Solutions:**
```bash theme={null}
# Use HTTP/2 protocol (more stable)
cloudflared tunnel --url http://localhost:3333 --protocol http2
# Increase heartbeat interval
cloudflared tunnel --url http://localhost:3333 --heartbeat-interval 30s
```
### WebSocket Errors
```
WebSocket connection failed: Error during WebSocket handshake
```
Cloudflare Tunnel supports WebSocket by default, but check:
```bash theme={null}
# Verify cloudflared version (ensure latest)
cloudflared version
# Update if needed
brew upgrade cloudflared # macOS
```
## Alternatives to Tunnels
### SSH Port Forwarding
For secure remote access without Cloudflare:
```bash theme={null}
# On remote machine
ssh -R 3333:localhost:3333 user@remote-server
# Or reverse tunnel
ssh -L 3333:localhost:3333 user@remote-machine
```
### VPN Access
Access via VPN:
```bash theme={null}
# Connect to VPN
sudo openvpn --config company.ovpn
# Start dashboard (local only)
npx claude-code-templates@latest --analytics
# Access via VPN IP
http://10.0.0.5:3333
```
### ngrok Alternative
Similar tunnel service:
```bash theme={null}
# Install ngrok
brew install ngrok # macOS
# Start tunnel
ngrok http 3333
```
## Examples
### Monitor from Mobile While Coding
```bash theme={null}
# On development machine
npx claude-code-templates@latest --analytics --tunnel
# Copy URL to phone
# Monitor Claude Code activity in real-time from mobile
```
### Share Demo with Team
```bash theme={null}
# Start chat interface with tunnel
npx claude-code-templates@latest --chats --tunnel
# Share URL in Slack:
# "Check out this conversation: https://xyz.trycloudflare.com"
```
### Remote Debugging
```bash theme={null}
# Developer 1: Start analytics with tunnel
npx claude-code-templates@latest --analytics --tunnel
# Developer 2: Access from home
# Open tunnel URL
# See real-time conversation state and debug issues
```
## Performance Considerations
### Latency
Cloudflare Tunnel adds minimal latency:
* **Local**: Less than 1ms
* **Tunnel**: 10-50ms (depending on location)
* **WebSocket**: Real-time updates still feel instant
### Bandwidth
Analytics dashboard bandwidth usage:
* **Initial load**: \~500KB (HTML, CSS, JS)
* **WebSocket updates**: \~1-5KB per message
* **Polling**: \~10KB per refresh
### Scaling
Free tunnels support:
* Unlimited bandwidth
* 100+ concurrent connections
* WebSocket connections
For higher traffic, consider named tunnels with load balancing.
## Next Steps
Build custom agents, commands, and MCPs
Run Claude Code in isolated environments
# Sandbox Execution
Source: https://davila7-claude-code-templates-86.mintlify.app/advanced/sandbox-execution
Execute Claude Code in isolated cloud and local sandboxes with E2B, Docker, and Cloudflare Workers
# Sandbox Execution
Run Claude Code in completely isolated environments for safe experimentation, testing, or executing untrusted code.
## Overview
Claude Code Templates supports three sandbox providers:
* **E2B** - Cloud-based sandboxes with automatic cleanup
* **Docker** - Local containerized environments
* **Cloudflare Workers** - Serverless edge computing
## E2B Cloud Sandboxes
E2B provides isolated cloud environments perfect for safe code execution without affecting your local machine.
### Setup
Sign up at [e2b.dev](https://e2b.dev) and get your API key from the dashboard.
```bash theme={null}
export E2B_API_KEY=your_api_key_here
export ANTHROPIC_API_KEY=your_anthropic_key
```
```bash theme={null}
npx claude-code-templates@latest --sandbox e2b --prompt "Create a React todo app"
```
### Using E2B with Components
Install specific components before execution:
```bash theme={null}
npx claude-code-templates@latest \
--sandbox e2b \
--agent react-expert,frontend-developer \
--prompt "Build a responsive dashboard with charts"
```
The sandbox will:
1. Create an isolated E2B cloud environment
2. Install specified agents/commands/MCPs
3. Execute your prompt with Claude Code
4. Download all generated files to your local machine
5. Automatically clean up the sandbox
### How It Works
The E2B launcher (`e2b-launcher.py`) handles the entire lifecycle:
```python theme={null}
# Executed automatically when you use --sandbox e2b
python e2b-launcher.py \
"your prompt" \
"--agent react-expert" \
$E2B_API_KEY \
$ANTHROPIC_API_KEY
```
**Key Features:**
* **Automatic timeout management** - Extends sandbox lifetime during operations
* **Real-time streaming** - See Claude Code output as it happens
* **File download** - All generated files copied to `sandbox-{id}/` directory
* **WebSocket retry logic** - Handles connection issues gracefully
* **Progress indicators** - Visual feedback during execution
Files are downloaded to a project directory named `sandbox-{id}` in your current working directory, preserving the full directory structure.
### Environment Variables
Pass additional environment variables to the sandbox:
```bash theme={null}
export E2B_API_KEY=your_key
export ANTHROPIC_API_KEY=your_key
export DATABASE_URL=postgres://...
npx claude-code-templates@latest \
--sandbox e2b \
--prompt "Set up database migrations"
```
The sandbox environment inherits:
* `ANTHROPIC_API_KEY` (required)
* `E2B_API_KEY` (required)
* Custom environment variables you set
E2B sandboxes have a 10-15 minute timeout. The launcher automatically extends this to 15 minutes for long-running operations.
### Monitoring Sandbox Execution
The E2B launcher provides real-time feedback:
```
☁️ EXECUTING CLAUDE CODE IN SECURE CLOUD SANDBOX
════════════════════════════════════════════════
⏳ Starting execution...
🔒 Isolated E2B environment active
📡 Streaming real-time output below:
────────────────────────────────────────────────
📝 LIVE OUTPUT:
────────────────────────────────────────────────
🎯 Claude Code started responding:
[Real-time output from Claude Code...]
```
### Troubleshooting E2B
**WebSocket Connection Failed**
```
⚠️ WebSocket connection failed, retrying in 3 seconds...
```
This is usually caused by:
* Network/firewall blocking WebSocket connections
* Corporate proxy restrictions
* Temporary E2B service issues
**Solutions:**
* Try from a different network
* Check firewall/proxy settings
* Wait a few minutes and retry
**No Files Generated**
If the sandbox completes but no files appear:
```bash theme={null}
# The launcher searches for common file extensions
# Check the sandbox output for file paths
# Files are saved to: sandbox-{id}/
```
## Docker Local Sandboxes
Run Claude Code in isolated Docker containers on your local machine.
### Prerequisites
Download from [docker.com](https://docs.docker.com/get-docker/)
Ensure Docker Desktop is running or start the daemon:
```bash theme={null}
# macOS/Windows: Launch Docker Desktop
# Linux:
sudo systemctl start docker
```
```bash theme={null}
export ANTHROPIC_API_KEY=your_api_key
```
### Running Docker Sandboxes
```bash theme={null}
npx claude-code-templates@latest \
--sandbox docker \
--prompt "Create a Python FastAPI server"
```
**First run:**
```
🔨 Checking Docker image...
📦 Building Docker image (this may take a few minutes)...
```
**Subsequent runs:**
```
🔨 Checking Docker image...
✅ Image already exists
```
### Docker Architecture
The Docker launcher (`docker-launcher.js`) orchestrates:
1. **Image build** - Creates `claude-sandbox` image with Node.js and dependencies
2. **Volume mounting** - Maps `./output/` for file persistence
3. **Environment injection** - Passes `ANTHROPIC_API_KEY` securely
4. **Container execution** - Runs `execute.js` with your prompt
5. **Cleanup** - Removes container with `--rm` flag
```javascript theme={null}
// Executed automatically
node docker-launcher.js \
"your prompt" \
"--agent python-expert"
```
### Output Directory
All files are saved to `./output/` in your current directory:
```bash theme={null}
output/
├── main.py
├── requirements.txt
├── Dockerfile
└── README.md
```
The Docker container runs with `--rm` flag, so it's automatically removed after execution. Only files in the mounted `output/` directory persist.
### Custom Docker Configuration
Modify the Dockerfile in `components/sandbox/docker/Dockerfile`:
```dockerfile theme={null}
FROM node:18-alpine
# Add system dependencies
RUN apk add --no-cache python3 py3-pip git
# Install Claude Code
RUN npm install -g claude-code
# Set working directory
WORKDIR /app
# Copy execution script
COPY execute.js /app/
CMD ["node", "execute.js"]
```
## Cloudflare Workers Sandbox
Run Claude Code in serverless edge environments.
### Setup Cloudflare Sandbox
```bash theme={null}
npx claude-code-templates@latest \
--sandbox cloudflare \
--prompt "Create a serverless API"
```
This installs the Cloudflare sandbox components to `.claude/sandbox/cloudflare/`:
```
.claude/sandbox/cloudflare/
├── src/index.ts # Main worker entry point
├── launcher.ts # Local development launcher
├── monitor.ts # Execution monitoring
├── wrangler.toml # Cloudflare configuration
└── package.json # Dependencies
```
### Deploying to Cloudflare
```bash theme={null}
npm install -g wrangler
```
```bash theme={null}
wrangler login
```
```bash theme={null}
cd .claude/sandbox/cloudflare
wrangler deploy
```
### Local Development
```bash theme={null}
cd .claude/sandbox/cloudflare
npm run dev
```
Access the worker at `http://localhost:8787`
## Sandbox Comparison
| Feature | E2B | Docker | Cloudflare |
| --------------- | ----------------- | ---------------------- | ------------------- |
| **Environment** | Cloud | Local | Edge |
| **Setup Time** | Instant | 2-5 min (first build) | Moderate |
| **Isolation** | Complete | Complete | Sandboxed |
| **File Access** | Downloaded | Mounted volume | Limited |
| **Internet** | ✅ Yes | ✅ Yes | ✅ Yes |
| **Cleanup** | Automatic | Automatic (container) | Manual |
| **Cost** | Pay per use | Free (local resources) | Free tier available |
| **Best For** | Quick experiments | Offline work | Serverless APIs |
## Security Considerations
**Never run untrusted code outside a sandbox.** Always use sandbox execution when:
* Testing code from unknown sources
* Experimenting with system-level operations
* Running potentially destructive commands
* Working with sensitive data in isolated environments
### Sandbox Isolation
All sandbox providers offer:
* **Process isolation** - Code runs in separate processes
* **Filesystem isolation** - Limited access to host files
* **Network isolation** - Controlled outbound connections
* **Resource limits** - CPU, memory, and time constraints
### API Key Security
API keys are passed securely:
```bash theme={null}
# ✅ Good - Environment variables
export ANTHROPIC_API_KEY=sk-ant-...
export E2B_API_KEY=...
# ❌ Bad - Never hardcode keys
npx claude-code-templates --anthropic-api-key sk-ant-... # Visible in process list
```
## Advanced Usage
### Batch Sandbox Execution
Run multiple prompts in sequence:
```bash theme={null}
#!/bin/bash
prompts=(
"Create a REST API with Express"
"Add authentication middleware"
"Write integration tests"
)
for prompt in "${prompts[@]}"; do
npx claude-code-templates@latest \
--sandbox e2b \
--agent backend-developer \
--prompt "$prompt"
done
```
### Custom Sandbox Templates
Create your own E2B templates:
```yaml theme={null}
# e2b.toml
from = "ubuntu:22.04"
[exec]
cmd = "npm install -g claude-code"
```
### Monitoring Long-Running Tasks
The E2B monitor provides progress updates:
```python theme={null}
# From e2b-launcher.py
def show_progress():
progress_messages = [
"⏳ Still processing...",
"🔄 Claude Code is working on your request...",
"⚙️ Analyzing requirements...",
"🛠️ Building solution...",
]
```
## Examples
### Safe Code Experimentation
```bash theme={null}
npx claude-code-templates@latest \
--sandbox e2b \
--prompt "Experiment with different sorting algorithms and benchmark them"
```
### Multi-Component Project
```bash theme={null}
npx claude-code-templates@latest \
--sandbox e2b \
--agent fullstack-developer,database-expert \
--mcp postgresql \
--prompt "Create a blog platform with user authentication"
```
### Testing Framework
```bash theme={null}
npx claude-code-templates@latest \
--sandbox docker \
--agent testing-specialist \
--prompt "Set up Jest with React Testing Library and write component tests"
```
## Next Steps
Share your Claude Code sessions with team members
Access Claude Code dashboards remotely
# Session Sharing
Source: https://davila7-claude-code-templates-86.mintlify.app/advanced/session-sharing
Export, share, and clone Claude Code conversation sessions with team members
# Session Sharing
Share your Claude Code conversation history with teammates, collaborators, or across machines.
## Overview
The session sharing system allows you to:
* **Export** conversations as portable JSON files
* **Upload** sessions to cloud storage (x0.at)
* **Clone** shared sessions to continue conversations
* **Download** session context as markdown files
Implemented in `src/session-sharing.js`, this feature enables seamless collaboration.
## Exporting Sessions
### Export as Markdown
Download a conversation as a markdown file optimized for Claude Code:
```javascript theme={null}
const SessionSharing = require('./session-sharing');
const sessionSharing = new SessionSharing(conversationAnalyzer);
const result = await sessionSharing.exportSessionAsMarkdown(
conversationId,
conversationData,
{ messageLimit: 100 }
);
console.log(result.filename); // claude-context-project-2026-02-28.md
console.log(result.messageCount); // 87
```
**Markdown format:**
```markdown theme={null}
# Previous Conversation Context
> **Note to Claude Code**: This file contains the complete conversation
> history from a previous session. Read and understand this context to
> continue helping the user with their task.
**Project:** my-project
**Date:** 2026-02-28
**Messages in this export:** 87
---
## 💬 Conversation History
### Message 1: 👤 User
*2026-02-28, 10:30:15*
Create a React component for user authentication
---
### Message 2: 🤖 Assistant
*2026-02-28, 10:30:45*
I'll create an authentication component with login and signup forms...
[Tool use and results...]
```
Markdown exports are perfect for providing context to new Claude Code sessions or sharing read-only conversation history.
### Export as JSON
Export the full session data for cloning:
```javascript theme={null}
const exportData = await sessionSharing.exportSessionData(
conversationId,
conversationData,
{ messageLimit: 100 }
);
// Export format
{
"version": "1.0.0",
"exported_at": "2026-02-28T14:30:00.000Z",
"conversation": {
"id": "conv_abc123",
"project": "my-app",
"messageCount": 87,
"totalMessageCount": 150,
"wasLimited": true,
"tokens": { "input": 45000, "output": 32000 },
"model": "claude-sonnet-4-5-20250929"
},
"messages": [
{
"uuid": "msg_123",
"type": "user",
"timestamp": "2026-02-28T10:30:15.000Z",
"message": {
"id": "msg_123",
"role": "user",
"content": [{ "type": "text", "text": "Create a React component..." }]
}
},
// More messages...
],
"metadata": {
"exportTool": "claude-code-templates",
"exportVersion": "1.0.0",
"messageLimit": 100
}
}
```
## Sharing Sessions
### Upload to x0.at
Share sessions via the x0.at file hosting service:
```javascript theme={null}
const sessionData = await sessionSharing.exportSessionData(
conversationId,
conversationData
);
const shareUrl = await sessionSharing.uploadToX0(
sessionData,
conversationId
);
console.log('Share URL:', shareUrl);
// https://x0.at/abc123.json
```
**Sharing workflow:**
Convert conversation to portable JSON format
```bash theme={null}
curl -s -F "file=@session-conv_abc123.json" https://x0.at
```
Send the returned URL to collaborators:
```
https://x0.at/xyz789.json
```
**x0.at retention policy:**
* Files are kept for 3-100 days based on size
* Files are **not encrypted** by default
* Don't share sessions containing sensitive data (API keys, passwords, credentials)
### Generate Share QR Code
Create QR codes for mobile sharing:
```javascript theme={null}
const qrCode = await sessionSharing.generateQRCode(
`npx claude-code-templates@latest --clone-session ${shareUrl}`
);
console.log(qrCode.dataUrl); // Data URL for image display
```
Display the QR code in a web interface or terminal for easy mobile scanning.
## Cloning Sessions
### Clone from URL
Download and import a shared session:
```bash theme={null}
npx claude-code-templates@latest \
--clone-session https://x0.at/abc123.json
```
**Clone process:**
```
📥 Downloading session from https://x0.at/abc123.json...
✅ Session downloaded successfully
📊 Project: my-app
💬 Messages: 87
🤖 Model: claude-sonnet-4-5-20250929
✅ Session installed successfully!
📂 Location: ~/.claude/projects/my-app/conv_abc123.jsonl
💡 To continue this conversation, run:
claude --resume conv_abc123
Or open Claude Code to see it in your sessions list
```
### Clone Implementation
The cloning process (`cloneSession` method):
1. **Download** - Fetch JSON from URL using curl
2. **Validate** - Check session structure and required fields
3. **Install** - Place in `~/.claude/projects/{project}/` directory
4. **Settings** - Create `settings.json` with metadata
5. **Ready** - Session appears in Claude Code session list
```javascript theme={null}
async cloneSession(url, options = {}) {
// 1. Download
const sessionData = await this.downloadSession(url);
// 2. Validate
this.validateSessionData(sessionData);
// 3. Install
const result = await this.installSession(sessionData, options);
return result;
}
```
### Session Installation
Cloned sessions are installed to the standard Claude Code directory:
```
~/.claude/projects/my-app/
├── conv_abc123.jsonl # Conversation messages (JSONL format)
└── settings.json # Project metadata
```
**settings.json structure:**
```json theme={null}
{
"projectName": "my-app",
"projectPath": "/path/to/project",
"sharedSession": true,
"originalExport": {
"exportedAt": "2026-02-28T14:30:00.000Z",
"exportTool": "claude-code-templates",
"exportVersion": "1.0.0"
},
"importedAt": "2026-02-28T15:45:00.000Z"
}
```
Cloned sessions integrate seamlessly with Claude Code. Use `claude --resume {id}` or select them from the sessions list in the UI.
## Message Limits
Large conversations are truncated to avoid excessive file sizes:
```javascript theme={null}
// Default: Last 100 messages
const result = await sessionSharing.exportSessionData(
conversationId,
conversationData,
{ messageLimit: 100 }
);
// Custom limit
const fullExport = await sessionSharing.exportSessionData(
conversationId,
conversationData,
{ messageLimit: 500 }
);
```
**Limit indicators:**
```javascript theme={null}
if (result.wasLimited) {
console.log(`Exported ${result.messageCount} of ${result.totalMessageCount} messages`);
// Exported 100 of 237 messages
}
```
## JSONL Format
Sessions use JSONL (JSON Lines) format - one JSON object per line:
```jsonl theme={null}
{"uuid":"msg_1","type":"user","timestamp":"2026-02-28T10:30:00.000Z","message":{"role":"user","content":[{"type":"text","text":"Hello"}]}}
{"uuid":"msg_2","type":"assistant","timestamp":"2026-02-28T10:30:15.000Z","message":{"role":"assistant","content":[{"type":"text","text":"Hi there!"}]}}
```
This format allows:
* **Streaming** - Append messages without parsing entire file
* **Partial reads** - Read specific lines without loading all messages
* **Efficient parsing** - Process one message at a time
## Security & Privacy
**Before sharing sessions:**
* Remove API keys and credentials from conversation history
* Redact sensitive business logic or proprietary code
* Check for hardcoded passwords or tokens
* Verify no customer data is included
### Sanitizing Sessions
Before export, review messages for:
```javascript theme={null}
// Check for API keys
const sensitivePatterns = [
/sk-[a-zA-Z0-9]{32,}/, // Anthropic keys
/ghp_[a-zA-Z0-9]{36}/, // GitHub tokens
/AIza[a-zA-Z0-9_-]{35}/, // Google API keys
/[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}/ // Credit cards
];
// Redact sensitive content before sharing
```
### Private Sharing
For sensitive projects, use private file sharing:
1. **Export locally** - Save JSON to disk
2. **Encrypt** - Use GPG or similar encryption
3. **Share privately** - Use secure channels (Slack, email, private cloud)
4. **Decrypt** - Recipient decrypts before cloning
```bash theme={null}
# Encrypt export
gpg --encrypt --recipient teammate@example.com session.json
# Decrypt before cloning
gpg --decrypt session.json.gpg > session.json
npx claude-code-templates@latest --clone-session file://./session.json
```
## Use Cases
### Team Collaboration
Share context when handing off work:
```bash theme={null}
# Developer A exports session
cct --export-session conv_123 --upload
# Shares URL with Developer B
# Developer B clones session
cct --clone-session https://x0.at/abc.json
# Continues conversation where Developer A left off
```
### Cross-Machine Sync
Continue work on different machines:
```bash theme={null}
# On laptop
cct --export-session current --upload
# Note URL: https://x0.at/xyz.json
# On desktop
cct --clone-session https://x0.at/xyz.json
```
### Code Review Context
Provide full context for code reviews:
```bash theme={null}
# Export conversation that led to the PR
cct --export-session conv_pr_123 --markdown
# Attach claude-context-feature-2026-02-28.md to PR
```
### Onboarding
Share project setup sessions with new team members:
```bash theme={null}
# Export onboarding conversation
cct --export-session onboarding --upload
# Share with new hires
```
## API Reference
### SessionSharing Class
```javascript theme={null}
class SessionSharing {
constructor(conversationAnalyzer)
// Export as markdown
async exportSessionAsMarkdown(conversationId, conversationData, options)
// Export as JSON
async exportSessionData(conversationId, conversationData, options)
// Upload to x0.at
async uploadToX0(sessionData, conversationId)
// Clone from URL
async cloneSession(url, options)
// Generate QR code
async generateQRCode(command)
}
```
### Export Options
```javascript theme={null}
{
messageLimit: 100, // Max messages to export (default: 100)
}
```
### Clone Options
```javascript theme={null}
{
projectPath: '/path/to/project' // Override project path
}
```
## Troubleshooting
### Clone Fails with "Invalid session file"
```
❌ Failed to clone session: Invalid session file - missing version
```
**Causes:**
* Corrupted download
* Not a valid Claude Code session export
* Outdated export format
**Solutions:**
* Re-download the file
* Verify URL is correct
* Check export was created with recent version
### Upload to x0.at Fails
```
❌ Error: Invalid response from x0.at
```
**Solutions:**
* Check internet connection
* Verify x0.at service is available
* Try again in a few minutes
### Session Not Appearing in Claude Code
```bash theme={null}
# Verify installation
ls ~/.claude/projects/
# Check specific session
ls ~/.claude/projects/my-app/conv_*.jsonl
# Validate JSONL format
cat ~/.claude/projects/my-app/conv_abc123.jsonl | head -1 | jq
```
## Next Steps
Run Claude Code in isolated environments
Access analytics dashboards remotely
# Claude Code Check
Source: https://davila7-claude-code-templates-86.mintlify.app/api/claude-code-check
Automated monitoring of Claude Code releases with Discord notifications
## Endpoint
**POST/GET** `/api/claude-code-check`
Monitors the `@anthropic-ai/claude-code` npm package for new releases and sends formatted Discord notifications. Runs automatically via Vercel Cron every 30 minutes.
## Trigger Methods
### Vercel Cron (Automatic)
Configured in `vercel.json`:
```json theme={null}
{
"crons": [{
"path": "/api/claude-code-check",
"schedule": "*/30 * * * *"
}]
}
```
Runs every 30 minutes.
### Manual Trigger
```bash theme={null}
curl -X POST https://www.aitmpl.com/api/claude-code-check
```
## Process Flow
1. **Fetch latest npm version** from `https://registry.npmjs.org/@anthropic-ai/claude-code/latest`
2. **Check database** if version already notified
3. **Fetch changelog** from GitHub (`CHANGELOG.md`)
4. **Parse changes** using Claude AI (via `_parser-claude.js`)
5. **Save to database** (Neon PostgreSQL)
6. **Send Discord notification** with formatted embed
7. **Update metadata** tracking
## Response
### Success - New Version Detected
`success`
Version number detected (e.g., `1.2.3`)
Database ID of the version record
Summary of changes
Total number of changes
Change counts by type (features, fixes, improvements, breaking)
Discord notification status
Whether notification was sent
HTTP status code from Discord webhook
#### Example Success Response
```json theme={null}
{
"status": "success",
"version": "1.2.3",
"versionId": 42,
"changes": {
"total": 12,
"byType": {
"features": 5,
"fixes": 4,
"improvements": 3,
"breaking": 0
}
},
"discord": {
"sent": true,
"status": 200
}
}
```
### Success - Already Processed
`already_processed`
Version number
Explanation message
#### Example Already Processed Response
```json theme={null}
{
"status": "already_processed",
"version": "1.2.3",
"message": "Version already notified to Discord"
}
```
### Error Response (500)
Error type
Error message
Stack trace (development mode only)
#### Example Error Response
```json theme={null}
{
"error": "Internal server error",
"message": "Could not find version 1.2.3 in changelog",
"details": "Error: Could not find version 1.2.3 in changelog\n at parseVersionChangelog..."
}
```
## Discord Notification Format
The endpoint sends a rich embed to Discord:
````json theme={null}
{
"username": "Claude Code Monitor",
"avatar_url": "https://raw.githubusercontent.com/anthropics/claude-code/main/assets/icon.png",
"embeds": [{
"title": "🚀 Claude Code 1.2.3 Released",
"description": "A new version of Claude Code is available with **12 changes**!",
"url": "https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md#123",
"color": 9067510,
"fields": [
{
"name": "⚠️ Breaking Changes",
"value": "• Removed deprecated API\n• Changed config format",
"inline": false
},
{
"name": "✨ New Features",
"value": "• Added feature X\n• Added feature Y",
"inline": false
},
{
"name": "⚡ Improvements",
"value": "• Improved performance\n• Better error messages",
"inline": false
},
{
"name": "🐛 Bug Fixes",
"value": "• Fixed crash on startup\n• Fixed memory leak",
"inline": false
},
{
"name": "📦 Installation",
"value": "```bash\nnpm install -g @anthropic-ai/claude-code@1.2.3\n```",
"inline": false
},
{
"name": "🔗 Links",
"value": "[NPM Package](https://www.npmjs.com/package/@anthropic-ai/claude-code/v/1.2.3) • [Full Changelog](https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md#123)",
"inline": false
}
],
"footer": {
"text": "Claude Code Changelog Monitor",
"icon_url": "https://avatars.githubusercontent.com/u/100788936?s=200&v=4"
},
"timestamp": "2026-02-28T12:34:56.789Z"
}]
}
````
### Change Categories
* **⚠️ Breaking Changes**: Changes that break backwards compatibility
* **✨ New Features**: New functionality added
* **⚡ Improvements**: Enhancements to existing features
* **🐛 Bug Fixes**: Bug fixes and corrections
Only non-empty categories are included in the embed.
## Database Schema
### claude\_code\_versions
Stores version metadata:
```sql theme={null}
CREATE TABLE claude_code_versions (
id SERIAL PRIMARY KEY,
version VARCHAR(20) NOT NULL UNIQUE,
published_at TIMESTAMP NOT NULL,
changelog_content TEXT,
npm_url TEXT,
github_url TEXT,
discord_notified BOOLEAN DEFAULT false,
discord_notification_sent_at TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW()
);
```
### claude\_code\_changes
Stores individual changes:
```sql theme={null}
CREATE TABLE claude_code_changes (
id SERIAL PRIMARY KEY,
version_id INTEGER REFERENCES claude_code_versions(id),
change_type VARCHAR(50),
description TEXT,
category VARCHAR(100),
created_at TIMESTAMP DEFAULT NOW()
);
```
### discord\_notifications\_log
Logs Discord webhook calls:
```sql theme={null}
CREATE TABLE discord_notifications_log (
id SERIAL PRIMARY KEY,
version_id INTEGER REFERENCES claude_code_versions(id),
webhook_url TEXT,
payload JSONB,
response_status INTEGER,
response_body TEXT,
created_at TIMESTAMP DEFAULT NOW()
);
```
### monitoring\_metadata
Tracks monitoring statistics:
```sql theme={null}
CREATE TABLE monitoring_metadata (
id INTEGER PRIMARY KEY,
last_check_at TIMESTAMP,
last_version_found VARCHAR(20),
check_count INTEGER DEFAULT 0,
error_count INTEGER DEFAULT 0,
last_error TEXT
);
```
## External Dependencies
### NPM Registry API
```bash theme={null}
GET https://registry.npmjs.org/@anthropic-ai/claude-code/latest
```
Returns package metadata including:
* `version` - Latest version number
* `time.modified` - Publication timestamp
### GitHub Changelog
```bash theme={null}
GET https://raw.githubusercontent.com/anthropics/claude-code/main/CHANGELOG.md
```
Markdown changelog with version sections.
### Discord Webhook
```bash theme={null}
POST $DISCORD_WEBHOOK_URL_CHANGELOG
```
Sends formatted embeds to Discord channel.
## Environment Variables
PostgreSQL connection string for Neon database
Format: `postgresql://user:pass@host/db?sslmode=require`
Discord webhook URL for changelog notifications
Fallback: `DISCORD_WEBHOOK_URL`
Environment mode (`development` or `production`)
Controls error detail visibility
## CORS Support
```http theme={null}
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: Content-Type
```
Preflight `OPTIONS` requests return `200 OK`.
## Error Handling
Errors are logged and tracked:
1. **Console logging**: All errors logged with context
2. **Database tracking**: `monitoring_metadata` table updated with error count and message
3. **Graceful degradation**: Metadata update failures don't crash the endpoint
## Example Manual Trigger
```bash theme={null}
# Trigger check
curl -X POST https://www.aitmpl.com/api/claude-code-check
# Response
{
"status": "success",
"version": "1.2.3",
"versionId": 42,
"changes": {
"total": 12,
"byType": {
"features": 5,
"fixes": 4,
"improvements": 3,
"breaking": 0
}
},
"discord": {
"sent": true,
"status": 200
}
}
```
## Monitoring
Check monitoring health:
```sql theme={null}
SELECT
last_check_at,
last_version_found,
check_count,
error_count,
last_error
FROM monitoring_metadata
WHERE id = 1;
```
View recent notifications:
```sql theme={null}
SELECT
v.version,
v.discord_notification_sent_at,
l.response_status
FROM claude_code_versions v
LEFT JOIN discord_notifications_log l ON v.id = l.version_id
ORDER BY v.created_at DESC
LIMIT 10;
```
## Notes
* The endpoint is idempotent: duplicate checks for the same version return `already_processed`
* Changelog content is truncated to 50,000 characters before storage
* GitHub URL uses version without dots (e.g., `#123` for version `1.2.3`)
* Parser uses Claude AI (via `_parser-claude.js`) for intelligent changelog parsing
* All timestamps stored in ISO 8601 format with timezone
* Webhook URL can be overridden with `DISCORD_WEBHOOK_URL_CHANGELOG` environment variable
# Discord Integration
Source: https://davila7-claude-code-templates-86.mintlify.app/api/discord-integration
Discord bot slash commands for component search and installation
## Endpoint
**POST** `/api/discord/interactions`
Handles Discord application command interactions. This endpoint processes slash commands from the Claude Code Templates Discord bot.
## Authentication
Requests are authenticated using Ed25519 signature verification:
Ed25519 signature of the request
Unix timestamp of the request
The endpoint uses the `discord-interactions` library to verify signatures against `DISCORD_PUBLIC_KEY`.
### Invalid Signature
```json theme={null}
{
"error": "Invalid request signature"
}
```
Returns `401 Unauthorized`.
## Available Commands
### /search
Search for components by name or category.
Search query (matches component name or category)
Filter by component type:
* `skills`
* `agents`
* `commands`
* `mcps`
* `settings`
* `hooks`
* `templates`
* `plugins`
#### Response
Returns Discord embed with search results (up to 10 matches):
```json theme={null}
{
"type": 4,
"data": {
"embeds": [{
"title": "🔍 Search Results for \"react\"",
"description": "Found 3 result(s)",
"color": 56831,
"fields": [
{
"name": "1. 🤖 react-expert",
"value": "**Type:** agents | **Downloads:** 142\n[View on aitmpl.com](https://www.aitmpl.com/component/agent/development-team/react-expert)",
"inline": false
}
],
"timestamp": "2026-02-28T12:34:56.789Z"
}]
}
}
```
Results are ranked by relevance:
* Exact match: score 100
* Starts with query: score 50
* Contains query: score 20
### /info
Get detailed information about a specific component.
Component name
Component type (if omitted, searches all types)
#### Response
Returns Discord embed with component details:
```json theme={null}
{
"type": 4,
"data": {
"embeds": [{
"title": "🤖 frontend-developer",
"url": "https://www.aitmpl.com/component/agent/development-team/frontend-developer",
"description": "Expert frontend developer specializing in React, Vue, and modern web technologies",
"color": 16737131,
"fields": [
{
"name": "Type",
"value": "`agents`",
"inline": true
},
{
"name": "Category",
"value": "development-team",
"inline": true
},
{
"name": "Downloads",
"value": "142",
"inline": true
},
{
"name": "Component Page",
"value": "[View on aitmpl.com](https://www.aitmpl.com/component/agent/development-team/frontend-developer)",
"inline": false
}
],
"timestamp": "2026-02-28T12:34:56.789Z"
}]
}
}
```
#### Component Not Found
```json theme={null}
{
"type": 4,
"data": {
"content": "Component \"invalid-name\" not found. Use `/search` to find components.",
"flags": 64
}
}
```
The `flags: 64` makes the message ephemeral (only visible to the user).
### /install
Get installation command for a component.
Component name
Component type (if omitted, searches all types)
#### Response
Returns Discord embed with installation instructions:
````json theme={null}
{
"type": 4,
"data": {
"embeds": [{
"title": "🤖 Install frontend-developer",
"description": "Copy and paste this command in your terminal:",
"color": 56831,
"url": "https://www.aitmpl.com/component/agent/development-team/frontend-developer",
"fields": [
{
"name": "Installation Command",
"value": "```bash\nnpx claude-code-templates@latest --agent frontend-developer\n```",
"inline": false
},
{
"name": "Component Page",
"value": "[View on aitmpl.com](https://www.aitmpl.com/component/agent/development-team/frontend-developer)",
"inline": false
}
],
"timestamp": "2026-02-28T12:34:56.789Z"
}]
}
}
````
Note: Templates use `--template` flag instead of `--templates`.
### /popular
Show the most downloaded component of a specific type.
Component type to filter by
#### Response
Returns the component with the highest download count:
```json theme={null}
{
"type": 4,
"data": {
"embeds": [{
"title": "🤖 fullstack-developer",
"url": "https://www.aitmpl.com/component/agent/development-team/fullstack-developer",
"description": "Complete fullstack development specialist",
"color": 16737131,
"fields": [
{
"name": "Type",
"value": "`agents`",
"inline": true
},
{
"name": "Category",
"value": "development-team",
"inline": true
},
{
"name": "Downloads",
"value": "856",
"inline": true
}
],
"timestamp": "2026-02-28T12:34:56.789Z"
}]
}
}
```
### /random
Show a random component of a specific type.
Component type to filter by
#### Response
Returns a randomly selected component (same format as `/popular`).
## Component Cache
The endpoint caches component data from `https://aitmpl.com/components.json`:
* **Cache duration**: 5 minutes
* **Cache key**: `cachedComponents` (in-memory)
* **Refresh**: Automatic on cache expiration
* **Timeout**: 10 seconds for HTTP request
## Component Types & Icons
Each component type has an associated icon and color:
| Type | Icon | Color (Hex) |
| --------- | ---- | ----------- |
| skills | 🎨 | #9B59B6 |
| agents | 🤖 | #FF6B6B |
| commands | ⚡ | #4ECDC4 |
| mcps | 🔌 | #95E1D3 |
| settings | ⚙️ | #F9CA24 |
| hooks | 🪝 | #6C5CE7 |
| templates | 📋 | #A8E6CF |
| plugins | 🧩 | #FFD93D |
## Error Handling
### 405 Method Not Allowed
```json theme={null}
{
"error": "Method not allowed"
}
```
### 500 Server Configuration Error
```json theme={null}
{
"error": "Server configuration error"
}
```
Returned when `DISCORD_PUBLIC_KEY` is not configured.
### Generic Command Error
If a command fails (e.g., network error fetching components):
```json theme={null}
{
"type": 4,
"data": {
"content": "❌ An error occurred",
"flags": 64
}
}
```
The error is logged to console but shown generically to the user.
## Interaction Types
The endpoint handles two Discord interaction types:
### PING (type: 1)
Discord verification ping. Returns:
```json theme={null}
{
"type": 1
}
```
### APPLICATION\_COMMAND (type: 2)
Slash command execution. See command responses above.
## Example Request
Example curl request (signature headers must be valid):
```bash theme={null}
curl -X POST https://www.aitmpl.com/api/discord/interactions \
-H "Content-Type: application/json" \
-H "x-signature-ed25519: abc123..." \
-H "x-signature-timestamp: 1709123456" \
-d '{
"type": 2,
"data": {
"name": "search",
"options": [
{"name": "query", "value": "react"},
{"name": "type", "value": "agents"}
]
}
}'
```
## Notes
* All embed timestamps use ISO 8601 format
* Component URLs follow pattern: `/component/{singular_type}/{category}/{name}`
* Type names are pluralized in the code but singularized in URLs
* Ephemeral messages (flags: 64) are only visible to the command user
* The endpoint returns Discord interaction responses, not standard REST responses
# API Overview
Source: https://davila7-claude-code-templates-86.mintlify.app/api/overview
Claude Code Templates API endpoints for download tracking, Discord integration, and version monitoring
## Base URL
All API endpoints are hosted on Vercel:
```
https://www.aitmpl.com/api
```
## Available Endpoints
### Download Tracking
**POST** `/api/track-download-supabase`
Tracks component downloads for analytics. Used automatically by the CLI on every component installation.
[View documentation →](/api/track-download)
### Discord Integration
**POST** `/api/discord/interactions`
Handles Discord bot slash commands for searching and installing components.
[View documentation →](/api/discord-integration)
### Claude Code Monitoring
**POST/GET** `/api/claude-code-check`
Monitors Claude Code releases and sends Discord notifications. Runs automatically via Vercel Cron every 30 minutes.
[View documentation →](/api/claude-code-check)
## Authentication
Most endpoints do not require authentication. The Discord interactions endpoint validates requests using Ed25519 signature verification.
## CORS
All endpoints support Cross-Origin Resource Sharing (CORS) with the following headers:
```http theme={null}
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: Content-Type, User-Agent
```
## Rate Limiting
There are no explicit rate limits, but endpoints are subject to Vercel's serverless function limits:
* **Execution time**: 10 seconds (Hobby), 60 seconds (Pro)
* **Memory**: 1024 MB
* **Payload size**: 4.5 MB
## Error Responses
All endpoints return consistent error responses:
Error type or message
Human-readable error description
Additional error details (development mode only)
### Example Error Response
```json theme={null}
{
"error": "Internal server error",
"message": "Failed to track download",
"details": "Database connection failed"
}
```
## Environment
The API runs on Vercel Serverless Functions with the following infrastructure:
* **Database (Download Tracking)**: Supabase
* **Database (Claude Code Monitoring)**: Neon PostgreSQL
* **Runtime**: Node.js
* **Region**: Auto-selected by Vercel Edge Network
## Status & Monitoring
Monitor API health:
```bash theme={null}
# View production logs
vercel logs aitmpl.com --follow
# Check deployment status
vercel ls
```
## Support
For API issues or questions:
* GitHub Issues: [github.com/anomalyco/opencode](https://github.com/anomalyco/opencode)
* Documentation: [aitmpl.com](https://aitmpl.com)
# Track Download
Source: https://davila7-claude-code-templates-86.mintlify.app/api/track-download
Endpoint for tracking component downloads and analytics
## Endpoint
**POST** `/api/track-download-supabase`
Tracks component downloads for analytics. This endpoint is called automatically by the CLI whenever a user installs a component.
## Request
### Headers
Must be `application/json`
Client user agent string (automatically captured)
### Body Parameters
Component type. Must be one of:
* `agent`
* `command`
* `setting`
* `hook`
* `mcp`
* `skill`
* `template`
Component name. Maximum 255 characters.
Component path in the repository
Component category (e.g., "development-team", "automation")
Version of the CLI tool used for installation
### Example Request
```bash theme={null}
curl -X POST https://www.aitmpl.com/api/track-download-supabase \
-H "Content-Type: application/json" \
-H "User-Agent: claude-code-templates/1.0.0" \
-d '{
"type": "agent",
"name": "frontend-developer",
"path": "cli-tool/components/agents/development-team/frontend-developer.md",
"category": "development-team",
"cliVersion": "1.0.0"
}'
```
## Response
### Success Response (200 OK)
Always `true` on success
Confirmation message
Download information
Component type
Component name
ISO 8601 timestamp of the download
#### Example Success Response
```json theme={null}
{
"success": true,
"message": "Download tracked successfully",
"data": {
"type": "agent",
"name": "frontend-developer",
"timestamp": "2026-02-28T12:34:56.789Z"
}
}
```
### Error Responses
#### 400 Bad Request - Invalid Component Type
```json theme={null}
{
"error": "Invalid component type"
}
```
#### 400 Bad Request - Missing Required Fields
```json theme={null}
{
"error": "Component type and name are required"
}
```
#### 400 Bad Request - Name Too Long
```json theme={null}
{
"error": "Component name too long"
}
```
#### 405 Method Not Allowed
```json theme={null}
{
"error": "Method not allowed",
"allowed": ["POST"]
}
```
#### 500 Internal Server Error
```json theme={null}
{
"error": "Internal server error",
"message": "Failed to track download",
"details": "Database insert failed: connection timeout"
}
```
Note: The `details` field is only included in development mode.
## Data Storage
Download events are stored in two Supabase tables:
### component\_downloads
Stores individual download records with:
* Component metadata (type, name, path, category)
* User information (IP address, country, user agent)
* CLI version
* Timestamp
### download\_stats
Aggregated statistics using upsert:
* Total downloads per component
* Last download timestamp
* Automatically updated via `onConflict` on `(component_type, component_name)`
## Metadata Captured
The endpoint automatically captures:
Extracted from headers in order:
1. `x-forwarded-for` (first IP)
2. `x-real-ip`
3. Connection remote address
4. Fallback: `127.0.0.1`
Extracted from Vercel geo header `x-vercel-ip-country`
From `user-agent` request header
## Rate Limiting
No explicit rate limits are enforced, but requests are subject to:
* Vercel serverless function execution limits (10s timeout)
* Supabase connection pool limits
## CORS Support
The endpoint supports CORS with:
```http theme={null}
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, User-Agent
```
Preflight `OPTIONS` requests return `200 OK`.
## Notes
* The endpoint never fails the user's installation if tracking fails
* Stats update errors are logged but don't return 500 responses
* All timestamps are stored in ISO 8601 format
* The endpoint is idempotent (duplicate downloads are recorded separately)
# Database Components
Source: https://davila7-claude-code-templates-86.mintlify.app/categories/database
Database specialists, MCPs, and tools for PostgreSQL, MySQL, Neon, Supabase, and more
# Database Components
The Database category includes specialized agents, MCPs, and commands for database architecture, optimization, migrations, and platform-specific integrations.
Explore all database components at **aitmpl.com**
## Quick Install
```bash theme={null}
# Install database essentials
npx claude-code-templates@latest \
--agent database-architect \
--agent postgres-pro \
--mcp neon \
--mcp supabase
# Or install the database template
npx claude-code-templates@latest --template database-project
```
## Database Agents
Expert in database schema design, normalization, and architecture
**Expertise:**
* Schema design and normalization
* Data modeling (ER diagrams)
* Index strategy
* Partitioning and sharding
* Replication architecture
* Backup and recovery planning
**Technologies:**
* PostgreSQL, MySQL, MongoDB
* Redis, Cassandra, DynamoDB
* Database design patterns
* Capacity planning
```bash theme={null}
npx claude-code-templates@latest --agent database-architect
```
**Example Usage:**
```
@database-architect Design a multi-tenant database schema for a SaaS
application with 10k tenants. Include user management, subscriptions,
and usage tracking.
```
Database administration, maintenance, and operations
**Expertise:**
* Database configuration
* Performance tuning
* Backup and recovery
* User and permission management
* Monitoring and alerting
* Disaster recovery
```bash theme={null}
npx claude-code-templates@latest --agent database-administrator
```
Query optimization, indexing, and performance tuning
**Expertise:**
* Query performance analysis
* Index optimization
* Query plan analysis (EXPLAIN)
* Connection pooling
* Caching strategies
* Slow query detection
**Techniques:**
* Index selection and design
* Query rewriting
* Materialized views
* Partitioning strategies
* Denormalization when needed
```bash theme={null}
npx claude-code-templates@latest --agent database-optimizer
```
**Example Usage:**
```
@database-optimizer Analyze and optimize this slow query.
It's taking 5 seconds to fetch user orders with related products.
SELECT * FROM orders o
JOIN order_items oi ON o.id = oi.order_id
JOIN products p ON oi.product_id = p.id
WHERE o.user_id = 123
```
Systematic database performance optimization
```bash theme={null}
npx claude-code-templates@latest --agent database-optimization
```
## PostgreSQL Specialists
PostgreSQL expert for advanced features and optimization
**Expertise:**
* Advanced SQL features (CTEs, window functions, LATERAL joins)
* PostgreSQL-specific features (JSONB, full-text search, arrays)
* Extensions (PostGIS, pg\_stat\_statements, pg\_cron)
* Replication (streaming, logical)
* Connection pooling (PgBouncer)
* Performance tuning
**Use cases:**
* Complex query optimization
* Full-text search implementation
* Geospatial queries with PostGIS
* JSON/JSONB data handling
* Advanced indexing (GiST, GIN, BRIN)
```bash theme={null}
npx claude-code-templates@latest --agent postgres-pro
```
NoSQL databases (MongoDB, Cassandra, Redis)
```bash theme={null}
npx claude-code-templates@latest --agent nosql-specialist
```
## Platform-Specific Agents
### Neon Database Specialists
Neon serverless Postgres specialist
**Expertise:**
* Neon branching workflows
* Autoscaling configuration
* Branch-based development
* Instant provisioning
* Connection pooling
* Cost optimization
```bash theme={null}
npx claude-code-templates@latest --agent neon-expert
```
**Example Usage:**
```
@neon-expert Set up a branching workflow where each PR gets
its own database branch for testing.
```
Neon-specific architecture and design
```bash theme={null}
npx claude-code-templates@latest --agent neon-database-architect
```
Neon authentication and security
```bash theme={null}
npx claude-code-templates@latest --agent neon-auth-specialist
```
### Supabase Database Specialists
Supabase schema design and RLS policies
**Expertise:**
* PostgreSQL schema design for Supabase
* Row Level Security (RLS) policies
* Supabase Auth integration
* Realtime subscriptions
* Storage bucket configuration
```bash theme={null}
npx claude-code-templates@latest --agent supabase-schema-architect
```
## Database MCPs
Direct integration with Neon database platform
**Capabilities:**
* Query databases directly from Claude
* Create and manage database branches
* Access Neon Management API
* Monitor database metrics
* Manage connection strings
```bash theme={null}
npx claude-code-templates@latest --mcp neon
```
**Setup:**
```bash theme={null}
# Add Neon API key to .env
echo "NEON_API_KEY=your_api_key" >> .env
```
**Example Usage:**
```
# In Claude Code chat:
Query my Neon database for all users created in the last 7 days
Create a new database branch called "feature-auth" from main
Show me the current database metrics and connection count
```
Direct integration with Supabase platform
**Capabilities:**
* Query database
* Manage authentication
* Storage operations
* Realtime subscriptions
* Edge functions
```bash theme={null}
npx claude-code-templates@latest --mcp supabase
```
**Setup:**
```bash theme={null}
# Add Supabase credentials to .env
echo "SUPABASE_URL=https://xxx.supabase.co" >> .env
echo "SUPABASE_KEY=your_service_key" >> .env
```
Direct PostgreSQL database connection
```bash theme={null}
npx claude-code-templates@latest --mcp postgresql-integration
```
Direct MySQL database connection
```bash theme={null}
npx claude-code-templates@latest --mcp mysql-integration
```
## Database Commands
### Supabase Management Commands
Create and manage Supabase migrations
```bash theme={null}
npx claude-code-templates@latest --command supabase-migration-assistant
```
Sync local schema with Supabase
```bash theme={null}
npx claude-code-templates@latest --command supabase-schema-sync
```
Optimize Supabase database performance
```bash theme={null}
npx claude-code-templates@latest --command supabase-performance-optimizer
```
Audit Supabase security and RLS policies
```bash theme={null}
npx claude-code-templates@latest --command supabase-security-audit
```
Explore and analyze Supabase data
```bash theme={null}
npx claude-code-templates@latest --command supabase-data-explorer
```
Manage Supabase backups
```bash theme={null}
npx claude-code-templates@latest --command supabase-backup-manager
```
Monitor Supabase realtime connections
```bash theme={null}
npx claude-code-templates@latest --command supabase-realtime-monitor
```
Generate TypeScript types from Supabase schema
```bash theme={null}
npx claude-code-templates@latest --command supabase-type-generator
```
### Snowflake Commands
Create semantic views in Snowflake
```bash theme={null}
npx claude-code-templates@latest --command snowflake-semanticview
```
## Database Workflows
### Schema Design Workflow
```bash theme={null}
# 1. Design schema
@database-architect Design a schema for a social media platform
with users, posts, comments, and likes. Include proper indexing.
# 2. Implement in database
@postgres-pro Implement the schema with appropriate indexes,
constraints, and triggers.
# 3. Optimize
@database-optimizer Review the schema and suggest optimizations
for queries that fetch a user's feed.
```
### Migration Workflow
```bash theme={null}
# Install Supabase tools
npx claude-code-templates@latest \
--agent supabase-schema-architect \
--command supabase-migration-assistant
# Create migration
/supabase-migration-assistant create add_user_profiles
# Apply migration
/supabase-migration-assistant apply
# Verify
/supabase-schema-sync verify
```
### Performance Optimization Workflow
```bash theme={null}
# Identify slow queries
@database-optimizer Analyze slow queries in the application
# Create indexes
@postgres-pro Add appropriate indexes for the identified queries
# Test performance
@database-optimizer Measure query performance improvements
# Monitor
/supabase-performance-optimizer monitor
```
## Best Practices
### 1. Schema Design
```bash theme={null}
@database-architect Design schema with:
- Proper normalization (3NF for transactional data)
- Strategic denormalization for performance
- Appropriate data types
- Constraints for data integrity
- Indexes for common queries
```
### 2. Query Optimization
```bash theme={null}
@database-optimizer Review queries for:
- Index usage (check EXPLAIN plans)
- N+1 query problems
- Unnecessary joins
- Large result sets
- Missing WHERE clauses
```
### 3. Security
```bash theme={null}
# Use RLS with Supabase
@supabase-schema-architect Implement Row Level Security policies
for multi-tenant isolation
# Audit security
/supabase-security-audit
```
### 4. Monitoring
```bash theme={null}
# Monitor performance
/supabase-performance-optimizer monitor
# Monitor realtime
/supabase-realtime-monitor
# Regular backups
/supabase-backup-manager schedule
```
## Real-World Examples
### Example 1: E-commerce Database
```bash theme={null}
# Install tools
npx claude-code-templates@latest \
--agent database-architect \
--agent postgres-pro \
--mcp neon
# Design schema
@database-architect Design an e-commerce database with:
- Products with variants and inventory
- Shopping carts and orders
- Payment transactions
- Customer reviews
- Order fulfillment tracking
# Implement
@postgres-pro Implement the schema with:
- JSONB for product attributes
- Partial indexes for active products
- Triggers for inventory updates
- Full-text search for products
```
### Example 2: Multi-Tenant SaaS
```bash theme={null}
# Install Supabase tools
npx claude-code-templates@latest \
--agent supabase-schema-architect \
--command supabase-security-audit
# Design tenant isolation
@supabase-schema-architect Design multi-tenant schema with:
- Tenant-scoped data access
- RLS policies for isolation
- Shared and tenant-specific tables
# Audit security
/supabase-security-audit
```
### Example 3: Analytics Database
```bash theme={null}
# Install specialists
npx claude-code-templates@latest \
--agent database-architect \
--agent database-optimizer
# Design analytics schema
@database-architect Design a time-series analytics schema
with partitioning by date and appropriate aggregation tables.
# Optimize queries
@database-optimizer Optimize queries for dashboard that shows:
- Daily active users (last 30 days)
- Top 10 features by usage
- User cohort retention
```
## Database Template
```bash theme={null}
npx claude-code-templates@latest --template database-project
```
**Includes:**
* Database architect agent
* Database optimizer agent
* Postgres pro agent
* Neon MCP
* Supabase MCP
* Migration commands
* Performance monitoring
## Next Steps
* [Browse all database components](https://aitmpl.com/?category=database)
* [View development team](/categories/development-team)
* [Explore DevOps components](/categories/devops-infrastructure)
* [Check out security components](/categories/security)
# Development Team Components
Source: https://davila7-claude-code-templates-86.mintlify.app/categories/development-team
Complete development team agents covering frontend, backend, mobile, DevOps, testing, and architecture
# Development Team Components
The Development Team category includes AI specialists that replicate a complete software development team. These agents handle everything from frontend design to backend APIs, database architecture, testing, and deployment.
Explore all development team components at **aitmpl.com**
## Quick Install
```bash theme={null}
# Install the full development team
npx claude-code-templates@latest \
--agent backend-developer \
--agent frontend-developer \
--agent devops-engineer \
--agent test-generator
# Or install individually
npx claude-code-templates@latest --agent backend-developer
```
## Core Development Agents
Senior backend developer specializing in APIs, microservices, and scalable systems
**Expertise:**
* RESTful API design
* Microservices architecture
* Database integration
* Authentication & authorization
* Performance optimization
* Production deployment
**Tech Stack:**
* Node.js 18+, Python 3.11+, Go 1.21+
* PostgreSQL, Redis, MongoDB
* Docker, Kubernetes
* OAuth2, JWT
```bash theme={null}
npx claude-code-templates@latest --agent backend-developer
```
**Example Usage:**
```
@backend-developer Create a user service API with JWT auth,
PostgreSQL persistence, and Redis caching. Target 100ms p95 latency.
```
Expert in React, Vue, Angular, and modern frontend frameworks
**Expertise:**
* Component architecture
* State management (Redux, Zustand, Pinia)
* Responsive design
* Performance optimization
* Accessibility (WCAG)
* Testing (Jest, Vitest, Testing Library)
**Tech Stack:**
* React 18+, Vue 3, Angular 17+
* TypeScript, Tailwind CSS
* Vite, Webpack, Next.js
* PWA, Web Workers
```bash theme={null}
npx claude-code-templates@latest --agent frontend-developer
```
**Example Usage:**
```
@frontend-developer Build a dashboard with charts, real-time updates,
and dark mode using React and Tailwind CSS.
```
End-to-end application development with frontend and backend expertise
**Expertise:**
* Full application architecture
* Frontend + Backend integration
* Database design
* API development
* Deployment automation
* Performance tuning
**Tech Stack:**
* React, Next.js, Vue, Nuxt
* Node.js, Express, Fastify
* PostgreSQL, MongoDB
* Vercel, Railway, Fly.io
```bash theme={null}
npx claude-code-templates@latest --agent fullstack-developer
```
Infrastructure, CI/CD, containerization, and deployment automation
**Expertise:**
* Infrastructure as Code (Terraform, Bicep)
* Container orchestration (Docker, K8s)
* CI/CD pipelines (GitHub Actions, GitLab CI)
* Cloud platforms (AWS, Azure, GCP)
* Monitoring & logging
* Security hardening
**Tech Stack:**
* Kubernetes, Docker, Helm
* Terraform, Pulumi
* Prometheus, Grafana
* GitHub Actions, ArgoCD
```bash theme={null}
npx claude-code-templates@latest --agent devops-engineer
```
**Example Usage:**
```
@devops-engineer Set up a Kubernetes cluster with auto-scaling,
monitoring, and CI/CD pipeline for our microservices.
```
## Specialized Development Agents
### Mobile Development
iOS, Android, React Native, and Flutter development
```bash theme={null}
npx claude-code-templates@latest --agent mobile-developer
```
Native iOS development with Swift and SwiftUI
```bash theme={null}
npx claude-code-templates@latest --agent ios-developer
```
Cross-platform Flutter applications
```bash theme={null}
npx claude-code-templates@latest --agent flutter-ui-developer
```
### Architecture & Design
System architecture and design patterns
```bash theme={null}
npx claude-code-templates@latest --agent code-architect
```
Backend system architecture and scalability
```bash theme={null}
npx claude-code-templates@latest --agent backend-architect
```
User interface and experience design
```bash theme={null}
npx claude-code-templates@latest --agent ui-ux-designer
```
Visual design and component libraries
```bash theme={null}
npx claude-code-templates@latest --agent ui-designer
```
Command-line interface design
```bash theme={null}
npx claude-code-templates@latest --agent cli-ui-designer
```
### Testing & Quality Assurance
Automated test generation with comprehensive coverage
**Capabilities:**
* Unit test generation
* Integration test setup
* E2E test scenarios
* Test data factories
* Mocking strategies
* Coverage analysis
```bash theme={null}
npx claude-code-templates@latest --agent test-generator
```
**Example Usage:**
```
@test-generator Generate comprehensive tests for the user service
with 80%+ coverage, including edge cases and error scenarios.
```
Test execution and automation
```bash theme={null}
npx claude-code-templates@latest --agent test-runner
```
### Desktop Development
Cross-platform desktop applications with Electron
```bash theme={null}
npx claude-code-templates@latest --agent electron-pro
```
### Code Exploration
Codebase analysis and documentation
```bash theme={null}
npx claude-code-templates@latest --agent code-explorer
```
## Team Workflows
### Full Development Cycle
```bash theme={null}
# 1. Architecture phase
@code-architect Design a microservices architecture for an e-commerce platform
# 2. Backend implementation
@backend-developer Implement the product catalog service with PostgreSQL
# 3. Frontend development
@frontend-developer Build the product listing and detail pages
# 4. Testing
@test-generator Generate comprehensive tests for the product service
# 5. Deployment
@devops-engineer Set up CI/CD pipeline and Kubernetes deployment
```
### API Development Team
```bash theme={null}
# Backend API
npx claude-code-templates@latest --agent backend-developer
# Database design
npx claude-code-templates@latest --agent database-architect
# API documentation
npx claude-code-templates@latest --command generate-docs
# Testing
npx claude-code-templates@latest --agent test-generator
```
### Mobile App Team
```bash theme={null}
# Cross-platform mobile
npx claude-code-templates@latest --agent mobile-developer
# Backend API
npx claude-code-templates@latest --agent backend-developer
# UI/UX design
npx claude-code-templates@latest --agent ui-ux-designer
```
## Best Practices
### Agent Coordination
1. **Start with Architecture**: Use `@code-architect` to plan system design
2. **Backend First**: Implement APIs before frontend
3. **Test as You Go**: Use `@test-generator` alongside development
4. **Deploy Early**: Set up CI/CD with `@devops-engineer` from the start
### Communication Between Agents
Agents can work together:
```bash theme={null}
# Backend developer creates API
@backend-developer Create user authentication API
# Frontend developer integrates
@frontend-developer Integrate the authentication API with login form
# Test generator verifies
@test-generator Generate E2E tests for the authentication flow
```
### Specialization vs. Generalization
* **Specialized agents** (backend-developer, frontend-developer) for focused tasks
* **Generalized agents** (fullstack-developer) for small projects or rapid prototyping
## Real-World Examples
### Example 1: SaaS Application
```bash theme={null}
# Install team
npx claude-code-templates@latest \
--agent fullstack-developer \
--agent database-architect \
--agent devops-engineer
# Build features
@fullstack-developer Create subscription management with Stripe
@database-architect Design multi-tenant database schema
@devops-engineer Deploy to Kubernetes with auto-scaling
```
### Example 2: Mobile App
```bash theme={null}
# Install team
npx claude-code-templates@latest \
--agent mobile-developer \
--agent backend-developer \
--agent ui-ux-designer
# Build app
@ui-ux-designer Design the onboarding flow
@backend-developer Create the GraphQL API
@mobile-developer Build the React Native app
```
### Example 3: Enterprise Web App
```bash theme={null}
# Install team
npx claude-code-templates@latest \
--agent backend-architect \
--agent frontend-developer \
--agent devops-engineer \
--agent test-generator
# Build application
@backend-architect Design microservices architecture
@backend-developer Implement order processing service
@frontend-developer Build admin dashboard
@test-generator Create comprehensive test suite
@devops-engineer Set up production infrastructure
```
## Team Templates
Use pre-configured team setups:
```bash theme={null}
# Fullstack web team
npx claude-code-templates@latest --template fullstack-web
# Mobile development team
npx claude-code-templates@latest --template mobile-development
# Microservices team
npx claude-code-templates@latest --template microservices
```
## Next Steps
* [Browse all development team agents](https://aitmpl.com/?category=development-team)
* [View database components](/categories/database)
* [Explore DevOps components](/categories/devops-infrastructure)
* [Check out testing components](/categories/testing)
* [See all templates](/components/templates)
# DevOps & Infrastructure Components
Source: https://davila7-claude-code-templates-86.mintlify.app/categories/devops-infrastructure
Cloud platforms, Kubernetes, Terraform, CI/CD, and infrastructure automation specialists
# DevOps & Infrastructure Components
The DevOps & Infrastructure category includes specialists for cloud platforms, container orchestration, infrastructure as code, CI/CD pipelines, and site reliability engineering.
Explore all DevOps and infrastructure components at **aitmpl.com**
## Quick Install
```bash theme={null}
# Install DevOps essentials
npx claude-code-templates@latest \
--agent devops-engineer \
--agent cloud-architect \
--agent kubernetes-specialist \
--agent terraform-engineer
# Or install the DevOps template
npx claude-code-templates@latest --template devops-pipeline
```
## Core DevOps Agents
Complete DevOps specialist for infrastructure and deployment
**Expertise:**
* CI/CD pipeline design and implementation
* Container orchestration (Docker, Kubernetes)
* Infrastructure as Code (Terraform, Pulumi)
* Cloud platforms (AWS, Azure, GCP)
* Monitoring and observability
* Incident response
**Technologies:**
* Docker, Kubernetes, Helm
* GitHub Actions, GitLab CI, Jenkins
* Terraform, Ansible, Pulumi
* Prometheus, Grafana, DataDog
* AWS/Azure/GCP CLIs and SDKs
```bash theme={null}
npx claude-code-templates@latest --agent devops-engineer
```
**Example Usage:**
```
@devops-engineer Set up a production-ready Kubernetes cluster
with auto-scaling, monitoring, and CI/CD pipeline for our
microservices application.
```
Multi-cloud architecture and infrastructure design
**Expertise:**
* Cloud architecture patterns
* Multi-cloud and hybrid cloud
* Cost optimization
* Security and compliance
* High availability design
* Disaster recovery
**Platforms:**
* AWS (EC2, S3, RDS, Lambda, ECS, EKS)
* Azure (VMs, Blob Storage, SQL, Functions, AKS)
* GCP (Compute Engine, Cloud Storage, Cloud Run, GKE)
```bash theme={null}
npx claude-code-templates@latest --agent cloud-architect
```
Platform engineering and developer experience
**Expertise:**
* Internal developer platforms
* Developer tooling
* Self-service infrastructure
* Platform observability
* Golden paths
```bash theme={null}
npx claude-code-templates@latest --agent platform-engineer
```
Site Reliability Engineering for production systems
**Expertise:**
* Service Level Objectives (SLOs)
* Incident response and postmortems
* Reliability engineering
* Capacity planning
* Automation and toil reduction
* Production debugging
```bash theme={null}
npx claude-code-templates@latest --agent sre-engineer
```
## Container Orchestration
Kubernetes deployment, scaling, and operations
**Expertise:**
* Kubernetes architecture
* Deployments, StatefulSets, DaemonSets
* Services, Ingress, NetworkPolicies
* ConfigMaps and Secrets management
* Helm charts and Kustomize
* Service mesh (Istio, Linkerd)
* Autoscaling (HPA, VPA, Cluster Autoscaler)
* Monitoring and logging
**Use cases:**
* Microservices deployment
* Stateful application management
* Multi-tenant clusters
* Blue-green and canary deployments
```bash theme={null}
npx claude-code-templates@latest --agent kubernetes-specialist
```
**Example Usage:**
```
@kubernetes-specialist Deploy our microservices to Kubernetes
with:
- Horizontal Pod Autoscaling based on CPU and custom metrics
- Ingress with TLS termination
- Network policies for pod-to-pod communication
- Prometheus monitoring
```
Microservices architecture and design patterns
```bash theme={null}
npx claude-code-templates@latest --agent microservices-architect
```
## Infrastructure as Code
### Terraform Specialists
Infrastructure as Code with Terraform
**Expertise:**
* Terraform configuration
* Module development
* State management
* Multi-environment setups
* Provider configuration
* Best practices
```bash theme={null}
npx claude-code-templates@latest --agent terraform-engineer
```
Advanced Terraform patterns and optimization
```bash theme={null}
npx claude-code-templates@latest --agent terraform-specialist
```
Terragrunt for DRY Terraform configurations
```bash theme={null}
npx claude-code-templates@latest --agent terragrunt-expert
```
Review Terraform code for best practices
```bash theme={null}
npx claude-code-templates@latest --agent terraform-iac-reviewer
```
### Azure Infrastructure Specialists
Azure cloud architecture and best practices
**Expertise:**
* Azure architecture patterns
* Landing zones
* Security and compliance
* Cost optimization
* Migration strategies
```bash theme={null}
npx claude-code-templates@latest --agent azure-principal-architect
```
Azure infrastructure deployment and management
```bash theme={null}
npx claude-code-templates@latest --agent azure-infra-engineer
```
Azure SaaS application architecture
```bash theme={null}
npx claude-code-templates@latest --agent azure-saas-architect
```
Export existing Azure infrastructure to IaC
```bash theme={null}
npx claude-code-templates@latest --agent azure-iac-exporter
```
Generate Azure IaC from requirements
```bash theme={null}
npx claude-code-templates@latest --agent azure-iac-generator
```
Plan Azure infrastructure with Terraform
```bash theme={null}
npx claude-code-templates@latest --agent terraform-azure-planning
```
Implement Azure infrastructure with Terraform
```bash theme={null}
npx claude-code-templates@latest --agent terraform-azure-implement
```
Plan Azure infrastructure with Bicep
```bash theme={null}
npx claude-code-templates@latest --agent bicep-plan
```
Implement Azure infrastructure with Bicep
```bash theme={null}
npx claude-code-templates@latest --agent bicep-implement
```
## Deployment & CI/CD
Deployment automation and release management
**Expertise:**
* Deployment strategies (blue-green, canary, rolling)
* Release automation
* Rollback procedures
* Feature flags
* Progressive delivery
```bash theme={null}
npx claude-code-templates@latest --agent deployment-engineer
```
Vercel platform deployment and optimization
```bash theme={null}
npx claude-code-templates@latest --agent vercel-deployment-specialist
```
## Monitoring & Operations
Observability, monitoring, and alerting
**Expertise:**
* Metrics collection (Prometheus, DataDog, CloudWatch)
* Logging (ELK, Loki, CloudWatch Logs)
* Distributed tracing (Jaeger, Zipkin, Tempo)
* Dashboards and visualization
* Alerting and on-call
* SLO/SLI definition
```bash theme={null}
npx claude-code-templates@latest --agent monitoring-specialist
```
Incident response and troubleshooting
```bash theme={null}
npx claude-code-templates@latest --agent incident-responder
```
DevOps-focused incident management
```bash theme={null}
npx claude-code-templates@latest --agent devops-incident-responder
```
Production troubleshooting and debugging
```bash theme={null}
npx claude-code-templates@latest --agent devops-troubleshooter
```
## Security Engineering
Infrastructure security and compliance
**Expertise:**
* Security architecture
* Compliance (SOC2, HIPAA, GDPR)
* Vulnerability management
* Security automation
* Penetration testing
* Zero trust architecture
```bash theme={null}
npx claude-code-templates@latest --agent security-engineer
```
Network architecture and security
```bash theme={null}
npx claude-code-templates@latest --agent network-engineer
```
## Specialized Infrastructure Agents
Azure Logic Apps integration and automation
```bash theme={null}
npx claude-code-templates@latest --agent azure-logic-apps-expert
```
Azure Verified Modules with Bicep
```bash theme={null}
npx claude-code-templates@latest --agent azure-verified-modules-bicep
```
Azure Verified Modules with Terraform
```bash theme={null}
npx claude-code-templates@latest --agent azure-verified-modules-terraform
```
Microsoft 365 administration
```bash theme={null}
npx claude-code-templates@latest --agent m365-admin
```
Azure Data Explorer (Kusto) queries
```bash theme={null}
npx claude-code-templates@latest --agent kusto-assistant
```
Windows server infrastructure
```bash theme={null}
npx claude-code-templates@latest --agent windows-infra-admin
```
Migrate from ARM templates to Bicep or Terraform
```bash theme={null}
npx claude-code-templates@latest --agent arm-migration
```
Apify web scraping and automation
```bash theme={null}
npx claude-code-templates@latest --agent apify-integration-expert
```
Neo4j graph database Docker setup
```bash theme={null}
npx claude-code-templates@latest --agent neo4j-docker-client-generator
```
## DevOps Workflows
### Complete CI/CD Pipeline
```bash theme={null}
# 1. Infrastructure setup
@terraform-engineer Create Terraform configuration for:
- Kubernetes cluster (EKS/AKS/GKE)
- Container registry
- Monitoring stack
- Load balancer
# 2. Kubernetes deployment
@kubernetes-specialist Create Kubernetes manifests for:
- Microservices deployment
- Ingress configuration
- ConfigMaps and Secrets
- HorizontalPodAutoscaler
# 3. CI/CD pipeline
@devops-engineer Set up GitHub Actions workflow for:
- Build and test
- Docker image build and push
- Kubernetes deployment
- Automated rollback on failure
# 4. Monitoring
@monitoring-specialist Set up:
- Prometheus metrics
- Grafana dashboards
- Alert rules for SLOs
- On-call rotation
```
### Infrastructure as Code Workflow
```bash theme={null}
# 1. Plan infrastructure
@cloud-architect Design AWS infrastructure for microservices
# 2. Generate Terraform
@terraform-engineer Create Terraform modules for:
- VPC and networking
- EKS cluster
- RDS database
- S3 buckets
- IAM roles
# 3. Review
@terraform-iac-reviewer Review Terraform code for best practices
# 4. Apply
@devops-engineer Apply Terraform and verify infrastructure
```
### Kubernetes Migration
```bash theme={null}
# 1. Architecture
@microservices-architect Design microservices architecture
# 2. Containerization
@devops-engineer Containerize existing applications
# 3. Kubernetes setup
@kubernetes-specialist:
- Create Kubernetes manifests
- Set up namespaces and RBAC
- Configure networking
- Set up persistent storage
# 4. Migration
@deployment-engineer Plan and execute migration with zero downtime
```
## Best Practices
### 1. Infrastructure as Code
```bash theme={null}
# Version control everything
@terraform-engineer Store all infrastructure as code in Git
# Use modules for reusability
@terraform-engineer Create reusable Terraform modules
# Implement GitOps
@devops-engineer Set up ArgoCD for Kubernetes deployments
```
### 2. Observability
```bash theme={null}
# Three pillars of observability
@monitoring-specialist Set up:
- Metrics (Prometheus)
- Logs (Loki/ELK)
- Traces (Tempo/Jaeger)
# Define SLOs
@sre-engineer Define Service Level Objectives:
- Availability: 99.9%
- Latency: p95 < 200ms
- Error rate: < 0.1%
```
### 3. Security
```bash theme={null}
# Security scanning
@security-engineer Implement:
- Container image scanning
- Infrastructure vulnerability scanning
- Secrets management (Vault, AWS Secrets Manager)
- Network policies
# Compliance
@security-engineer Ensure compliance with SOC2/HIPAA/GDPR
```
### 4. Cost Optimization
```bash theme={null}
# Right-sizing
@cloud-architect Analyze and optimize resource usage
# Auto-scaling
@kubernetes-specialist Implement HPA and cluster autoscaling
# Reserved instances
@cloud-architect Purchase reserved instances for predictable workloads
```
## Real-World Examples
### Example 1: Microservices on Kubernetes
```bash theme={null}
# Install specialists
npx claude-code-templates@latest \
--agent kubernetes-specialist \
--agent microservices-architect \
--agent monitoring-specialist
# Deploy
@microservices-architect Design service boundaries and communication
@kubernetes-specialist Deploy services with:
- Service mesh (Istio) for traffic management
- mTLS for secure communication
- Distributed tracing
- Canary deployments
@monitoring-specialist Set up observability stack
```
### Example 2: Multi-Cloud Infrastructure
```bash theme={null}
# Install cloud specialists
npx claude-code-templates@latest \
--agent cloud-architect \
--agent terraform-engineer \
--agent devops-engineer
# Design and implement
@cloud-architect Design multi-cloud architecture with:
- Primary workloads on AWS
- DR site on Azure
- CDN on Cloudflare
@terraform-engineer Implement with Terraform Cloud
```
### Example 3: SRE Implementation
```bash theme={null}
# Install SRE tools
npx claude-code-templates@latest \
--agent sre-engineer \
--agent monitoring-specialist \
--agent incident-responder
# Implement SRE practices
@sre-engineer:
- Define SLOs and error budgets
- Set up monitoring and alerting
- Create runbooks
- Implement chaos engineering
```
## DevOps Template
```bash theme={null}
npx claude-code-templates@latest --template devops-pipeline
```
**Includes:**
* DevOps engineer agent
* Cloud architect agent
* Kubernetes specialist agent
* Terraform engineer agent
* Monitoring specialist agent
* Deployment automation
* Infrastructure monitoring
## Next Steps
* [Browse all DevOps components](https://aitmpl.com/?category=devops-infrastructure)
* [View development team](/categories/development-team)
* [Explore database components](/categories/database)
* [Check out security components](/categories/security)
# Security Components
Source: https://davila7-claude-code-templates-86.mintlify.app/categories/security
Comprehensive security tools including agents, commands, and hooks for auditing, scanning, and hardening
# Security Components
The Security category includes agents, commands, and hooks focused on application security, vulnerability detection, secrets management, and security best practices.
Explore all security components at **aitmpl.com**
## Quick Install
```bash theme={null}
# Install security essentials
npx claude-code-templates@latest \
--command security-audit \
--hook security/secret-scanner \
--hook security/dangerous-command-blocker \
--setting permissions/read-only-mode
# Or install the security template
npx claude-code-templates@latest --template security-hardened
```
## Security Commands
Comprehensive security assessment and vulnerability analysis
**What it checks:**
* Dependency vulnerabilities
* Authentication & authorization
* Input validation & sanitization
* Data protection & encryption
* Secrets management
* Error handling & logging
* Infrastructure security
* Security headers & CORS
```bash theme={null}
npx claude-code-templates@latest --command security-audit
```
**Usage:**
```bash theme={null}
# Full audit
/security-audit --full
# Focus on specific area
/security-audit authentication
/security-audit dependencies
```
**Output includes:**
* Severity levels (Critical, High, Medium, Low)
* Specific file references
* Remediation steps
* Code examples
Scan codebase for hardcoded secrets, API keys, and credentials
**Detects:**
* API keys and tokens
* Database passwords
* Private keys and certificates
* OAuth secrets
* Cloud provider credentials
* Slack/Discord webhooks
```bash theme={null}
npx claude-code-templates@latest --command secrets-scanner
```
**Usage:**
```bash theme={null}
/secrets-scanner
```
Check dependencies for known vulnerabilities using npm audit, pip check, etc.
```bash theme={null}
npx claude-code-templates@latest --command dependency-audit
```
Apply security best practices to your application
**Applies:**
* Security headers
* CORS configuration
* Input validation
* Rate limiting
* CSP policies
* Cookie security
```bash theme={null}
npx claude-code-templates@latest --command security-hardening
```
Automated penetration testing workflows
```bash theme={null}
npx claude-code-templates@latest --command penetration-test
```
Add secure authentication to your application
**Options:**
* JWT authentication
* OAuth2 integration
* Session management
* Password hashing (bcrypt, argon2)
* MFA/2FA support
```bash theme={null}
npx claude-code-templates@latest --command add-authentication-system
```
## Security Hooks
### Prevent Secret Leaks
Automatically scan commits for secrets before they're pushed
**How it works:**
1. Runs before each commit (pre-commit hook)
2. Scans all staged files for secret patterns
3. Blocks commit if secrets are detected
4. Shows which files and lines contain secrets
```bash theme={null}
npx claude-code-templates@latest --hook security/secret-scanner
```
**Detects:**
```regex theme={null}
# API Keys
(api[_-]?key|apikey)\s*=\s*["'][^"']
# AWS Credentials
(aws[_-]?access[_-]?key[_-]?id)
# Database URLs
(postgres|mysql|mongodb)://[^\s]+:[^\s]+@
# Private Keys
-----BEGIN (RSA |EC )?PRIVATE KEY-----
# OAuth Tokens
(client[_-]?secret|oauth[_-]?token)
```
**Example Output:**
```
❌ SECRET DETECTED in config/database.js:12
const password = "my_secret_password"
❌ SECRET DETECTED in .env.production:5
API_KEY=sk_live_abc123xyz
Commit blocked. Remove secrets before committing.
```
### Block Dangerous Operations
Prevent dangerous or destructive commands
**Blocks:**
* Force push to main/master
* Rebase on shared branches
* Hard reset
* Direct push to protected branches
* Destructive rm commands
```bash theme={null}
npx claude-code-templates@latest --hook security/dangerous-command-blocker
```
**Example:**
```bash theme={null}
# Blocked
git push --force origin main
# ✗ Error: Force push to main branch is not allowed
# Allowed
git push origin feature/my-feature
# ✓ Success
```
### Protect Sensitive Files
Prevent committing sensitive files
**Protected files:**
* `.env`, `.env.local`, `.env.production`
* `credentials.json`, `secrets.yaml`
* `id_rsa`, `*.pem`, `*.key`
* `*.p12`, `*.pfx`
```bash theme={null}
npx claude-code-templates@latest --hook security/file-protection
```
### Automated Security Scans
Run security checks before commits
**Runs:**
* Dependency vulnerability scan
* Secret detection
* Code quality checks
* SAST (Static Application Security Testing)
```bash theme={null}
npx claude-code-templates@latest --hook security/security-scanner
```
## Security Settings
Restrict Claude Code to read-only operations
**Blocks:**
* File writes and edits
* Git commits and pushes
* Bash commands that modify files
* Destructive operations
**Use cases:**
* Code review mode
* Production environment analysis
* Learning from existing codebases
* Untrusted environments
```bash theme={null}
npx claude-code-templates@latest --setting permissions/read-only-mode
```
Limit bash command execution to safe operations
```bash theme={null}
npx claude-code-templates@latest --setting permissions/restricted-bash
```
Disable MCP servers with dangerous capabilities
```bash theme={null}
npx claude-code-templates@latest --setting mcp/disable-risky-servers
```
## Security Agents
Security engineering specialist (part of DevOps Infrastructure category)
**Expertise:**
* Security architecture
* Threat modeling
* Secure coding practices
* Security testing
* Incident response
```bash theme={null}
npx claude-code-templates@latest --agent security-engineer
```
## Security Workflows
### Pre-Commit Security
Automatic security checks before every commit:
```bash theme={null}
# Install security hooks
npx claude-code-templates@latest \
--hook security/secret-scanner \
--hook security/dangerous-command-blocker \
--hook security/file-protection
# Now every commit is automatically scanned
git commit -m "Add user service"
# ✓ No secrets detected
# ✓ No dangerous commands
# ✓ No sensitive files
# Commit successful
```
### Regular Security Audits
Schedule comprehensive security audits:
```bash theme={null}
# Install security audit command
npx claude-code-templates@latest --command security-audit
# Run full audit weekly
/security-audit --full
# Or focus on specific areas
/security-audit dependencies # Check dependency vulnerabilities
/security-audit authentication # Review auth implementation
/security-audit data-protection # Check encryption and data handling
```
### Security Hardening
Apply security best practices to new projects:
```bash theme={null}
# Install hardening command
npx claude-code-templates@latest --command security-hardening
# Apply hardening
/security-hardening
# Applies:
# - Security headers (CSP, HSTS, X-Frame-Options)
# - CORS configuration
# - Rate limiting
# - Input validation
# - Cookie security
```
### Secrets Management
Never commit secrets:
```bash theme={null}
# Install secret scanner
npx claude-code-templates@latest --hook security/secret-scanner
# Use environment variables
echo "API_KEY=your_key_here" >> .env
echo ".env" >> .gitignore
# Commits with secrets are blocked
git commit -m "Add config"
# ❌ SECRET DETECTED: Remove secrets before committing
```
## Security Best Practices
### 1. Defense in Depth
Layer multiple security controls:
```bash theme={null}
# Install multiple security components
npx claude-code-templates@latest \
--hook security/secret-scanner \
--hook security/dangerous-command-blocker \
--command security-audit \
--setting permissions/restricted-bash
```
### 2. Automated Security
Automate security checks in CI/CD:
```yaml theme={null}
# .github/workflows/security.yml
name: Security Scan
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: npx claude-code-templates@latest --command security-audit
```
### 3. Regular Audits
Schedule regular security reviews:
```bash theme={null}
# Weekly dependency audit
/dependency-audit
# Monthly full security audit
/security-audit --full
# After each major feature
/security-audit authentication
```
### 4. Least Privilege
Restrict permissions when possible:
```bash theme={null}
# Enable read-only mode for code review
npx claude-code-templates@latest --setting permissions/read-only-mode
# Disable risky MCP servers
npx claude-code-templates@latest --setting mcp/disable-risky-servers
```
## Security Template
Use the pre-configured security template:
```bash theme={null}
npx claude-code-templates@latest --template security-hardened
```
**Includes:**
* Security audit command
* Secret scanner hook
* Dangerous command blocker
* File protection hook
* Read-only mode setting
* Branch protection
* Security engineer agent
## Real-World Examples
### Example 1: Prevent Secret Leak
```bash theme={null}
# Developer accidentally commits secret
echo "API_KEY=sk_live_abc123" >> config.js
git add config.js
git commit -m "Add config"
# ❌ SECRET DETECTED in config.js:1
# API_KEY=sk_live_abc123
#
# Commit blocked. Remove secrets before committing.
# Developer fixes
echo "API_KEY=process.env.API_KEY" > config.js
echo "API_KEY=sk_live_abc123" >> .env
echo ".env" >> .gitignore
git add config.js .gitignore
git commit -m "Add config with env vars"
# ✓ Success
```
### Example 2: Comprehensive Audit
```bash theme={null}
/security-audit --full
# ⚠️ MEDIUM: Dependency vulnerability found
# Package: express@4.17.1
# Vulnerability: CVE-2024-xxxxx
# Fix: npm install express@4.18.2
#
# ❌ CRITICAL: Hardcoded database password
# File: src/db/connection.js:5
# Line: const password = "my_password"
# Fix: Use environment variables
#
# ⚠️ HIGH: Missing security headers
# File: src/server.js
# Issue: No CSP, HSTS, or X-Frame-Options headers
# Fix: Add helmet.js middleware
```
## Next Steps
* [Browse all security components](https://aitmpl.com/?category=security)
* [View development team](/categories/development-team)
* [Explore DevOps components](/categories/devops-infrastructure)
* [Check out testing components](/categories/testing)
# Testing Components
Source: https://davila7-claude-code-templates-86.mintlify.app/categories/testing
Testing agents, commands, and hooks for unit, integration, E2E, and performance testing
# Testing Components
The Testing category includes specialists for test generation, test automation, quality assurance, and comprehensive testing strategies across unit, integration, E2E, and performance testing.
Explore all testing components at **aitmpl.com**
## Quick Install
```bash theme={null}
# Install testing essentials
npx claude-code-templates@latest \
--agent test-generator \
--command setup-testing \
--command e2e-setup \
--hook testing/test-runner
# Or install the testing template
npx claude-code-templates@latest --template testing-suite
```
## Testing Agents
Automated test generation with comprehensive coverage
**Expertise:**
* Unit test generation
* Integration test design
* E2E test scenarios
* Test data factories
* Mocking and stubbing strategies
* Coverage analysis
* Edge case identification
**Technologies:**
* Jest, Vitest, Mocha
* React Testing Library, Vue Test Utils
* Playwright, Cypress, Puppeteer
* Supertest for API testing
* MSW (Mock Service Worker)
```bash theme={null}
npx claude-code-templates@latest --agent test-generator
```
**Example Usage:**
```
@test-generator Generate comprehensive tests for the user
authentication service with 80%+ coverage. Include:
- Unit tests for password hashing
- Integration tests for login/logout
- E2E tests for complete auth flow
- Edge cases (expired tokens, invalid credentials)
```
Test execution automation and orchestration
**Expertise:**
* Test suite execution
* Parallel test running
* Test result reporting
* Flaky test detection
* Test prioritization
```bash theme={null}
npx claude-code-templates@latest --agent test-runner
```
## Testing Commands
### Test Infrastructure Setup
Configure comprehensive testing infrastructure
**Sets up:**
* Test framework (Jest/Vitest/Mocha)
* Test runners and reporters
* Coverage tools
* Mocking libraries
* CI/CD integration
* Test utilities
```bash theme={null}
npx claude-code-templates@latest --command setup-testing
```
**Usage:**
```bash theme={null}
/setup-testing
```
**Creates:**
* `jest.config.js` or `vitest.config.js`
* Test setup files
* Example test files
* Coverage configuration
* CI/CD test workflow
Set up end-to-end testing with Playwright or Cypress
**Options:**
* Playwright (recommended)
* Cypress
* TestCafe
* Puppeteer
```bash theme={null}
npx claude-code-templates@latest --command e2e-setup
```
**Features:**
* Browser automation setup
* Page object models
* Test fixtures
* Screenshot/video recording
* CI/CD integration
Complete testing setup with all test types
```bash theme={null}
npx claude-code-templates@latest --command setup-comprehensive-testing
```
Configure load and performance testing
**Tools:**
* k6
* Artillery
* Apache JMeter
```bash theme={null}
npx claude-code-templates@latest --command setup-load-testing
```
Set up visual regression testing
```bash theme={null}
npx claude-code-templates@latest --command setup-visual-testing
```
### Test Generation Commands
Auto-generate unit and integration tests
**Generates:**
* Unit tests for functions and classes
* Integration tests for modules
* Mock implementations
* Test data factories
* Edge case tests
```bash theme={null}
npx claude-code-templates@latest --command generate-tests
```
**Usage:**
```bash theme={null}
# Generate tests for specific file
/generate-tests src/services/user.service.ts
# Generate tests for directory
/generate-tests src/api
# Generate with specific coverage target
/generate-tests src/utils --coverage 90
```
Generate comprehensive test case documentation
```bash theme={null}
npx claude-code-templates@latest --command generate-test-cases
```
Interactive test writing assistant
```bash theme={null}
npx claude-code-templates@latest --command write-tests
```
### Test Analysis Commands
Analyze and improve test coverage
**Analyzes:**
* Line coverage
* Branch coverage
* Function coverage
* Statement coverage
* Uncovered code paths
**Reports:**
* Coverage summary
* Files with low coverage
* Specific uncovered lines
* Coverage trends
```bash theme={null}
npx claude-code-templates@latest --command test-coverage
```
**Usage:**
```bash theme={null}
# Check coverage
/test-coverage
# Set minimum threshold
/test-coverage --threshold 80
# Generate HTML report
/test-coverage --report html
```
Analyze test quality and effectiveness
**Checks:**
* Test naming conventions
* Test independence
* Assertion quality
* Test duplication
* Flaky test detection
```bash theme={null}
npx claude-code-templates@latest --command test-quality-analyzer
```
### Specialized Testing Commands
Set up mutation testing for test effectiveness
**What is mutation testing:**
Introduces small changes (mutations) to code and verifies tests catch them.
```bash theme={null}
npx claude-code-templates@latest --command add-mutation-testing
```
Set up property-based testing with fast-check
```bash theme={null}
npx claude-code-templates@latest --command add-property-based-testing
```
Orchestrate complex test automation workflows
```bash theme={null}
npx claude-code-templates@latest --command test-automation-orchestrator
```
Automate test changelog generation
```bash theme={null}
npx claude-code-templates@latest --command test-changelog-automation
```
Comprehensive web application testing
```bash theme={null}
npx claude-code-templates@latest --command webapp-testing
```
## Testing Hooks
Automatically run tests before commits
**Behavior:**
* Runs before each commit (pre-commit hook)
* Executes tests for changed files
* Blocks commit if tests fail
* Shows test results and failures
**Configuration:**
* Run all tests or only affected tests
* Set timeout limits
* Configure coverage thresholds
```bash theme={null}
npx claude-code-templates@latest --hook testing/test-runner
```
**Example:**
```bash theme={null}
git commit -m "Add user service"
# Running tests for changed files...
# ✓ user.service.test.ts (5 tests)
# ✓ auth.service.test.ts (8 tests)
#
# 13 tests passed
# Coverage: 87%
# Commit successful
```
## Testing Strategies
### Testing Pyramid
```
/\
/E2E\
/______\
/ \
/Integration\
/____________\
/ \
/ Unit Tests \
/__________________\
```
**Unit Tests (70%)**: Fast, isolated tests for individual functions/methods
**Integration Tests (20%)**: Test module interactions and API endpoints
**E2E Tests (10%)**: Test complete user workflows through the UI
### Test-Driven Development (TDD)
```bash theme={null}
# 1. Write failing test
@test-generator Generate test for user registration validation
# 2. Implement feature
@backend-developer Implement user registration
# 3. Run tests
/test-coverage
# 4. Refactor
@code-architect Refactor user registration for better design
```
## Testing Workflows
### Complete Testing Setup
```bash theme={null}
# 1. Install testing tools
npx claude-code-templates@latest \
--agent test-generator \
--command setup-testing \
--command e2e-setup \
--hook testing/test-runner
# 2. Configure testing infrastructure
/setup-testing
/e2e-setup playwright
# 3. Generate tests
@test-generator Generate tests for existing codebase with 80% coverage
# 4. Run tests
npm test
# 5. Check coverage
/test-coverage
```
### Feature Development with Tests
```bash theme={null}
# 1. Write test first (TDD)
@test-generator Generate tests for new payment processing feature
# 2. Implement feature
@backend-developer Implement payment processing
# 3. Run tests
npm test
# 4. Verify coverage
/test-coverage src/services/payment.service.ts --threshold 85
# 5. Add E2E tests
@test-generator Generate E2E tests for payment flow
```
### CI/CD Testing Pipeline
```bash theme={null}
# Install tools
npx claude-code-templates@latest \
--command setup-testing \
--command test-coverage
# Create GitHub Actions workflow
@devops-engineer Set up testing workflow:
- Run unit tests on PR
- Run integration tests on merge to main
- Run E2E tests before deploy
- Fail if coverage < 80%
- Upload coverage reports
```
## Best Practices
### 1. Comprehensive Coverage
```bash theme={null}
# Aim for 80%+ coverage
/test-coverage --threshold 80
# Focus on critical paths
@test-generator Prioritize tests for:
- Authentication and authorization
- Payment processing
- Data validation
- Error handling
```
### 2. Test Independence
```bash theme={null}
# Each test should be independent
@test-generator Generate tests that:
- Don't rely on execution order
- Use test fixtures for setup
- Clean up after themselves
- Mock external dependencies
```
### 3. Fast Feedback
```bash theme={null}
# Keep tests fast
@test-generator:
- Unit tests: < 100ms each
- Integration tests: < 1s each
- E2E tests: < 30s each
# Run tests in parallel
/setup-testing --parallel
```
### 4. Meaningful Tests
```bash theme={null}
# Test behavior, not implementation
@test-generator Write tests that:
- Test user-facing behavior
- Verify business logic
- Check error scenarios
- Don't test implementation details
```
## Real-World Examples
### Example 1: API Testing
```bash theme={null}
# Install testing tools
npx claude-code-templates@latest \
--agent test-generator \
--command setup-testing
# Generate API tests
@test-generator Generate tests for REST API:
- GET /users (list users)
- POST /users (create user)
- PUT /users/:id (update user)
- DELETE /users/:id (delete user)
Include:
- Happy path tests
- Validation errors
- Authentication checks
- Authorization checks
```
### Example 2: Frontend Component Testing
```bash theme={null}
# Install tools
npx claude-code-templates@latest \
--agent test-generator \
--command setup-testing
# Generate component tests
@test-generator Generate React tests for LoginForm component:
- Renders correctly
- Validates email format
- Validates password length
- Shows loading state
- Handles login success
- Handles login errors
- Disables submit when invalid
```
### Example 3: E2E Testing
```bash theme={null}
# Install E2E tools
npx claude-code-templates@latest \
--agent test-generator \
--command e2e-setup
# Setup E2E
/e2e-setup playwright
# Generate E2E tests
@test-generator Generate E2E tests for checkout flow:
1. User adds product to cart
2. User proceeds to checkout
3. User enters shipping info
4. User enters payment info
5. User confirms order
6. User sees confirmation page
Include error scenarios:
- Invalid credit card
- Out of stock items
- Network errors
```
### Example 4: Load Testing
```bash theme={null}
# Install load testing
npx claude-code-templates@latest --command setup-load-testing
# Setup
/setup-load-testing k6
# Create load test
@test-generator Generate k6 load test:
- Target: 1000 RPS
- Duration: 5 minutes
- Ramp-up: 1 minute
- Endpoints: /api/products, /api/users
- Success criteria: p95 < 200ms, errors < 1%
```
## Testing Template
```bash theme={null}
npx claude-code-templates@latest --template testing-suite
```
**Includes:**
* Test generator agent
* Test runner agent
* Setup testing command
* E2E setup command
* Test coverage command
* Test runner hook (pre-commit)
* Load testing setup
* Visual testing setup
## Test Types
### Unit Tests
* Test individual functions/methods
* Fast execution (\< 100ms)
* No external dependencies
* High code coverage
### Integration Tests
* Test module interactions
* Test API endpoints
* Test database operations
* Mock external services
### E2E Tests
* Test complete user workflows
* Browser automation
* Real user interactions
* Covers multiple systems
### Performance Tests
* Load testing (k6, Artillery)
* Stress testing
* Spike testing
* Soak testing
### Visual Tests
* Screenshot comparison
* Visual regression detection
* Cross-browser testing
* Responsive design testing
## Next Steps
* [Browse all testing components](https://aitmpl.com/?category=testing)
* [View development team](/categories/development-team)
* [Explore security components](/categories/security)
* [Check out DevOps components](/categories/devops-infrastructure)
# Analytics Dashboard
Source: https://davila7-claude-code-templates-86.mintlify.app/cli/analytics
Real-time analytics dashboard for monitoring Claude Code usage and sessions
# Analytics Dashboard
The Analytics Dashboard provides comprehensive real-time monitoring of your Claude Code usage, conversations, and performance metrics.
## Launch Analytics
### Basic Launch
Start the analytics dashboard:
```bash theme={null}
cct --analytics
```
This:
1. Starts web server on `http://localhost:3333`
2. Opens dashboard in your default browser
3. Begins real-time monitoring
### With Remote Access
Enable Cloudflare Tunnel for remote access:
```bash theme={null}
cct --analytics --tunnel
```
Generates a public URL like:
```
https://analytics-abc123.trycloudflare.com
```
Access from any device with internet connection.
### Specific Views
Open to specific dashboard pages:
```bash theme={null}
# Open to agents view
cct --agents
# Open to Year in Review 2025
cct --2025
```
## Dashboard Features
### Overview Page
The main dashboard shows:
**Real-time Statistics**:
* Total conversations
* Token usage (input/output)
* Cache usage (creation/read)
* Active projects count
* Last activity timestamp
**Recent Conversations**:
* Conversation list with timestamps
* Project names and paths
* Message counts
* Token usage per conversation
* Conversation states (active/completed)
**Activity Heatmap**:
* Visual representation of daily activity
* Hour-by-hour usage patterns
* Peak usage times
* Activity trends
### Agents Analytics
Dedicated agent performance tracking:
```bash theme={null}
cct --agents
```
**Metrics**:
* Agent usage frequency
* Average tokens per agent
* Success rates
* Response times
* Popular agents
**Analysis**:
* Most used agents
* Agent effectiveness
* Usage patterns
* Recommendations
### Session Data
Max plan usage tracking:
**Session Limits**:
* Current session count
* 5-hour rolling window
* Remaining messages
* Reset time
**Historical Data**:
* Session history
* Usage patterns
* Peak periods
### Conversation Details
Detailed conversation breakdown:
**For each conversation**:
* Project name and path
* Creation timestamp
* Last update time
* Message count
* Total tokens (input/output)
* Cache tokens (creation/read)
* Tool usage statistics
* Conversation state
### Token Analytics
**Input Tokens**:
* Total input tokens
* Average per message
* Trends over time
**Output Tokens**:
* Total output tokens
* Average per response
* Generation patterns
**Cache Tokens**:
* Cache creation tokens
* Cache read tokens
* Cache efficiency
### Project Analytics
**Active Projects**:
* Project names
* Last activity
* Conversation counts
* Token usage per project
* Project status
**Project Insights**:
* Most active projects
* Token consumption by project
* Project trends
## Year in Review 2025
Comprehensive annual usage statistics:
```bash theme={null}
cct --2025
```
### Metrics Included
**Usage Stats**:
* Total conversations
* Total messages
* Total tokens
* Active days
* Average daily usage
**Top Lists**:
* Most used agents
* Most active projects
* Busiest days
* Peak hours
**Achievements**:
* Milestones reached
* Productivity metrics
* Growth trends
**Visualizations**:
* Usage timeline
* Activity calendar
* Token distribution
* Agent usage breakdown
## Real-Time Updates
The dashboard updates automatically:
**WebSocket Connection**:
* Real-time data streaming
* Instant conversation updates
* Live token counting
* State change notifications
**Refresh Intervals**:
* Conversations: Live updates
* Statistics: Every 5 seconds
* Charts: Every 10 seconds
## Analytics Options
Launch analytics dashboard
Enable Cloudflare Tunnel for remote access (use with --analytics)
Launch analytics dashboard with agents view
Launch Year in Review 2025 dashboard
Enable verbose logging for debugging
## Configuration
### Port Configuration
Default port: `3333`
To use a different port, modify environment:
```bash theme={null}
PORT=8080 cct --analytics
```
### Data Sources
Analytics reads from:
```bash theme={null}
~/.claude/ # Claude Code directory
~/.claude/conversations/ # Conversation history
~/.claude/statsig/ # Usage statistics
```
### Cache Configuration
Data caching for performance:
* **Cache duration**: 60 seconds
* **Refresh interval**: 5 seconds
* **Memory threshold**: 300 MB
## Performance Monitoring
### System Resources
The dashboard monitors:
**Memory Usage**:
* Current memory consumption
* Memory threshold (300 MB)
* Garbage collection triggers
**Performance Metrics**:
* Data load times
* Query performance
* WebSocket latency
### Optimization
For large conversation histories:
1. **Cleanup old conversations**:
```bash theme={null}
# Set retention policy
cct --setting retention/retention-7-days
```
2. **Limit conversation loading**:
* Dashboard loads last 1000 conversations
* Older conversations available on demand
3. **Use cache effectively**:
* Data cached for 60 seconds
* Reduces file system reads
## Cloudflare Tunnel
### Setup Remote Access
Enable public URL:
```bash theme={null}
cct --analytics --tunnel
```
**Output**:
```
🌐 Cloudflare Tunnel:
✅ Public URL: https://analytics-abc123.trycloudflare.com
📱 Scan QR code to access from mobile
```
### Security Considerations
**Public URLs**:
* URLs are temporary (expire after session)
* No authentication by default
* Anyone with URL can access
**Best Practices**:
1. Use only when needed
2. Share URL privately
3. Close tunnel after use
4. Don't share URLs publicly
### Mobile Access
Access from mobile devices:
1. Launch with tunnel:
```bash theme={null}
cct --analytics --tunnel
```
2. Scan QR code displayed in terminal
3. Or open generated URL in mobile browser
## Chats Mobile Interface
Mobile-optimized conversation browser:
```bash theme={null}
cct --chats
cct --chats-mobile
```
**Features**:
* Touch-optimized UI
* Quick conversation access
* Search and filter
* Swipe gestures
* Responsive design
**With Remote Access**:
```bash theme={null}
cct --chats --tunnel
```
## Plugin Dashboard
Manage Claude Code plugins:
```bash theme={null}
cct --plugins
```
**Features**:
* Browse plugin marketplace
* View installed plugins
* Manage permissions
* Enable/disable plugins
## Skills Dashboard
Explore Claude Code skills:
```bash theme={null}
cct --skills-manager
```
**Features**:
* View installed skills
* Explore skill catalog
* Skill documentation
* Installation status
## Teams Dashboard
Multi-agent collaboration review:
```bash theme={null}
cct --teams
```
**Features**:
* Team session history
* Agent collaboration metrics
* Team performance
* Collaboration patterns
## Use Cases
### 1. Daily Monitoring
```bash theme={null}
# Start day with analytics check
cct --analytics
# Review:
# - Yesterday's usage
# - Active conversations
# - Token consumption
```
### 2. Team Reporting
```bash theme={null}
# Generate weekly report
cct --analytics
# Export metrics:
# - Screenshot dashboard
# - Note key statistics
# - Share with team
```
### 3. Performance Optimization
```bash theme={null}
# Analyze token usage
cct --analytics
# Identify:
# - High token conversations
# - Inefficient patterns
# - Optimization opportunities
```
### 4. Mobile Monitoring
```bash theme={null}
# Enable remote access
cct --analytics --tunnel
# Monitor from:
# - Smartphone
# - Tablet
# - Another computer
```
### 5. Agent Effectiveness
```bash theme={null}
# Review agent performance
cct --agents
# Analyze:
# - Most used agents
# - Agent success rates
# - Usage patterns
```
## Troubleshooting
### Dashboard Won't Open
**Check port availability**:
```bash theme={null}
lsof -i :3333
```
**Kill conflicting process**:
```bash theme={null}
kill -9 $(lsof -t -i :3333)
```
**Use different port**:
```bash theme={null}
PORT=8080 cct --analytics
```
### No Data Displayed
**Verify Claude directory**:
```bash theme={null}
ls -la ~/.claude/
ls -la ~/.claude/conversations/
```
**Check permissions**:
```bash theme={null}
chmod -R 755 ~/.claude/
```
**Verify conversations exist**:
```bash theme={null}
find ~/.claude/conversations/ -name "*.json" | head
```
### Slow Performance
**Clear old conversations**:
```bash theme={null}
# Set retention policy
cct --setting retention/retention-7-days
# Manual cleanup
find ~/.claude/conversations/ -mtime +30 -delete
```
**Increase memory threshold**:
Edit `src/analytics.js` (for advanced users).
### Tunnel Connection Failed
**Check network**:
```bash theme={null}
ping trycloudflare.com
```
**Retry tunnel**:
```bash theme={null}
cct --analytics --tunnel
```
**Use without tunnel**:
```bash theme={null}
cct --analytics
```
### WebSocket Disconnects
**Check firewall**:
* Allow WebSocket connections on port 3333
* Disable firewall temporarily to test
**Restart dashboard**:
```bash theme={null}
# Kill existing
pkill -f analytics
# Restart
cct --analytics
```
## Advanced Usage
### Custom Analytics
Extend with custom queries:
```javascript theme={null}
// Read conversation data
const fs = require('fs');
const path = require('path');
const homeDir = require('os').homedir();
const conversationsDir = path.join(homeDir, '.claude', 'conversations');
const conversations = fs.readdirSync(conversationsDir)
.filter(f => f.endsWith('.json'))
.map(f => JSON.parse(fs.readFileSync(path.join(conversationsDir, f))));
// Custom analysis
const totalTokens = conversations.reduce((sum, conv) => {
return sum + (conv.usage?.input_tokens || 0) + (conv.usage?.output_tokens || 0);
}, 0);
console.log('Total tokens:', totalTokens);
```
### Export Analytics Data
```bash theme={null}
# Export to JSON
node -e "const fs = require('fs'); const data = require('$HOME/.claude/conversations/conversation-123.json'); fs.writeFileSync('export.json', JSON.stringify(data, null, 2));"
```
### Integration with Monitoring Tools
Forward metrics to external tools:
```javascript theme={null}
// Example: Send to monitoring service
const metrics = {
timestamp: Date.now(),
conversations: conversationCount,
tokens: totalTokens,
projects: activeProjects.length
};
// POST to monitoring API
fetch('https://monitoring.example.com/metrics', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(metrics)
});
```
## Next Steps
* [Health Check](/cli/health-check) - Verify Claude Code setup
* [CLI Flags Reference](/cli/flags) - Complete flags documentation
* [Configuration Guide](/cli/configuration) - Settings and config files
* [Environment Variables](/cli/environment-variables) - Configure analytics
# Configuration Files
Source: https://davila7-claude-code-templates-86.mintlify.app/cli/configuration
Claude Code configuration files, settings, and project structure
# Configuration Files and Settings
Claude Code uses multiple configuration files to manage settings, permissions, hooks, and integrations. Understanding these files helps you customize and optimize your Claude Code setup.
## Configuration Hierarchy
Claude Code reads configuration from multiple locations with a specific precedence:
```
1. ~/.claude/settings.json (User-level settings)
2. .claude/settings.json (Project-level settings)
3. .claude/settings.local.json (Local developer overrides)
```
Settings cascade and merge, with later files overriding earlier ones.
## Directory Structure
### User Directory
Global configuration directory:
```
~/.claude/
├── settings.json # User-level settings
├── .claude.json # Authentication config
├── agents/ # Global agents
│ ├── customer-support.md
│ └── security-auditor.md
├── commands/ # Global commands
│ ├── check-file.md
│ └── generate-tests.md
├── conversations/ # Conversation history
│ ├── conv-123.json
│ └── conv-456.json
└── statsig/ # Usage statistics
```
### Project Directory
Project-specific configuration:
```
.claude/
├── CLAUDE.md # Project context and guidelines
├── settings.json # Project settings
├── settings.local.json # Local overrides (gitignored)
├── agents/ # Project agents
│ ├── frontend-developer.md
│ └── backend-developer.md
├── commands/ # Project commands
│ ├── setup-testing.md
│ └── deploy-staging.md
└── scripts/ # Helper scripts
├── context-monitor.py
└── token-counter.py
.mcp.json # MCP server configurations
```
## settings.json
### User Settings
Location: `~/.claude/settings.json`
User-level settings apply globally across all projects.
**Example**:
```json theme={null}
{
"model": "claude-sonnet-4-20250514",
"telemetryEnabled": false,
"cleanupPeriodDays": 30,
"permissions": {
"allow": [
{
"type": "exec",
"pattern": "npm"
},
{
"type": "exec",
"pattern": "git"
}
],
"deny": [
{
"type": "read",
"pattern": "**/.env*"
},
{
"type": "read",
"pattern": "**/secrets/**"
}
]
},
"hooks": {
"PreToolUse": [
{
"command": "echo 'Pre-tool use hook'",
"description": "Log before tool usage"
}
],
"PostToolUse": [
{
"command": "echo 'Post-tool use hook'",
"description": "Log after tool usage"
}
]
},
"env": {
"NODE_ENV": "development"
}
}
```
### Project Settings
Location: `.claude/settings.json`
Project-specific settings for team sharing (committed to git).
**Example**:
```json theme={null}
{
"model": "claude-sonnet-4-20250514",
"permissions": {
"allow": [
{
"type": "exec",
"pattern": "npm run *"
},
{
"type": "exec",
"pattern": "yarn *"
}
],
"additionalDirectories": [
"~/projects/shared-library"
]
},
"hooks": {
"PreToolUse": [
{
"command": "npm run lint",
"description": "Run linter before file modifications"
}
]
},
"enableAllProjectMcpServers": true,
"enabledMcpjsonServers": [
"github",
"web-fetch"
]
}
```
### Local Settings
Location: `.claude/settings.local.json`
Developer-specific overrides (gitignored, never committed).
**Example**:
```json theme={null}
{
"model": "claude-haiku-4-20250514",
"telemetryEnabled": false,
"permissions": {
"additionalDirectories": [
"~/my-personal-scripts"
]
},
"env": {
"DEBUG": "true"
}
}
```
## settings.json Fields
### Model Selection
Claude model to use for conversations
**Options**:
* `claude-sonnet-4-20250514` - Balanced performance
* `claude-opus-4-20250514` - Maximum capability
* `claude-haiku-4-20250514` - Fast responses
**Example**:
```json theme={null}
{
"model": "claude-sonnet-4-20250514"
}
```
### Permissions
Control what Claude Code can access and execute
**Structure**:
```json theme={null}
{
"permissions": {
"allow": [
{
"type": "exec|read|write",
"pattern": "glob-pattern"
}
],
"deny": [
{
"type": "exec|read|write",
"pattern": "glob-pattern"
}
],
"additionalDirectories": [
"/path/to/directory"
]
}
}
```
**Permission Types**:
* `exec` - Command execution
* `read` - File reading
* `write` - File writing
**Pattern Examples**:
```json theme={null}
{
"permissions": {
"allow": [
{ "type": "exec", "pattern": "npm" },
{ "type": "exec", "pattern": "git *" },
{ "type": "read", "pattern": "**/*.js" },
{ "type": "write", "pattern": "src/**" }
],
"deny": [
{ "type": "read", "pattern": "**/.env*" },
{ "type": "read", "pattern": "**/secrets/**" },
{ "type": "exec", "pattern": "rm -rf" }
]
}
}
```
### Hooks
Automation hooks triggered at specific lifecycle events
**Hook Types**:
* `PreToolUse` - Before tool execution
* `PostToolUse` - After tool execution
* `Stop` - On session stop
* `Notification` - For notifications
**Example**:
```json theme={null}
{
"hooks": {
"PreToolUse": [
{
"command": "npm run lint",
"description": "Lint before changes"
},
{
"command": "npm test",
"description": "Run tests"
}
],
"PostToolUse": [
{
"command": "git add .",
"description": "Stage changes"
}
],
"Stop": [
{
"command": "echo 'Session ended'",
"description": "Log session end"
}
]
}
}
```
### Environment Variables
Environment variables available to Claude Code
**Example**:
```json theme={null}
{
"env": {
"NODE_ENV": "development",
"DEBUG": "true",
"API_URL": "http://localhost:3000"
}
}
```
**Warning**: Never put sensitive keys in project settings (use `.claude/settings.local.json` instead).
### Telemetry
Enable or disable usage telemetry
**Default**: `true`
**Example**:
```json theme={null}
{
"telemetryEnabled": false
}
```
### Cleanup Period
Number of days to retain conversation history
**Default**: `30`
**Options**:
* `7` - One week
* `30` - One month (default)
* `90` - Three months
* `365` - One year
* `-1` - Never delete
**Example**:
```json theme={null}
{
"cleanupPeriodDays": 7
}
```
### MCP Configuration
Auto-approve all MCP servers from .mcp.json
**Default**: `false`
**Example**:
```json theme={null}
{
"enableAllProjectMcpServers": true,
"enabledMcpjsonServers": [
"github",
"web-fetch",
"filesystem"
],
"disabledMcpjsonServers": [
"memory"
]
}
```
### Statusline
Configure statusline display
**Example**:
```json theme={null}
{
"statusline": {
"command": "python3",
"args": [".claude/scripts/context-monitor.py"],
"refreshInterval": 5000
}
}
```
## .mcp.json
MCP (Model Context Protocol) server configurations.
**Location**: Project root (`.mcp.json`)
**Structure**:
```json theme={null}
{
"mcpServers": {
"server-name": {
"command": "executable",
"args": ["arg1", "arg2"],
"env": {
"VAR_NAME": "value"
}
}
}
}
```
### Complete Example
```json theme={null}
{
"mcpServers": {
"fetch": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-fetch"]
},
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "."],
"env": {
"ALLOWED_DIRECTORIES": "."
}
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
},
"memory": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-memory"]
}
}
}
```
### Server Configuration Fields
Executable command to start the server
Command-line arguments (optional)
Environment variables for the server (optional)
## .claude.json
Authentication configuration.
**Location**: `~/.claude.json`
**Structure**:
```json theme={null}
{
"oauthAccount": {
"accountUuid": "uuid-here",
"emailAddress": "user@example.com",
"refreshToken": "encrypted-token"
},
"apiKey": "sk-ant-xxx"
}
```
**Warning**: Contains sensitive authentication data. Never commit to git.
## CLAUDE.md
Project context and guidelines.
**Location**: `.claude/CLAUDE.md`
**Purpose**:
* Project overview
* Coding standards
* Architecture notes
* Development guidelines
* Important context for Claude
**Example**:
```markdown theme={null}
# Project Name
Brief project description.
## Architecture
Key architectural decisions and patterns.
## Code Standards
- Follow ESLint rules
- Write tests for new features
- Update documentation
## Important Files
- `src/index.js` - Main entry point
- `config/` - Configuration files
## Commands
- `npm test` - Run tests
- `npm run build` - Build for production
```
## Gitignore Recommendations
Add to `.gitignore`:
```gitignore theme={null}
# Claude Code local settings
.claude/settings.local.json
# Claude authentication (never commit!)
.claude.json
# Conversation history (optional, team preference)
.claude/conversations/
# Scripts cache
.claude/scripts/*.pyc
```
**Commit to git**:
* `.claude/CLAUDE.md`
* `.claude/settings.json`
* `.claude/agents/`
* `.claude/commands/`
* `.mcp.json`
## Configuration Presets
Install pre-configured settings:
### Security-Focused
```bash theme={null}
cct --setting security/read-only-mode
cct --setting permissions/deny-sensitive-files
cct --setting security/strict-permissions
```
### Performance-Optimized
```bash theme={null}
cct --setting model/use-haiku
cct --setting retention/retention-7-days
cct --setting telemetry/disable-telemetry
```
### Development-Friendly
```bash theme={null}
cct --setting permissions/allow-npm-commands
cct --setting model/use-sonnet
cct --setting retention/retention-30-days
```
## Best Practices
### 1. Separate Concerns
* **User settings**: Personal preferences, global permissions
* **Project settings**: Team standards, project permissions
* **Local settings**: Developer-specific overrides, API keys
### 2. Security
* Never commit API keys or secrets
* Use environment variables for sensitive data
* Add `.claude/settings.local.json` to `.gitignore`
* Review permissions regularly
### 3. Team Collaboration
* Commit `.claude/settings.json` for team consistency
* Document required settings in README
* Use environment variables for deployment-specific config
* Share MCP configurations in `.mcp.json`
### 4. Performance
* Set appropriate `cleanupPeriodDays` for conversation retention
* Use Haiku model for simple tasks
* Limit `additionalDirectories` to necessary paths
* Monitor conversation history size
### 5. Documentation
* Keep `CLAUDE.md` up to date with project changes
* Document custom agents and commands
* Explain hook purposes
* Note required environment variables
## Troubleshooting
### Settings Not Applied
**Check file locations**:
```bash theme={null}
ls -la ~/.claude/settings.json
ls -la .claude/settings.json
ls -la .claude/settings.local.json
```
**Verify JSON syntax**:
```bash theme={null}
jsonlint ~/.claude/settings.json
jsonlint .claude/settings.json
```
**Check permissions**:
```bash theme={null}
chmod 644 .claude/settings.json
```
### Hooks Not Running
**Verify hook configuration**:
```bash theme={null}
cat .claude/settings.json | jq '.hooks'
```
**Test command manually**:
```bash theme={null}
npm run lint # Test if command works
```
**Check command availability**:
```bash theme={null}
which npm
which git
```
### MCP Servers Not Working
**Verify .mcp.json**:
```bash theme={null}
cat .mcp.json | jq '.mcpServers'
```
**Test server manually**:
```bash theme={null}
npx -y @modelcontextprotocol/server-fetch
```
**Check server permissions**:
```bash theme={null}
# In .claude/settings.json
{
"enabledMcpjsonServers": ["server-name"]
}
```
## Next Steps
* [CLI Flags Reference](/cli/flags) - All CLI flags
* [Environment Variables](/cli/environment-variables) - Environment configuration
* [Install Components](/cli/install-component) - Component installation
* [Health Check](/cli/health-check) - Verify configuration
# Create Global Agents
Source: https://davila7-claude-code-templates-86.mintlify.app/cli/create-agent
Create globally accessible AI agents that can be executed from anywhere
# Create Global Agents
Global agents are AI assistants that can be executed from any directory on your system, like command-line tools. They provide instant access to specialized AI capabilities without navigating to specific projects.
## Overview
Global agents are:
* **Accessible anywhere** - Run from any directory
* **Self-contained** - Include their own system prompts
* **Context-aware** - Auto-detect project types
* **Shell-integrated** - Work in scripts, npm tasks, CI/CD
## Creating a Global Agent
### Basic Creation
Create a global agent from any available agent:
```bash theme={null}
cct --create-agent
```
### Examples
```bash theme={null}
# Create a customer support agent
cct --create-agent customer-support
# Create from a category
cct --create-agent development-team/frontend-developer
# Create a security auditor
cct --create-agent security-auditor
```
### Installation Locations
Global agents install to:
**System Directory** (preferred, immediately available):
```
/usr/local/bin/
```
**User Directory** (fallback, requires PATH setup):
```
~/.claude-code-templates/bin/
```
Agent files are stored at:
```
~/.claude-code-templates/agents/.md
```
## Using Global Agents
### Basic Usage
Once created, invoke global agents from anywhere:
```bash theme={null}
"your prompt here"
```
### Examples
```bash theme={null}
# Customer support queries
customer-support "How do I handle refund requests?"
# Security analysis
security-auditor "Review this authentication code for vulnerabilities"
# Frontend development
frontend-developer "Optimize this React component for performance"
# Documentation
technical-writer "Create API documentation for this endpoint"
```
### Context Auto-Detection
Global agents automatically detect your project context:
```bash theme={null}
cd ~/projects/my-react-app
frontend-developer "Review this component"
# Auto-detects: React project, analyzes relevant files
cd ~/projects/my-api
backend-developer "Optimize database queries"
# Auto-detects: Node.js/Python project, focuses on API files
```
### Project Type Detection
Agents detect project types based on:
| Indicator | Project Type |
| -------------------------------------- | ------------------ |
| `package.json` with React | React |
| `package.json` with Vue | Vue |
| `package.json` with Next.js | Next.js |
| `package.json` (generic) | JavaScript/Node.js |
| `requirements.txt` or `pyproject.toml` | Python |
| `Cargo.toml` | Rust |
| `go.mod` | Go |
### Relevant Files Auto-Selection
Based on project type, agents focus on:
**JavaScript/React/Vue/Next.js**:
* `src/`
* `lib/`
* `components/`
* `pages/`
* `api/`
* `routes/`
**Python**:
* `*.py`
* `src/`
* `app/`
* `api/`
**Rust**:
* `src/`
* `Cargo.toml`
**Go**:
* `*.go`
* `cmd/`
* `internal/`
* `pkg/`
## Advanced Usage
### Explicit File Selection
Specify files or directories explicitly:
```bash theme={null}
--file "your prompt"
--dir "your prompt"
```
### Examples
```bash theme={null}
# Analyze a specific file
security-auditor --file auth.js "Check for vulnerabilities"
# Review a directory
frontend-developer --dir components/ "Optimize these components"
# Multiple files
backend-developer --file routes.js --file controllers.js "Review routing logic"
```
### Disable Auto-Detection
Disable project context auto-detection:
```bash theme={null}
--no-auto "your prompt"
```
Useful for general questions without project context:
```bash theme={null}
customer-support --no-auto "What are best practices for email support?"
```
### Verbose Mode
Enable detailed debugging output:
```bash theme={null}
--verbose "your prompt"
-v "your prompt"
```
Shows:
* User input
* Project context detection
* Final prompt length
* System prompt preview
* Claude command being executed
### Help Command
View agent-specific help:
```bash theme={null}
--help
-h
```
Displays:
* Usage syntax
* Context options
* Examples
## Global Agent Options
The prompt to send to the agent
Include specific file in context (can be used multiple times)
Include specific directory in context (can be used multiple times)
Disable automatic project context detection
Enable verbose debugging output (alias: -v)
Display help information (alias: -h)
## Managing Global Agents
### List Installed Agents
View all installed global agents:
```bash theme={null}
cct --list-agents
```
Output includes:
* Agent name
* Installation location (system/user)
* Executable status
* Creation date
* Usage examples
### Update an Agent
Update to the latest version:
```bash theme={null}
cct --update-agent
```
This re-downloads the agent from GitHub and updates the executable.
### Remove an Agent
Delete a global agent:
```bash theme={null}
cct --remove-agent
```
Removes:
* Executable script from `/usr/local/bin/` or user bin
* Agent file from `~/.claude-code-templates/agents/`
## PATH Configuration
### System Installation
If installed to `/usr/local/bin/`, agents are immediately available with no setup required.
### User Installation
If installed to `~/.claude-code-templates/bin/`, add to PATH:
**Bash** (`~/.bashrc` or `~/.bash_profile`):
```bash theme={null}
export PATH="$HOME/.claude-code-templates/bin:$PATH"
```
**Zsh** (`~/.zshrc`):
```bash theme={null}
export PATH="$HOME/.claude-code-templates/bin:$PATH"
```
**Fish** (`~/.config/fish/config.fish`):
```fish theme={null}
set -gx PATH $HOME/.claude-code-templates/bin $PATH
```
### Apply Changes
Reload your shell configuration:
```bash theme={null}
# Bash
source ~/.bashrc
# Zsh
source ~/.zshrc
# Fish
source ~/.config/fish/config.fish
```
Or restart your terminal.
### Verify PATH
Check if PATH is configured correctly:
```bash theme={null}
echo $PATH | grep claude-code-templates
```
## Use Cases
### 1. Customer Support
```bash theme={null}
# Create agent
cct --create-agent customer-support
# Use from anywhere
customer-support "How to handle billing disputes?"
customer-support "Best practices for escalation?"
```
### 2. Code Review Automation
```bash theme={null}
# Create security auditor
cct --create-agent security-auditor
# Review code before commits
cd ~/projects/my-app
security-auditor --file auth.js "Check for security issues"
```
### 3. Documentation Generation
```bash theme={null}
# Create technical writer
cct --create-agent technical-writer
# Generate docs
technical-writer --file api.js "Create API documentation"
```
### 4. npm Scripts Integration
Add to `package.json`:
```json theme={null}
{
"scripts": {
"review": "security-auditor --file $FILE 'Security review'",
"docs": "technical-writer --dir src/ 'Generate documentation'"
}
}
```
Run with:
```bash theme={null}
FILE=auth.js npm run review
npm run docs
```
### 5. CI/CD Integration
**GitHub Actions** (`.github/workflows/review.yml`):
```yaml theme={null}
name: Code Review
on: [pull_request]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: '18'
- name: Install CLI
run: npm install -g claude-code-templates
- name: Create Agent
run: cct --create-agent security-auditor
- name: Run Review
run: security-auditor --dir src/ "Security review"
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
```
### 6. Shell Aliases
Create convenient aliases:
```bash theme={null}
# Add to ~/.bashrc or ~/.zshrc
alias review='security-auditor'
alias docs='technical-writer'
alias optimize='frontend-developer'
# Usage
review --file auth.js "Check security"
docs --dir api/ "Generate docs"
optimize --file Component.jsx "Improve performance"
```
## Technical Details
### Executable Script Structure
Global agents are Node.js executable scripts that:
1. **Read agent system prompt** from `~/.claude-code-templates/agents/.md`
2. **Parse command-line arguments** (prompt, files, options)
3. **Detect project context** automatically
4. **Build final prompt** combining user input and context
5. **Execute Claude CLI** with agent's system prompt
6. **Stream response** to terminal
### Claude CLI Requirements
Global agents require Claude CLI:
```bash theme={null}
# Check if Claude CLI is installed
claude --version
# Install if needed
npm install -g @anthropic-ai/claude-code
```
### Authentication
Global agents use your existing Claude authentication:
* OAuth authentication from Claude Desktop
* `ANTHROPIC_API_KEY` environment variable
* API key in `~/.claude.json`
### System Prompt Handling
Agents use the `--system-prompt` flag to provide their specialized instructions:
```bash theme={null}
claude -p "user prompt" --system-prompt "agent system prompt"
```
This ensures the agent's expertise is applied to every request.
## Troubleshooting
### Agent Not Found After Creation
**Check PATH configuration:**
```bash theme={null}
echo $PATH | grep claude-code-templates
```
**Try full path:**
```bash theme={null}
~/.claude-code-templates/bin/ "test"
```
**Verify executable permissions:**
```bash theme={null}
ls -l ~/.claude-code-templates/bin/
# Should show: -rwxr-xr-x
```
### Claude CLI Not Found
**Install Claude CLI:**
```bash theme={null}
npm install -g @anthropic-ai/claude-code
```
**Verify installation:**
```bash theme={null}
which claude
claude --version
```
### Permission Denied (macOS/Linux)
**Make executable:**
```bash theme={null}
chmod +x ~/.claude-code-templates/bin/
```
**For system directory:**
```bash theme={null}
sudo chmod +x /usr/local/bin/
```
### Authentication Errors
**Check Claude authentication:**
```bash theme={null}
claude --version # Should work without errors
```
**Set API key if needed:**
```bash theme={null}
export ANTHROPIC_API_KEY=sk-ant-xxx
```
**Or configure in `~/.claude.json`:**
```json theme={null}
{
"apiKey": "sk-ant-xxx"
}
```
### Windows Issues
**Use PowerShell or Command Prompt:**
```powershell theme={null}
# PowerShell
$env:PATH += ";$HOME\.claude-code-templates\bin"
# Command Prompt
set PATH=%PATH%;%USERPROFILE%\.claude-code-templates\bin
```
**Or add to System Environment Variables:**
1. Open System Properties > Environment Variables
2. Add `%USERPROFILE%\.claude-code-templates\bin` to PATH
## Best Practices
1. **Use descriptive names**: `customer-support`, not `cs`
2. **Create specialized agents**: Focus on specific tasks
3. **Test with `--verbose`**: Understand how agents work
4. **Document for teams**: Share agent names and purposes
5. **Use in scripts**: Automate repetitive tasks
6. **Update regularly**: Keep agents current with `--update-agent`
7. **Leverage context**: Let agents auto-detect project types
8. **Combine with hooks**: Integrate into development workflow
## Next Steps
* [List and Manage Agents](/cli/list-agents) - Manage installed global agents
* [Install Components](/cli/install-component) - Install project-specific agents
* [CLI Flags Reference](/cli/flags) - Complete flags documentation
* [Environment Variables](/cli/environment-variables) - Configure authentication
# Environment Variables
Source: https://davila7-claude-code-templates-86.mintlify.app/cli/environment-variables
Environment variables for Claude Code Templates CLI configuration
# Environment Variables
Configure the Claude Code Templates CLI and Claude Code using environment variables for authentication, API keys, and runtime settings.
## Authentication Variables
### ANTHROPIC\_API\_KEY
Anthropic API key for Claude Code authentication
**Usage**:
```bash theme={null}
export ANTHROPIC_API_KEY=sk-ant-xxx
```
**Purpose**:
* Authenticate Claude Code CLI
* Enable API-based authentication
* Alternative to OAuth authentication
**Obtain Key**:
1. Visit [https://console.anthropic.com/](https://console.anthropic.com/)
2. Navigate to API Keys section
3. Create new API key
4. Copy and set as environment variable
**Priority**: Environment variable takes precedence over `~/.claude.json` API key.
**Security**:
* Never commit to git
* Use `.env` files with `.gitignore`
* Rotate keys regularly
* Use different keys for dev/prod
**Example `.env` file**:
```bash theme={null}
# .env
ANTHROPIC_API_KEY=sk-ant-api03-xxx
```
**Load in shell**:
```bash theme={null}
# Bash/Zsh
export $(cat .env | xargs)
# Or use dotenv
source .env
```
### ANTHROPIC\_AUTH\_TOKEN
Alternative authentication token (if using OAuth)
**Usage**:
```bash theme={null}
export ANTHROPIC_AUTH_TOKEN=your-token
```
**Purpose**: Alternative authentication method for enterprise setups.
## Sandbox Variables
### E2B\_API\_KEY
E2B API key for sandbox execution
**Usage**:
```bash theme={null}
export E2B_API_KEY=e2b_xxx
```
**Purpose**:
* Enable E2B sandbox execution
* Required for `--sandbox e2b` flag
**Obtain Key**:
1. Visit [https://e2b.dev/](https://e2b.dev/)
2. Sign up for account
3. Create API key
4. Set as environment variable
**Example**:
```bash theme={null}
export E2B_API_KEY=e2b_xxx
cct --sandbox e2b --prompt "Create a React app"
```
**Alternative**: Use `--e2b-api-key` flag:
```bash theme={null}
cct --sandbox e2b --e2b-api-key e2b_xxx --prompt "Create app"
```
### CLOUDFLARE\_TUNNEL\_TOKEN
Cloudflare Tunnel token for remote access (optional)
**Usage**:
```bash theme={null}
export CLOUDFLARE_TUNNEL_TOKEN=your-token
```
**Purpose**:
* Use custom Cloudflare Tunnel
* Persistent tunnel URLs
* Team access to dashboards
**Obtain Token**:
1. Create Cloudflare account
2. Install `cloudflared`
3. Create tunnel: `cloudflared tunnel create my-tunnel`
4. Get token from tunnel config
**Note**: The CLI uses temporary tunnels by default. This is only needed for persistent URLs.
## Runtime Configuration
### PORT
Port for analytics dashboard and web interfaces
**Usage**:
```bash theme={null}
export PORT=8080
cct --analytics
```
**Default**: `3333`
**Purpose**:
* Change default port if 3333 is in use
* Run multiple dashboards simultaneously
**Example**:
```bash theme={null}
# Terminal 1
PORT=3333 cct --analytics
# Terminal 2
PORT=4444 cct --chats
```
### NODE\_ENV
Node.js environment (development, production, test)
**Usage**:
```bash theme={null}
export NODE_ENV=development
```
**Values**:
* `development` - Development mode (verbose logging)
* `production` - Production mode (minimal logging)
* `test` - Testing mode
**Purpose**:
* Control logging verbosity
* Enable debug features
* Configure behavior
### DEBUG
Enable debug logging for specific modules
**Usage**:
```bash theme={null}
export DEBUG=*
export DEBUG=claude:*
export DEBUG=analytics:*
```
**Purpose**:
* Detailed debugging output
* Module-specific logs
* Troubleshooting
**Examples**:
```bash theme={null}
# All debug output
DEBUG=* cct --analytics
# Specific module
DEBUG=claude:* cct --agent frontend-developer
```
### CCT\_DEBUG
Enable Claude Code Templates debug logging
**Usage**:
```bash theme={null}
export CCT_DEBUG=true
```
**Purpose**:
* Show tracking debug messages
* Display non-critical errors
* Troubleshoot analytics issues
**Example**:
```bash theme={null}
CCT_DEBUG=true npx claude-code-templates --agent frontend-developer
```
### CCT\_NO\_TRACKING
Disable usage tracking and analytics
**Usage**:
```bash theme={null}
export CCT_NO_TRACKING=true
```
**Purpose**:
* Opt out of anonymous usage analytics
* Disable component download tracking
* Privacy-focused installations
**Example**:
```bash theme={null}
CCT_NO_TRACKING=true npx claude-code-templates --agent security-auditor
```
### CCT\_NO\_ANALYTICS
Alias for CCT\_NO\_TRACKING (disables analytics)
**Usage**:
```bash theme={null}
export CCT_NO_ANALYTICS=true
```
**Purpose**:
* Same as CCT\_NO\_TRACKING
* Alternative environment variable name
* Disables all telemetry
**Note**: Setting either `CCT_NO_TRACKING` or `CCT_NO_ANALYTICS` to `true` will disable tracking.
## Shell Configuration
### PATH
System PATH for global agent executables
**Usage**:
```bash theme={null}
export PATH="$HOME/.claude-code-templates/bin:$PATH"
```
**Purpose**:
* Make global agents accessible
* Enable command-line execution
* Required for user-directory installations
**Add to Shell Config**:
**Bash** (`~/.bashrc` or `~/.bash_profile`):
```bash theme={null}
# Claude Code Templates - Global Agents
export PATH="$HOME/.claude-code-templates/bin:$PATH"
```
**Zsh** (`~/.zshrc`):
```bash theme={null}
# Claude Code Templates - Global Agents
export PATH="$HOME/.claude-code-templates/bin:$PATH"
```
**Fish** (`~/.config/fish/config.fish`):
```fish theme={null}
# Claude Code Templates - Global Agents
set -gx PATH $HOME/.claude-code-templates/bin $PATH
```
**Apply Changes**:
```bash theme={null}
source ~/.bashrc # Or ~/.zshrc, ~/.config/fish/config.fish
```
### SHELL
Current shell (automatically set by system)
**Values**:
* `/bin/bash`
* `/bin/zsh`
* `/usr/bin/fish`
**Purpose**:
* Detect shell for PATH configuration
* Shell-specific features
* Autocompletion setup
### CI
Continuous Integration environment indicator
**Values**:
* `true` - Running in CI environment
* Unset - Local development
**Purpose**:
* Automatically disables tracking in CI/CD
* Prevents analytics in automated environments
* Skips interactive prompts
**Set by**: GitHub Actions, GitLab CI, CircleCI, Jenkins, and other CI platforms automatically set this variable.
**Manual Override**:
```bash theme={null}
# Force CI mode locally
CI=true npx claude-code-templates --agent frontend-developer
```
## Project-Specific Variables
These can be set in `.claude/settings.json` under the `env` field:
```json theme={null}
{
"env": {
"NODE_ENV": "development",
"DEBUG": "true",
"API_URL": "http://localhost:3000",
"DATABASE_URL": "${DATABASE_URL}"
}
}
```
**Variable Expansion**: Use `${VAR_NAME}` to reference system environment variables.
## Environment Variable Precedence
When multiple sources define the same variable:
1. **Command-line flags** (highest priority)
2. **Environment variables**
3. **Local settings** (`.claude/settings.local.json`)
4. **Project settings** (`.claude/settings.json`)
5. **User settings** (`~/.claude/settings.json`) (lowest priority)
**Example**:
```bash theme={null}
# Environment variable
export ANTHROPIC_API_KEY=sk-ant-111
# CLI flag (takes precedence)
cct --anthropic-api-key sk-ant-222 --prompt "test"
# Uses sk-ant-222
```
## .env Files
### Project .env
Store environment variables in `.env` file:
```bash theme={null}
# .env
ANTHROPIC_API_KEY=sk-ant-xxx
E2B_API_KEY=e2b_xxx
GITHUB_TOKEN=ghp_xxx
DATABASE_URL=postgresql://localhost/mydb
API_URL=http://localhost:3000
```
**Load with dotenv**:
```bash theme={null}
# Install dotenv-cli
npm install -g dotenv-cli
# Run with .env
dotenv cct --analytics
```
**Load in shell**:
```bash theme={null}
export $(cat .env | grep -v '^#' | xargs)
```
### .env.example
Create template for team:
```bash theme={null}
# .env.example
ANTHROPIC_API_KEY=sk-ant-your-key-here
E2B_API_KEY=e2b_your-key-here
GITHUB_TOKEN=ghp_your-token-here
DATABASE_URL=postgresql://user:pass@localhost/dbname
```
**Usage**:
```bash theme={null}
# Team member copies and fills in
cp .env.example .env
vim .env # Add real values
```
### Gitignore
Always exclude `.env` from git:
```gitignore theme={null}
# .gitignore
.env
.env.local
.env.*.local
.claude.json
.claude/settings.local.json
```
## CI/CD Configuration
### GitHub Actions
Set secrets in repository settings:
```yaml theme={null}
# .github/workflows/claude.yml
name: Claude Code
on: [push, pull_request]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: '18'
- name: Install CLI
run: npm install -g claude-code-templates
- name: Run Health Check
run: cct --health-check
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
```
**Set Secrets**:
1. Go to repository Settings > Secrets and variables > Actions
2. Add `ANTHROPIC_API_KEY` secret
3. Reference with `${{ secrets.ANTHROPIC_API_KEY }}`
### GitLab CI
```yaml theme={null}
# .gitlab-ci.yml
review:
image: node:18
script:
- npm install -g claude-code-templates
- cct --health-check
variables:
ANTHROPIC_API_KEY: $ANTHROPIC_API_KEY
```
**Set Variables**:
1. Go to Settings > CI/CD > Variables
2. Add `ANTHROPIC_API_KEY` (protected, masked)
## Docker Configuration
### Dockerfile
```dockerfile theme={null}
FROM node:18
WORKDIR /app
RUN npm install -g claude-code-templates
COPY . .
ENV NODE_ENV=production
CMD ["cct", "--analytics"]
```
### docker-compose.yml
```yaml theme={null}
version: '3.8'
services:
claude-analytics:
build: .
ports:
- "3333:3333"
environment:
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
- NODE_ENV=production
- PORT=3333
env_file:
- .env
```
**Run**:
```bash theme={null}
docker-compose up
```
## Security Best Practices
### 1. Never Commit Secrets
```bash theme={null}
# Check for secrets before commit
git diff | grep -i "api.key\|secret\|token\|password"
# Use git-secrets
git secrets --install
git secrets --register-aws
```
### 2. Use Separate Keys
* **Development**: Personal API key
* **Staging**: Team staging key
* **Production**: Production key (rotate regularly)
### 3. Restrict Permissions
```bash theme={null}
# Secure .env file
chmod 600 .env
# Verify
ls -la .env
# -rw------- (only owner can read/write)
```
### 4. Rotate Keys Regularly
```bash theme={null}
# Monthly rotation schedule
# 1. Generate new key
# 2. Update environment variables
# 3. Test applications
# 4. Revoke old key
```
### 5. Use Key Management Systems
**AWS Secrets Manager**:
```bash theme={null}
# Fetch secret
export ANTHROPIC_API_KEY=$(aws secretsmanager get-secret-value \
--secret-id anthropic-api-key \
--query SecretString \
--output text)
```
**HashiCorp Vault**:
```bash theme={null}
# Read secret
export ANTHROPIC_API_KEY=$(vault kv get -field=api_key secret/claude)
```
## Troubleshooting
### Variables Not Loading
**Check if variable is set**:
```bash theme={null}
echo $ANTHROPIC_API_KEY
env | grep ANTHROPIC
```
**Source shell config**:
```bash theme={null}
source ~/.bashrc # or ~/.zshrc
```
**Verify .env file**:
```bash theme={null}
cat .env | grep ANTHROPIC_API_KEY
```
### Authentication Fails
**Test API key**:
```bash theme={null}
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Hello"}]
}'
```
**Check key format**:
* Should start with `sk-ant-`
* No whitespace or special characters
* Not expired
### PATH Not Working
**Verify PATH includes bin directory**:
```bash theme={null}
echo $PATH | grep claude-code-templates
```
**Add to PATH manually**:
```bash theme={null}
export PATH="$HOME/.claude-code-templates/bin:$PATH"
```
**Check executable exists**:
```bash theme={null}
ls -la ~/.claude-code-templates/bin/
```
### Permission Denied
**Fix file permissions**:
```bash theme={null}
chmod 600 .env
chmod 755 ~/.claude-code-templates/bin/*
```
## Next Steps
* [CLI Flags Reference](/cli/flags) - All CLI flags
* [Configuration Guide](/cli/configuration) - Settings files
* [Health Check](/cli/health-check) - Verify configuration
* [CLI Overview](/cli/overview) - Complete CLI documentation
# CLI Flags Reference
Source: https://davila7-claude-code-templates-86.mintlify.app/cli/flags
Complete reference for all Claude Code Templates CLI flags and options
# CLI Flags Reference
Complete documentation of all command-line flags and options for the Claude Code Templates CLI.
## Component Installation Flags
### --agent
Install specific agent component (supports comma-separated values)
**Usage**:
```bash theme={null}
cct --agent
cct --agent frontend-developer
cct --agent development-team/frontend-developer
cct --agent security-auditor,devops-engineer
```
**Format**: Direct name or category/name
**Examples**:
* `frontend-developer`
* `development-team/react-specialist`
* `security-team/penetration-tester`
### --command
Install specific command component (supports comma-separated values)
**Usage**:
```bash theme={null}
cct --command
cct --command setup-testing
cct --command testing/generate-tests,code-review
```
**Format**: Direct name or category/name
### --mcp
Install specific MCP component (supports comma-separated values)
**Usage**:
```bash theme={null}
cct --mcp
cct --mcp web-fetch
cct --mcp github-integration,filesystem-access
```
**Available MCPs**:
* `web-fetch`
* `filesystem-access`
* `github-integration`
* `memory-integration`
* `mysql-integration`
* `postgresql-integration`
* `deepgraph-react`
* `deepgraph-typescript`
* `deepgraph-vue`
* `deepgraph-nextjs`
### --setting
Install specific setting component (supports comma-separated values)
**Usage**:
```bash theme={null}
cct --setting
cct --setting permissions/allow-npm-commands
cct --setting model/use-sonnet,telemetry/disable-telemetry
```
**Categories**:
* `permissions/` - Permission configurations
* `model/` - Model selection settings
* `telemetry/` - Telemetry controls
* `retention/` - Data retention policies
* `security/` - Security settings
* `statusline/` - Statusline configurations
### --hook
Install specific hook component (supports comma-separated values)
**Usage**:
```bash theme={null}
cct --hook
cct --hook automation/git-commit-validation
cct --hook automation/simple-notifications,automation/run-tests
```
**Hook Types**:
* PreToolUse hooks
* PostToolUse hooks
* Stop hooks
* Notification hooks
### --skill
Install specific skill component (supports comma-separated values)
**Usage**:
```bash theme={null}
cct --skill
cct --skill web-development/roier-seo
cct --skill document-processing/pptx
```
## Template and Configuration Flags
### --template
Specify template (e.g., common, javascript-typescript, python, ruby)
**Usage**:
```bash theme={null}
cct --template
cct --template javascript-typescript
cct --template python
```
**Available Templates**:
* `common` - Universal configuration
* `javascript-typescript` - Node.js, React, Vue, Next.js
* `python` - Django, Flask, FastAPI
* `ruby` - Rails, Sinatra
* `go` - Go projects
* `rust` - Rust/Cargo projects
### --language
Specify programming language (deprecated, use --template)
**Usage**:
```bash theme={null}
cct --language
cct --language javascript
```
**Deprecated**: Use `--template` instead.
### --framework
Specify framework (deprecated, use --template)
**Usage**:
```bash theme={null}
cct --framework
cct --framework react
```
**Deprecated**: Use `--template` instead.
### --directory
Target directory (default: current directory)
**Usage**:
```bash theme={null}
cct --directory
cct --directory ./my-project
cct -d ./my-project # Short alias
```
**Alias**: `-d`
## Execution Flags
### --yes
Skip prompts and use defaults
**Usage**:
```bash theme={null}
cct --yes
cct -y # Short alias
```
**Behavior**: Uses detected project type and default options.
**Alias**: `-y`
### --dry-run
Show what would be copied without actually copying
**Usage**:
```bash theme={null}
cct --dry-run
cct --agent frontend-developer --dry-run
```
**Behavior**: Displays files that would be created/modified without making changes.
### --verbose
Enable verbose logging for debugging and development
**Usage**:
```bash theme={null}
cct --verbose
cct --analytics --verbose
```
**Behavior**: Outputs detailed debugging information.
## Analytics and Dashboard Flags
### --analytics
Launch real-time Claude Code analytics dashboard
**Usage**:
```bash theme={null}
cct --analytics
cct --analytics --tunnel
```
**Port**: `3333`
**URL**: `http://localhost:3333`
### --chats
Launch mobile-first chats interface (AI-optimized for mobile devices)
**Usage**:
```bash theme={null}
cct --chats
cct --chats --tunnel
```
### --agents
Launch Claude Code agents dashboard (opens directly to conversations)
**Usage**:
```bash theme={null}
cct --agents
cct --agents --tunnel
```
### --chats-mobile
Launch mobile-first chats interface (same as --chats)
**Usage**:
```bash theme={null}
cct --chats-mobile
```
### --plugins
Launch Plugin Dashboard to view marketplaces, installed plugins, and permissions
**Usage**:
```bash theme={null}
cct --plugins
```
### --skills-manager
Launch Skills Dashboard to view and explore installed Claude Code Skills
**Usage**:
```bash theme={null}
cct --skills-manager
```
### --teams
Launch Agent Teams Dashboard to review multi-agent collaboration sessions
**Usage**:
```bash theme={null}
cct --teams
```
### --2025
Launch 2025 Year in Review dashboard (showcase your Claude Code usage statistics)
**Usage**:
```bash theme={null}
cct --2025
cct --2025 --tunnel
```
### --tunnel
Enable Cloudflare Tunnel for remote access (use with --analytics, --chats, or --2025)
**Usage**:
```bash theme={null}
cct --analytics --tunnel
cct --chats --tunnel
cct --2025 --tunnel
```
**Behavior**: Creates public URL for remote access.
**Restriction**: Only works with dashboard flags.
## Statistics and Analysis Flags
### --command-stats
Analyze existing Claude Code commands and offer optimization
**Usage**:
```bash theme={null}
cct --command-stats
cct --commands-stats # Alternative spelling
```
**Alias**: `--commands-stats`
### --hook-stats
Analyze existing automation hooks and offer optimization
**Usage**:
```bash theme={null}
cct --hook-stats
cct --hooks-stats # Alternative spelling
```
**Alias**: `--hooks-stats`
### --mcp-stats
Analyze existing MCP server configurations and offer optimization
**Usage**:
```bash theme={null}
cct --mcp-stats
cct --mcps-stats # Alternative spelling
```
**Alias**: `--mcps-stats`
## Health and Verification Flags
### --health-check
Run comprehensive health check to verify Claude Code setup
**Usage**:
```bash theme={null}
cct --health-check
cct --health # Short alias
cct --check # Alternative alias
cct --verify # Another alias
```
**Aliases**: `--health`, `--check`, `--verify`
## Global Agent Flags
### --create-agent
Create a global agent accessible from anywhere (e.g., customer-support)
**Usage**:
```bash theme={null}
cct --create-agent
cct --create-agent customer-support
cct --create-agent development-team/frontend-developer
```
**Installation**: Creates executable in `/usr/local/bin/` or `~/.claude-code-templates/bin/`
### --list-agents
List all installed global agents
**Usage**:
```bash theme={null}
cct --list-agents
```
### --remove-agent
Remove a global agent
**Usage**:
```bash theme={null}
cct --remove-agent
cct --remove-agent customer-support
```
### --update-agent
Update a global agent to the latest version
**Usage**:
```bash theme={null}
cct --update-agent
cct --update-agent customer-support
```
## Sandbox and Execution Flags
### --sandbox
Execute Claude Code in isolated sandbox environment (e.g., e2b)
**Usage**:
```bash theme={null}
cct --sandbox
cct --sandbox e2b --prompt "Create a React app"
```
**Supported Providers**:
* `e2b` - E2B sandbox
* `docker` - Docker containers
* `cloudflare` - Cloudflare Workers
### --prompt
Execute the provided prompt in Claude Code after installation or in sandbox
**Usage**:
```bash theme={null}
cct --prompt "Create a React component"
cct --agent frontend-developer --prompt "Review this code"
cct --sandbox e2b --prompt "Build an API"
```
### --e2b-api-key
E2B API key for sandbox execution (alternative to environment variable)
**Usage**:
```bash theme={null}
cct --sandbox e2b --e2b-api-key YOUR_KEY --prompt "Create app"
```
**Alternative**: Set `E2B_API_KEY` environment variable.
### --anthropic-api-key
Anthropic API key for Claude Code (alternative to environment variable)
**Usage**:
```bash theme={null}
cct --anthropic-api-key sk-ant-xxx --prompt "Create app"
```
**Alternative**: Set `ANTHROPIC_API_KEY` environment variable.
## Workflow Flags
### --workflow
Install workflow from hash (#hash) OR workflow YAML (base64 encoded) when used with component flags
**Usage**:
```bash theme={null}
# Install from hash
cct --workflow #security-audit-workflow
# Install with YAML (base64 encoded)
cct --workflow --agent security-auditor
```
**Behavior**:
* Standalone: Installs workflow from hash
* With components: Treats as YAML workflow definition
## Session Management Flags
### --clone-session
Download and import a shared Claude Code session from URL
**Usage**:
```bash theme={null}
cct --clone-session
cct --clone-session https://example.com/session/abc123
```
**Behavior**: Downloads session data and imports into local Claude Code.
### --studio
Launch Claude Code Studio interface for local and cloud execution
**Usage**:
```bash theme={null}
cct --studio
```
## Version and Help Flags
### --version
Display version information
**Usage**:
```bash theme={null}
cct --version
cct -v # Short alias
```
**Alias**: `-v`
### --help
Display help information
**Usage**:
```bash theme={null}
cct --help
cct -h # Short alias
```
**Alias**: `-h`
## Flag Combinations
### Common Combinations
**Install multiple components**:
```bash theme={null}
cct --agent security-auditor \
--command security-audit \
--mcp github-integration \
--setting read-only-mode
```
**Analytics with remote access**:
```bash theme={null}
cct --analytics --tunnel
cct --chats --tunnel
cct --2025 --tunnel
```
**Install and execute prompt**:
```bash theme={null}
cct --agent frontend-developer --prompt "Review this React component"
```
**Sandbox execution**:
```bash theme={null}
cct --sandbox e2b --e2b-api-key YOUR_KEY --prompt "Create a dashboard"
```
**Dry run installation**:
```bash theme={null}
cct --agent security-auditor --command security-audit --dry-run
```
**Directory-specific installation**:
```bash theme={null}
cct --directory ./project --agent frontend-developer --yes
```
**Verbose debugging**:
```bash theme={null}
cct --analytics --tunnel --verbose
cct --agent security-auditor --verbose
```
### Invalid Combinations
**Tunnel without dashboard**:
```bash theme={null}
# ❌ Error
cct --tunnel
# ✅ Correct
cct --analytics --tunnel
```
**Multiple exclusive flags**:
```bash theme={null}
# ❌ Avoid
cct --analytics --chats # Opens analytics (first wins)
# ✅ Correct
cct --analytics # Or
cct --chats # Run separately
```
## Flag Priority
When multiple flags are present:
1. **Sandbox execution** - Runs first if present
2. **Component installation** - If no sandbox
3. **Dashboard launch** - If no components
4. **Health check** - If specified
5. **Interactive menu** - If no flags
## Environment Variables vs Flags
Some flags have environment variable equivalents:
| Flag | Environment Variable |
| --------------------- | ------------------------- |
| `--anthropic-api-key` | `ANTHROPIC_API_KEY` |
| `--e2b-api-key` | `E2B_API_KEY` |
| `--directory` | `PWD` (current directory) |
Flags take precedence over environment variables.
## Default Values
| Flag | Default Value |
| ------------- | ----------------------------------- |
| `--directory` | `process.cwd()` (current directory) |
| `--template` | Auto-detected or `common` |
| `--yes` | `false` (interactive prompts) |
| `--dry-run` | `false` (execute changes) |
| `--verbose` | `false` (minimal output) |
| `--tunnel` | `false` (local only) |
## Next Steps
* [CLI Overview](/cli/overview) - Complete CLI documentation
* [Configuration Guide](/cli/configuration) - Settings and config files
* [Environment Variables](/cli/environment-variables) - Environment configuration
* [Install Components](/cli/install-component) - Component installation guide
# Health Check
Source: https://davila7-claude-code-templates-86.mintlify.app/cli/health-check
Verify Claude Code setup, configuration, and system requirements
# Health Check
The health check command performs comprehensive verification of your Claude Code installation, configuration, and project setup.
## Run Health Check
### Basic Usage
Run the health check:
```bash theme={null}
cct --health-check
cct --health # Short alias
cct --verify # Alternative alias
cct --check # Another alias
```
### Interactive Flow
The health check:
1. Runs all verification tests
2. Displays results in real-time
3. Generates health score
4. Provides recommendations
5. Optionally launches project setup
## Health Check Categories
The health check verifies seven categories:
### 1. System Requirements
Verifies your development environment:
**Operating System**:
* Platform: macOS, Linux, or Windows
* Version: Compatible release
* Status: ✅ Pass / ❌ Fail
**Node.js Version**:
* Required: Node.js 18+
* Current version check
* Compatibility verification
**Memory Available**:
* Recommended: 4GB+ total memory
* Current memory status
* Free memory available
**Network Connection**:
* Anthropic API connectivity
* Response time check
* Network accessibility
**Shell Environment**:
* Shell type (bash, zsh, fish)
* Autocompletion support
* Compatibility status
### 2. Claude Code Setup
Verifies Claude installation:
**Installation**:
* Claude Code CLI presence
* Version information
* Global/local installation
**Authentication**:
* OAuth account check
* API key verification
* Environment variable check
**Auto-updates**:
* Update settings
* Version currency
**Permissions**:
* Directory permissions
* Write access
* Configuration access
### 3. Project Setup
Verifies project configuration:
**Project Structure**:
* Project indicators (package.json, etc.)
* Directory structure
* Project type detection
**Configuration Files**:
* `.claude/` directory existence
* File count and structure
* Configuration validity
**User Settings**:
* `~/.claude/settings.json`
* Settings structure
* Permission rules
* Environment variables
**Project Settings**:
* `.claude/settings.json`
* Project-specific configuration
* Hook definitions
* MCP server lists
**Local Settings**:
* `.claude/settings.local.json`
* Local overrides
* Developer-specific config
### 4. Agents
Verifies installed agents:
**Project Agents**:
* `.claude/agents/` directory
* Agent file count
* Recursive directory scan
**Personal Agents**:
* `~/.claude/agents/` directory
* Global agent count
* Agent availability
**Agent Syntax**:
* YAML frontmatter validation
* Required fields (name, description)
* Proper markdown structure
### 5. MCP Servers
Verifies MCP configuration:
**Project MCP Config**:
* `.mcp.json` existence
* Server count
* Configuration validity
**MCP Config Syntax**:
* JSON validity
* Required fields (command)
* Args and env format
* Server configuration completeness
### 6. Custom Commands
Verifies slash commands:
**Project Commands**:
* `.claude/commands/` directory
* Command count
* File structure
**Personal Commands**:
* `~/.claude/commands/` directory
* Global command count
**Command Syntax**:
* Markdown structure
* `$ARGUMENTS` placeholder
* Proper formatting
### 7. Hooks Configuration
Verifies automation hooks:
**User Hooks**:
* `~/.claude/settings.json` hooks
* Hook count and types
**Project Hooks**:
* `.claude/settings.json` hooks
* Project-specific automation
**Local Hooks**:
* `.claude/settings.local.json` hooks
* Developer-specific hooks
**Hook Commands**:
* Command executability
* Shell builtin recognition
* Command availability verification
**MCP Hooks**:
* MCP-specific hook validation
* Integration checks
## Health Check Output
### Real-Time Display
As checks run:
```
┌───────────────────────┐
│ SYSTEM REQUIREMENTS │
└───────────────────────┘
✅ Operating System │ macOS 15.0 (compatible)
✅ Node.js Version │ v22.11.0 (compatible)
✅ Memory Available │ 16.0GB total, 8.5GB free (sufficient)
✅ Network Connection │ Connected to Anthropic API
✅ Shell Environment │ zsh (excellent autocompletion support)
┌─────────────────────┐
│ CLAUDE CODE SETUP │
└─────────────────────┘
✅ Installation │ v2.0.0 (globally installed)
✅ Authentication │ Authenticated via OAuth (user@example.com)
✅ Auto-updates │ Auto-updates assumed enabled
✅ Permissions │ Claude directory permissions OK
```
### Health Score
Final summary:
```
📊 Health Score: 28/30 checks passed (93%)
💡 Recommendations:
• Add proper frontmatter (name, description) to agent files
• Create .mcp.json file to configure MCP servers for your project
```
### Status Icons
* ✅ **Pass**: Check passed, no issues
* ⚠️ **Warn**: Check passed with warnings
* ❌ **Fail**: Check failed, needs attention
## Health Check Recommendations
Based on results, the health check suggests:
### System Issues
**Low Memory**:
```
Recommended 4GB+ memory for optimal performance
Consider closing other applications
```
**Network Issues**:
```
Cannot reach Anthropic API
Check your internet connection and firewall settings
```
**Shell Environment**:
```
Consider switching to Zsh for better autocompletion and features
```
### Configuration Issues
**Missing Frontmatter**:
```
Add proper frontmatter (name, description) to agent files
Example:
---
name: My Agent
description: Agent description
---
```
**Missing MCP Config**:
```
Create .mcp.json file to configure MCP servers for your project
Use: cct --mcp web-fetch
```
**Missing Agents Directory**:
```
Create .claude/agents/ directory to organize your custom agents
Use: cct --agent frontend-developer
```
**Invalid JSON**:
```
Fix JSON syntax errors in MCP configuration files
Validate with: jsonlint .mcp.json
```
**Missing Hook Commands**:
```
Add missing command fields to MCP server configurations
Ensure all servers have a 'command' field
```
## After Health Check
### Setup Recommendation
If health score is low (below 80%), the CLI prompts:
```
Would you like to run the Project Setup? (Y/n)
```
Selecting "Yes" launches interactive setup:
```bash theme={null}
cct # Interactive setup
```
### Manual Fixes
For specific issues, fix manually:
```bash theme={null}
# Fix agent syntax
vi .claude/agents/my-agent.md
# Add frontmatter:
# ---
# name: My Agent
# description: Description here
# ---
# Fix MCP config
vi .mcp.json
# Ensure valid JSON structure
# Fix permissions
chmod 755 .claude/
chmod 644 .claude/settings.json
```
## Use Cases
### 1. Initial Setup Verification
```bash theme={null}
# After installing Claude Code
cct --health-check
# Review results
# Fix any issues
# Re-run to verify fixes
```
### 2. Troubleshooting
```bash theme={null}
# When experiencing issues
cct --health-check
# Identify problem areas
# Follow recommendations
```
### 3. Team Onboarding
```bash theme={null}
# New team member setup
cct --health-check
# Ensure all requirements met
# Verify configuration
# Launch setup if needed
```
### 4. Pre-Deployment
```bash theme={null}
# Before deploying to production
cct --health-check
# Verify all configurations
# Ensure no warnings
# Document health score
```
### 5. Regular Maintenance
```bash theme={null}
# Monthly health check
cct --health-check
# Monitor degradation
# Proactive maintenance
```
## Troubleshooting
### Health Check Hangs
**Network timeout**:
* Check internet connection
* Verify Anthropic API access
* Use `Ctrl+C` to cancel
**File system issues**:
* Check `.claude/` permissions
* Verify disk space
* Close other applications
### False Negatives
**Claude CLI not detected**:
```bash theme={null}
# Verify installation
which claude
claude --version
# Reinstall if needed
npm install -g @anthropic-ai/claude-code
```
**Authentication fails**:
```bash theme={null}
# Check authentication
cat ~/.claude.json
# Re-authenticate
claude login
```
### Performance Issues
**Slow health check**:
* Large conversation history
* Many agents/commands
* Network latency
**Solutions**:
```bash theme={null}
# Clear old conversations
cct --setting retention/retention-7-days
# Optimize configuration
# Remove unused agents/commands
```
## Health Check Options
Run comprehensive health check
Short alias for --health-check
Alternative alias for --health-check
Another alias for --health-check
## Best Practices
### Regular Checks
Run health checks:
* After installation
* Before major updates
* Monthly maintenance
* When troubleshooting
* Team onboarding
### Documentation
Document health scores:
```bash theme={null}
# Save health check output
cct --health-check > health-$(date +%Y%m%d).txt
# Track over time
ls -l health-*.txt
```
### Team Standards
Set minimum health score:
```bash theme={null}
# Team policy: 90%+ health score required
cct --health-check
# If score < 90%, fix issues before proceeding
```
### Automation
Automate health checks:
```bash theme={null}
#!/bin/bash
# pre-commit-health-check.sh
HEALTH_OUTPUT=$(cct --health-check)
HEALTH_SCORE=$(echo "$HEALTH_OUTPUT" | grep -oP '\d+(?=%)')
if [ "$HEALTH_SCORE" -lt 90 ]; then
echo "❌ Health score too low: $HEALTH_SCORE%"
echo "Fix issues before committing"
exit 1
fi
echo "✅ Health check passed: $HEALTH_SCORE%"
```
## Advanced Usage
### Custom Health Checks
Extend with custom validations:
```bash theme={null}
#!/bin/bash
# custom-health-check.sh
# Run standard health check
cct --health-check
# Add custom checks
echo "
Custom Checks:"
# Check for specific files
if [ -f "CLAUDE.md" ]; then
echo "✅ CLAUDE.md exists"
else
echo "❌ CLAUDE.md missing"
fi
# Check git repository
if [ -d ".git" ]; then
echo "✅ Git repository initialized"
else
echo "⚠️ No git repository"
fi
```
### Health Check API
Programmatic access:
```javascript theme={null}
const { runHealthCheck } = require('claude-code-templates/src/health-check');
async function checkHealth() {
const results = await runHealthCheck();
console.log('Health Score:', results.healthScore);
console.log('Recommendations:', results.recommendations);
}
checkHealth();
```
## Next Steps
* [CLI Overview](/cli/overview) - Complete CLI documentation
* [Configuration Guide](/cli/configuration) - Settings and config files
* [Analytics Dashboard](/cli/analytics) - Monitor Claude Code usage
* [Environment Variables](/cli/environment-variables) - Configure authentication
# Install Components
Source: https://davila7-claude-code-templates-86.mintlify.app/cli/install-component
Install agents, commands, MCP servers, hooks, settings, and skills
# Install Components
The CLI supports installing six types of components: agents, commands, MCP servers, hooks, settings, and skills. Each component type serves a specific purpose in enhancing your Claude Code workflow.
## Component Installation Syntax
### Basic Installation
Install a single component:
```bash theme={null}
cct --agent
cct --command
cct --mcp
cct --hook
cct --setting
cct --skill
```
### Batch Installation
Install multiple components of the same type (comma-separated):
```bash theme={null}
cct --agent frontend-developer,backend-developer,security-auditor
cct --mcp web-fetch,github-integration,filesystem-access
```
Install different component types together:
```bash theme={null}
cct --agent security-auditor \
--command security-audit \
--mcp github-integration \
--setting read-only-mode
```
## Component Naming Formats
Components support two naming formats:
### Direct Name
```bash theme={null}
cct --agent frontend-developer
cct --command setup-testing
```
### Category/Name Format
```bash theme={null}
cct --agent development-team/frontend-developer
cct --command testing/setup-testing
cct --hook automation/simple-notifications
```
Both formats install to the same flat directory structure.
## Agents
### What are Agents?
Agents are specialized AI assistants with custom system prompts and behaviors. They provide expert guidance for specific tasks like frontend development, security auditing, or documentation writing.
### Installation Location
Agents install to:
```
.claude/agents/.md
```
### Examples
```bash theme={null}
# Frontend development
cct --agent frontend-developer
cct --agent development-team/react-specialist
# Backend development
cct --agent backend-developer
cct --agent development-team/api-architect
# Security
cct --agent security-auditor
cct --agent security-team/penetration-tester
# DevOps
cct --agent devops-engineer
cct --agent infrastructure-team/kubernetes-expert
# Documentation
cct --agent technical-writer
cct --agent content-team/api-documentation-specialist
```
### Popular Agents
Expert in React, Vue, Angular, and modern web frameworks
API design, database optimization, and server-side logic
Code security review, vulnerability detection, best practices
CI/CD, infrastructure, deployment automation
### Usage After Installation
Invoke agents in Claude Code:
```
@frontend-developer Help me optimize this React component
@security-auditor Review this authentication code
```
## Commands
### What are Commands?
Slash commands provide quick access to common workflows and operations. They accept arguments and can include complex instructions.
### Installation Location
Commands install to:
```
.claude/commands/.md
```
### Examples
```bash theme={null}
# Testing
cct --command setup-testing
cct --command testing/generate-tests
# Code review
cct --command code-review
cct --command review/security-check
# Documentation
cct --command generate-docs
cct --command documentation/api-reference
# Deployment
cct --command deploy-staging
cct --command deployment/production-checklist
```
### Command Structure
Commands use the `$ARGUMENTS` placeholder for user input:
```markdown theme={null}
# Command: setup-testing
Setup comprehensive testing infrastructure for $ARGUMENTS.
Include:
- Test framework configuration
- Example test files
- CI/CD integration
```
### Usage After Installation
```
/setup-testing React components
/generate-docs API endpoints
/code-review authentication module
```
## MCP Servers
### What are MCP Servers?
MCP (Model Context Protocol) servers provide Claude Code with access to external services, databases, APIs, and tools.
### Installation Location
MCP configurations merge into:
```
.mcp.json
```
### Examples
```bash theme={null}
# Web access
cct --mcp web-fetch
# File system
cct --mcp filesystem-access
# Version control
cct --mcp github-integration
# Databases
cct --mcp mysql-integration
cct --mcp postgresql-integration
# Memory
cct --mcp memory-integration
# Code analysis
cct --mcp deepgraph-react
cct --mcp deepgraph-typescript
cct --mcp deepgraph-vue
```
### Configuration Merging
When installing MCPs:
1. Existing `.mcp.json` is preserved
2. New servers are added to `mcpServers` object
3. Conflicting server names are overwritten
4. Description fields are automatically removed
### MCP Configuration Example
After installing `web-fetch`:
```json theme={null}
{
"mcpServers": {
"fetch": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-fetch"]
}
}
}
```
## Hooks
### What are Hooks?
Hooks are automation triggers that execute commands at specific Claude Code lifecycle events.
### Installation Location
Hooks merge into:
```
.claude/settings.json
```
### Hook Types
* **PreToolUse** - Execute before tool usage
* **PostToolUse** - Execute after tool usage
* **Stop** - Execute when session stops
* **Notification** - Execute for notifications
### Examples
```bash theme={null}
# Git automation
cct --hook automation/git-commit-validation
cct --hook automation/git-auto-commit
# Notifications
cct --hook automation/simple-notifications
cct --hook automation/slack-notifications
# Testing
cct --hook automation/run-tests-before-commit
# Security
cct --hook automation/security-scan
```
### Hook Configuration Example
```json theme={null}
{
"hooks": {
"PreToolUse": [
{
"command": "npm run lint",
"description": "Run linter before file modifications"
}
],
"PostToolUse": [
{
"command": "git add .",
"description": "Stage changes automatically"
}
]
}
}
```
## Settings
### What are Settings?
Settings are pre-configured Claude Code settings for permissions, models, telemetry, and behavior.
### Installation Location
Settings merge into:
```
.claude/settings.json
```
### Categories
#### Permissions
```bash theme={null}
cct --setting permissions/allow-npm-commands
cct --setting permissions/deny-sensitive-files
cct --setting permissions/additional-directories
```
#### Model Selection
```bash theme={null}
cct --setting model/use-sonnet
cct --setting model/use-haiku
cct --setting model/use-opus
```
#### Telemetry
```bash theme={null}
cct --setting telemetry/enable-telemetry
cct --setting telemetry/disable-telemetry
```
#### Retention
```bash theme={null}
cct --setting retention/retention-7-days
cct --setting retention/retention-30-days
cct --setting retention/retention-90-days
```
#### Security
```bash theme={null}
cct --setting security/read-only-mode
cct --setting security/strict-permissions
```
#### Statuslines
```bash theme={null}
cct --setting statusline/context-monitor
cct --setting statusline/token-counter
```
### Statusline Settings
Statusline settings include Python scripts that are automatically downloaded:
```bash theme={null}
cct --setting statusline/context-monitor
```
This installs:
* `.claude/settings.json` (statusline configuration)
* `.claude/scripts/context-monitor.py` (Python script)
### Settings Configuration Example
```json theme={null}
{
"model": "claude-sonnet-4-20250514",
"permissions": {
"allow": [
{
"type": "exec",
"pattern": "npm"
}
],
"deny": [
{
"type": "read",
"pattern": "**/.env*"
}
]
},
"telemetryEnabled": false,
"cleanupPeriodDays": 7
}
```
## Skills
### What are Skills?
Skills are specialized workflows and capabilities that extend Claude Code functionality.
### Examples
```bash theme={null}
# Web development
cct --skill web-development/roier-seo
# Document processing
cct --skill document-processing/pptx
# Creative design
cct --skill creative-design/algorithmic-art
# Utilities
cct --skill utilities/playwright-skill
```
## Installation Options
### Target Directory
Install to a specific directory:
```bash theme={null}
cct --agent frontend-developer --directory ./my-project
cct -d ./my-project --command setup-testing
```
### Dry Run
Preview what would be installed without making changes:
```bash theme={null}
cct --agent security-auditor --dry-run
```
### Silent Mode
Suppress installation output (used in batch operations):
```bash theme={null}
cct --agent frontend-developer --silent
```
### With Prompt Execution
Install components and execute a prompt:
```bash theme={null}
cct --agent security-auditor --prompt "Review authentication code"
```
## Component Discovery
### Browse Components
Explore all available components:
* Website: [https://aitmpl.com/](https://aitmpl.com/)
* Components by category
* Search and filter functionality
* Installation copy-paste commands
### Not Found Handling
If a component isn't found, the CLI shows available options:
```bash theme={null}
cct --agent nonexistent-agent
# ❌ Agent "nonexistent-agent" not found
# 📋 Available Agents:
# ...
```
## Workflow Installation
### Install from Workflow Hash
Install a pre-defined workflow:
```bash theme={null}
cct --workflow #security-audit-workflow
```
### Install with YAML Workflow
Provide a base64-encoded YAML workflow:
```bash theme={null}
cct --workflow --agent security-auditor
```
## Troubleshooting
### Component Not Found
1. Verify component name spelling
2. Check component exists at [https://aitmpl.com/](https://aitmpl.com/)
3. Try category/name format: `development-team/frontend-developer`
### Installation Failed
1. Check network connectivity
2. Verify target directory permissions
3. Try with `--verbose` flag for detailed output
### Merge Conflicts
* **MCPs**: New servers added, conflicts overwrite existing
* **Settings**: Deep merge, new keys added, conflicts overwrite
* **Hooks**: Arrays merged, duplicates may occur
### Permission Issues
```bash theme={null}
# Ensure write permissions
chmod 755 .claude/
# Check directory ownership
ls -la .claude/
```
## Advanced Usage
### Batch Installation Script
Create a setup script:
```bash theme={null}
#!/bin/bash
# setup-claude.sh
cct --agent frontend-developer \
--agent backend-developer \
--command setup-testing \
--command code-review \
--mcp github-integration \
--mcp web-fetch \
--setting permissions/allow-npm-commands \
--setting model/use-sonnet \
--hook automation/git-commit-validation
echo "✅ Claude Code setup complete!"
```
### Team Configuration
Share component configurations:
```bash theme={null}
# Document required components
echo "Required Components:" > CLAUDE-SETUP.md
echo "- Agent: frontend-developer" >> CLAUDE-SETUP.md
echo "- Command: setup-testing" >> CLAUDE-SETUP.md
echo "- MCP: github-integration" >> CLAUDE-SETUP.md
# Install from documentation
cct --agent frontend-developer \
--command setup-testing \
--mcp github-integration
```
## Next Steps
* [Create Global Agents](/cli/create-agent) - Build globally accessible agents
* [List and Manage Agents](/cli/list-agents) - Manage installed agents
* [CLI Flags Reference](/cli/flags) - Complete flags documentation
* [Configuration Files](/cli/configuration) - Settings and config files
# List and Manage Agents
Source: https://davila7-claude-code-templates-86.mintlify.app/cli/list-agents
View, update, and remove globally installed agents
# List and Manage Agents
Manage your globally installed agents with listing, updating, and removal commands.
## List Global Agents
### View All Installed Agents
Display all globally installed agents:
```bash theme={null}
cct --list-agents
```
### Output Format
The listing shows:
```
📋 Installed Global Agents:
✅ Found 3 global agent(s):
✅ customer-support (🌍 system)
Usage: customer-support "your prompt"
Created: 2/28/2026
✅ security-auditor (🌍 system)
Usage: security-auditor "your prompt"
Created: 2/27/2026
✅ frontend-developer (👤 user)
Usage: frontend-developer "your prompt"
Created: 2/26/2026
🌟 Global Usage:
• Run from any directory: "prompt"
• List agents: npx claude-code-templates@latest --list-agents
• Remove agent: npx claude-code-templates@latest --remove-agent
```
### Installation Locations
Agents can be installed in two locations:
**System Directory** (🌍):
```
/usr/local/bin/
```
* Immediately available
* No PATH configuration required
* Requires write permissions
**User Directory** (👤):
```
~/.claude-code-templates/bin/
```
* User-specific installation
* Requires PATH configuration
* Works without sudo/admin rights
### Information Displayed
For each agent:
The agent's command name
Installation directory (system or user)
Whether the agent is executable (✅ or ❌)
Example command to invoke the agent
Installation date
## Update Global Agents
### Update an Agent
Update an agent to the latest version from GitHub:
```bash theme={null}
cct --update-agent
```
### Examples
```bash theme={null}
# Update customer support agent
cct --update-agent customer-support
# Update security auditor
cct --update-agent security-auditor
# Update frontend developer
cct --update-agent frontend-developer
```
### What Happens During Update
1. **Verification**: Checks if agent exists
2. **Download**: Fetches latest version from GitHub main branch
3. **Backup**: Preserves existing agent (overwritten on success)
4. **Installation**: Writes new agent file and executable
5. **Confirmation**: Displays success message
### Update Output
```bash theme={null}
cct --update-agent customer-support
🔄 Updating global agent: customer-support
🔄 Re-downloading latest version...
🤖 Creating global agent: customer-support
🌍 Installing to system directory (immediately available)
✅ Agent downloaded successfully
✅ Global agent 'customer-support' created successfully!
📦 Usage:
customer-support "your prompt here"
🎉 Ready to use immediately! No setup required.
```
### When to Update
Update agents when:
* New features are added to the agent
* Bug fixes are released
* System prompts are improved
* You want the latest capabilities
### Version Tracking
Agents are always updated to the latest version from:
```
https://github.com/davila7/claude-code-templates/main/cli-tool/components/agents/
```
No version numbers are tracked; updates always fetch the current main branch version.
## Remove Global Agents
### Remove an Agent
Delete a globally installed agent:
```bash theme={null}
cct --remove-agent
```
### Examples
```bash theme={null}
# Remove customer support agent
cct --remove-agent customer-support
# Remove security auditor
cct --remove-agent security-auditor
# Remove frontend developer
cct --remove-agent frontend-developer
```
### What Gets Removed
Deletion removes:
1. **System executable**: `/usr/local/bin/` (if exists)
2. **User executable**: `~/.claude-code-templates/bin/` (if exists)
3. **Agent file**: `~/.claude-code-templates/agents/.md`
### Removal Output
```bash theme={null}
cct --remove-agent customer-support
🗑️ Removing global agent: customer-support
✅ Removed system executable: customer-support
✅ Removed agent file: customer-support.md
🎉 Global agent 'customer-support' removed successfully!
```
### Agent Not Found
If the agent doesn't exist:
```bash theme={null}
cct --remove-agent nonexistent
🗑️ Removing global agent: nonexistent
⚠️ Agent 'nonexistent' not found.
💡 List available agents with: --list-agents
```
### Safety
Removal is immediate and cannot be undone. To restore:
```bash theme={null}
cct --create-agent
```
## Managing Multiple Agents
### Bulk Updates
Update multiple agents with a script:
```bash theme={null}
#!/bin/bash
# update-all-agents.sh
# List of agents to update
AGENTS=("customer-support" "security-auditor" "frontend-developer")
for agent in "${AGENTS[@]}"; do
echo "Updating $agent..."
cct --update-agent "$agent"
echo ""
done
echo "✅ All agents updated!"
```
### Bulk Removal
Remove multiple agents:
```bash theme={null}
#!/bin/bash
# remove-agents.sh
AGENTS=("old-agent" "deprecated-agent")
for agent in "${AGENTS[@]}"; do
echo "Removing $agent..."
cct --remove-agent "$agent"
echo ""
done
```
### Inventory Management
Export installed agents list:
```bash theme={null}
# List agents to file
cct --list-agents > installed-agents.txt
# Share with team
cat installed-agents.txt
```
## Troubleshooting
### Agent Shows as Not Executable (❌)
**Fix permissions:**
```bash theme={null}
# For user directory
chmod +x ~/.claude-code-templates/bin/
# For system directory (requires sudo)
sudo chmod +x /usr/local/bin/
```
### Agent Not Appearing in List
**Verify installation:**
```bash theme={null}
# Check user directory
ls -la ~/.claude-code-templates/bin/
# Check system directory
ls -la /usr/local/bin/ | grep claude
```
**Check agent file exists:**
```bash theme={null}
ls -la ~/.claude-code-templates/agents/
```
### Update Fails
**Check network connectivity:**
```bash theme={null}
ping raw.githubusercontent.com
```
**Verify agent exists on GitHub:**
Visit: [https://aitmpl.com/](https://aitmpl.com/) and search for the agent.
**Try manual update:**
```bash theme={null}
# Remove and recreate
cct --remove-agent
cct --create-agent
```
### Cannot Remove Agent
**Check permissions:**
```bash theme={null}
# For system directory removal
sudo cct --remove-agent
```
**Manual removal:**
```bash theme={null}
# Remove executable
rm ~/.claude-code-templates/bin/
sudo rm /usr/local/bin/
# Remove agent file
rm ~/.claude-code-templates/agents/.md
```
### Duplicate Agents
If agent exists in both system and user directories:
```bash theme={null}
# Remove from both locations
sudo rm /usr/local/bin/
rm ~/.claude-code-templates/bin/
# Recreate in preferred location
cct --create-agent
```
## Best Practices
### Regular Updates
Update agents monthly or when new features are announced:
```bash theme={null}
# Create update script
echo '#!/bin/bash' > update-agents.sh
echo 'cct --list-agents | grep -oP "(?<=✅ )\w+(?= )" | xargs -I {} cct --update-agent {}' >> update-agents.sh
chmod +x update-agents.sh
# Run updates
./update-agents.sh
```
### Documentation
Document your installed agents:
```bash theme={null}
# Create agents inventory
cat > AGENTS.md << EOF
# Installed Global Agents
## Customer Support
- **Command**: customer-support
- **Purpose**: Handle customer inquiries
- **Usage**: \`customer-support "how to handle refunds?"\`
## Security Auditor
- **Command**: security-auditor
- **Purpose**: Code security reviews
- **Usage**: \`security-auditor --file auth.js "review"\`
EOF
```
### Team Synchronization
Share agent configurations across teams:
```bash theme={null}
# Export agent list
cct --list-agents > team-agents.txt
# Team members install same agents
while read agent; do
cct --create-agent "$agent"
done < team-agents.txt
```
### Cleanup Unused Agents
Regularly review and remove unused agents:
```bash theme={null}
# List agents
cct --list-agents
# Remove unused
cct --remove-agent old-agent
cct --remove-agent deprecated-agent
```
### Backup Agent Files
Backup agent configurations:
```bash theme={null}
# Backup agents directory
tar -czf agents-backup.tar.gz ~/.claude-code-templates/agents/
# Restore if needed
tar -xzf agents-backup.tar.gz -C ~/
```
## Advanced Management
### Custom Agent Registry
Maintain a custom registry:
```bash theme={null}
# Create registry file
cat > agent-registry.json << EOF
{
"agents": [
{
"name": "customer-support",
"category": "business",
"version": "latest",
"required": true
},
{
"name": "security-auditor",
"category": "security",
"version": "latest",
"required": true
}
]
}
EOF
```
### Automated Updates
Schedule automatic updates with cron:
```bash theme={null}
# Edit crontab
crontab -e
# Add weekly update (Sundays at 2 AM)
0 2 * * 0 /usr/local/bin/update-agents.sh >> /var/log/agent-updates.log 2>&1
```
### Health Check
Verify all agents are functional:
```bash theme={null}
#!/bin/bash
# check-agents.sh
AGENTS=$(cct --list-agents | grep -oP '(?<=✅ )\w+(?= )')
for agent in $AGENTS; do
echo "Testing $agent..."
$agent --help > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "✅ $agent is working"
else
echo "❌ $agent is broken"
fi
done
```
## Migration
### Moving Between Machines
**Export agents:**
```bash theme={null}
# On source machine
tar -czf agents-export.tar.gz ~/.claude-code-templates/
scp agents-export.tar.gz user@target:/tmp/
```
**Import agents:**
```bash theme={null}
# On target machine
tar -xzf /tmp/agents-export.tar.gz -C ~/
# Fix permissions
chmod +x ~/.claude-code-templates/bin/*
# Add to PATH if needed
echo 'export PATH="$HOME/.claude-code-templates/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
```
### System to User Migration
Move from system to user directory:
```bash theme={null}
# List system agents
ls /usr/local/bin/ | grep -v '.'
# Recreate as user agents
for agent in $(ls /usr/local/bin/ | grep -v '.'); do
if [ -f ~/.claude-code-templates/agents/$agent.md ]; then
echo "Migrating $agent to user directory"
cp /usr/local/bin/$agent ~/.claude-code-templates/bin/
sudo rm /usr/local/bin/$agent
fi
done
```
## Next Steps
* [Create Global Agents](/cli/create-agent) - Create new global agents
* [Install Components](/cli/install-component) - Install project agents
* [CLI Flags Reference](/cli/flags) - All CLI flags
* [Configuration Guide](/cli/configuration) - Configuration files
# CLI Tool Overview
Source: https://davila7-claude-code-templates-86.mintlify.app/cli/overview
Complete guide to the Claude Code Templates CLI for managing components, agents, and configurations
# CLI Tool Overview
The Claude Code Templates CLI is a powerful tool for managing Claude Code configurations, components, and development workflows. Install and configure agents, commands, MCP servers, hooks, and settings for your projects.
## Installation
Install globally via npm:
```bash theme={null}
npm install -g claude-code-templates
```
Or use directly with npx (no installation required):
```bash theme={null}
npx claude-code-templates@latest
```
## Command Aliases
The CLI supports multiple command aliases for convenience:
```bash theme={null}
create-claude-config # Full command name
claude-code-templates # Package name
claude-code-template # Singular form
claude-init # Short init command
cctemplates # Abbreviated
cct # Shortest alias
claude-setup # Setup-focused
claude-config # Config-focused
```
All aliases provide identical functionality.
## Quick Start
### Interactive Setup
Launch the interactive menu to explore all features:
```bash theme={null}
cct
```
The menu provides access to:
* **Analytics Dashboard** - Monitor Claude Code usage and sessions
* **Chats Mobile** - AI-first mobile interface for conversations
* **Agents Dashboard** - View and analyze Claude conversations
* **Project Setup** - Configure Claude Code for your project
* **Health Check** - Verify your Claude Code setup
### Project Configuration
Setup Claude Code for your project with automatic detection:
```bash theme={null}
cct --yes # Use defaults with detected project type
```
Or run interactive prompts:
```bash theme={null}
cct # Follow guided setup
```
### Component Installation
Install specific components:
```bash theme={null}
# Install an agent
cct --agent frontend-developer
# Install a command
cct --command setup-testing
# Install an MCP server
cct --mcp web-fetch
# Install a hook
cct --hook automation/simple-notifications
# Install a setting
cct --setting permissions/allow-npm-commands
# Install a skill
cct --skill web-development/roier-seo
```
### Batch Installation
Install multiple components at once:
```bash theme={null}
cct --agent security-auditor --command security-audit --setting read-only-mode
cct --mcp web-fetch,filesystem-access,github-integration
```
## Core Features
### Analytics & Monitoring
Real-time analytics dashboard for Claude Code usage:
```bash theme={null}
cct --analytics # Launch analytics dashboard
cct --analytics --tunnel # Enable remote access via Cloudflare Tunnel
cct --agents # Launch agents dashboard
cct --2025 # Year in Review dashboard
```
### Global Agents
Create globally accessible AI agents:
```bash theme={null}
# Create a global agent
cct --create-agent customer-support
# List installed global agents
cct --list-agents
# Update an agent
cct --update-agent customer-support
# Remove an agent
cct --remove-agent customer-support
```
Once created, use global agents from anywhere:
```bash theme={null}
customer-support "How do I handle refund requests?"
```
### Health Check
Verify your Claude Code setup:
```bash theme={null}
cct --health-check
cct --health # Short alias
cct --verify # Alternative alias
```
Checks:
* System requirements (Node.js, OS, memory)
* Claude Code installation and authentication
* Project configuration files
* Agents, commands, and MCP servers
* Hook configurations
### Statistics & Analysis
Analyze your Claude Code usage:
```bash theme={null}
cct --command-stats # Analyze command usage
cct --hook-stats # Analyze automation hooks
cct --mcp-stats # Analyze MCP server usage
```
### Sandbox Execution
Run Claude Code in isolated sandbox environments:
```bash theme={null}
# E2B sandbox
cct --sandbox e2b --prompt "Create a React app"
# With API key
cct --sandbox e2b --e2b-api-key YOUR_KEY --prompt "Build a dashboard"
```
### Session Management
Clone and share Claude Code sessions:
```bash theme={null}
cct --clone-session https://example.com/session/abc123
```
## Component Types
The CLI manages six types of components:
### Agents (400+)
AI specialists for specific development tasks:
* Frontend developers (React, Vue, Angular)
* Backend developers (Node.js, Python, Go)
* Security auditors
* DevOps engineers
* Documentation writers
### Commands (225+)
Custom slash commands for workflows:
* Code review commands
* Testing setup
* Deployment automation
* Documentation generation
### MCP Servers (65+)
External service integrations:
* Web fetch
* Database connections (MySQL, PostgreSQL)
* GitHub integration
* Memory management
* File system access
### Settings (60+)
Claude Code configuration presets:
* Permissions management
* Model selection (Sonnet, Haiku)
* Telemetry controls
* Retention policies
* Statuslines
### Hooks (39+)
Automation triggers:
* Pre-tool use hooks
* Post-tool use hooks
* Notification hooks
* Git automation
* Testing automation
### Skills
Specialized workflows and capabilities:
* Web development tools
* Document processing
* Creative design
* Data analysis
## Configuration Files
The CLI creates and manages these files:
```bash theme={null}
.claude/
├── CLAUDE.md # Project context and guidelines
├── agents/ # Custom AI agents
├── commands/ # Slash commands
├── settings.json # Project settings
├── settings.local.json # Local overrides (gitignored)
└── scripts/ # Helper scripts
.mcp.json # MCP server configurations
```
## Environment Variables
Optional environment variables for enhanced functionality:
```bash theme={null}
# Anthropic API
ANTHROPIC_API_KEY=sk-ant-xxx
# Sandbox providers
E2B_API_KEY=xxx
# Remote access
CLOUDFLARE_TUNNEL_TOKEN=xxx
```
## Templates
Pre-configured templates for popular frameworks:
* **Common** - Universal configuration for any project
* **JavaScript/TypeScript** - Node.js, React, Vue, Next.js
* **Python** - Django, Flask, FastAPI
* **Ruby** - Rails, Sinatra
* **Go** - Standard library, Gin, Echo
* **Rust** - Cargo projects
## Dashboards
The CLI includes multiple web-based dashboards:
### Analytics Dashboard
```bash theme={null}
cct --analytics
```
Features:
* Real-time conversation tracking
* Token usage monitoring
* Session analysis
* Agent performance metrics
* Activity heatmaps
### Chats Mobile
```bash theme={null}
cct --chats
```
Mobile-optimized interface for:
* Conversation browsing
* Quick access to recent chats
* Search and filtering
### Plugin Dashboard
```bash theme={null}
cct --plugins
```
Manage:
* Marketplace browsing
* Installed plugins
* Permission management
### Skills Dashboard
```bash theme={null}
cct --skills-manager
```
Explore and manage Claude Code Skills.
### Teams Dashboard
```bash theme={null}
cct --teams
```
Review multi-agent collaboration sessions.
## Remote Access
Enable remote access to dashboards via Cloudflare Tunnel:
```bash theme={null}
cct --analytics --tunnel
cct --chats --tunnel
```
Generates a public URL for accessing dashboards from any device.
## Workflow Examples
### New Project Setup
```bash theme={null}
# Navigate to your project
cd my-project
# Run interactive setup
cct
# Or use defaults for detected project type
cct --yes
```
### Security-Focused Setup
```bash theme={null}
cct --agent security-auditor \
--command security-audit \
--setting permissions/deny-sensitive-files \
--setting security/read-only-mode
```
### Full-Stack Development
```bash theme={null}
cct --agent frontend-developer \
--agent backend-developer \
--command setup-testing \
--mcp github-integration \
--hook automation/git-commit-validation
```
### Documentation Project
```bash theme={null}
cct --agent technical-writer \
--command generate-docs \
--setting statusline/context-monitor
```
## Tips & Best Practices
1. **Start with Health Check**: Run `cct --health` before setup
2. **Use Dry Run**: Test configurations with `--dry-run`
3. **Leverage Analytics**: Monitor usage with `cct --analytics`
4. **Create Global Agents**: Build reusable agents with `--create-agent`
5. **Batch Install**: Install multiple components in one command
6. **Version Consistency**: Use `@latest` with npx for latest features
## Getting Help
View help for any command:
```bash theme={null}
cct --help
```
Explore components at:
* Website: [https://aitmpl.com/](https://aitmpl.com/)
* Documentation: [https://docs.aitmpl.com/](https://docs.aitmpl.com/)
* GitHub: [https://github.com/davila7/claude-code-templates](https://github.com/davila7/claude-code-templates)
## Next Steps
* [Install Components](/cli/install-component) - Detailed component installation guide
* [Create Global Agents](/cli/create-agent) - Build globally accessible agents
* [CLI Flags Reference](/cli/flags) - Complete flags documentation
* [Configuration Guide](/cli/configuration) - Settings and configuration files
# Agent Components
Source: https://davila7-claude-code-templates-86.mintlify.app/components/agents
400+ AI specialist agents for every development task - from frontend to DevOps
# Agent Components
Agents are AI specialists that help with specific development tasks. Each agent has expertise in particular technologies, frameworks, or methodologies.
Explore 400+ agents with search and filtering at **aitmpl.com**
## Installation
```bash theme={null}
# Install a single agent
npx claude-code-templates@latest --agent backend-developer
# Install multiple agents
npx claude-code-templates@latest --agent backend-developer --agent frontend-developer
# Install from specific category
npx claude-code-templates@latest --agent development-team/backend-developer
```
## Agent Categories
### Development Team
Core development specialists for building applications:
Senior backend developer specializing in APIs, microservices, and scalable systems
```bash theme={null}
npx claude-code-templates@latest --agent backend-developer
```
Expert in React, Vue, Angular, and modern frontend frameworks
```bash theme={null}
npx claude-code-templates@latest --agent frontend-developer
```
End-to-end application development with frontend and backend expertise
```bash theme={null}
npx claude-code-templates@latest --agent fullstack-developer
```
iOS, Android, React Native, and Flutter development specialist
```bash theme={null}
npx claude-code-templates@latest --agent mobile-developer
```
Infrastructure, CI/CD, containerization, and deployment automation
```bash theme={null}
npx claude-code-templates@latest --agent devops-engineer
```
Automated test generation with comprehensive coverage
```bash theme={null}
npx claude-code-templates@latest --agent test-generator
```
### Database Specialists
Database architecture, optimization, and platform-specific experts:
Schema design, normalization, and database architecture
```bash theme={null}
npx claude-code-templates@latest --agent database-architect
```
PostgreSQL optimization, query tuning, and advanced features
```bash theme={null}
npx claude-code-templates@latest --agent postgres-pro
```
Neon serverless Postgres specialist
```bash theme={null}
npx claude-code-templates@latest --agent neon-expert
```
Query optimization, indexing, and performance tuning
```bash theme={null}
npx claude-code-templates@latest --agent database-optimizer
```
### DevOps & Infrastructure
Cloud platforms, containerization, and infrastructure as code:
Multi-cloud architecture and infrastructure design
```bash theme={null}
npx claude-code-templates@latest --agent cloud-architect
```
K8s deployment, scaling, and orchestration
```bash theme={null}
npx claude-code-templates@latest --agent kubernetes-specialist
```
Infrastructure as Code with Terraform
```bash theme={null}
npx claude-code-templates@latest --agent terraform-engineer
```
Azure cloud architecture and best practices
```bash theme={null}
npx claude-code-templates@latest --agent azure-principal-architect
```
### AI Specialists
Machine learning, LLM development, and AI ethics:
Large Language Model architecture and fine-tuning
```bash theme={null}
npx claude-code-templates@latest --agent llm-architect
```
Expert prompt design and optimization
```bash theme={null}
npx claude-code-templates@latest --agent prompt-engineer
```
AI safety, bias detection, and ethical AI development
```bash theme={null}
npx claude-code-templates@latest --agent ai-ethics-advisor
```
ML model evaluation and performance analysis
```bash theme={null}
npx claude-code-templates@latest --agent model-evaluator
```
### API Development
RESTful APIs, GraphQL, and API architecture:
RESTful API design and architecture patterns
```bash theme={null}
npx claude-code-templates@latest --agent api-architect
```
GraphQL schema design and optimization
```bash theme={null}
npx claude-code-templates@latest --agent graphql-architect
```
### Documentation Specialists
Technical writing, API docs, and documentation automation:
Comprehensive technical documentation
```bash theme={null}
npx claude-code-templates@latest --agent documentation-expert
```
## Agent Features
All agents include:
* **Specialized Knowledge**: Deep expertise in specific technologies
* **Tool Access**: Pre-configured with appropriate tools (Read, Write, Bash, etc.)
* **Best Practices**: Industry-standard patterns and conventions
* **Model Selection**: Optimized model choice for the task
## How Agents Work
When you install an agent:
1. The agent file is downloaded to `.claude/agents/`
2. Use `@agent-name` in your Claude Code chat to invoke it
3. The agent automatically uses its specialized knowledge and tools
4. Results are integrated into your codebase
## Example Usage
```bash theme={null}
# Install backend developer agent
npx claude-code-templates@latest --agent backend-developer
# In Claude Code chat:
# @backend-developer Create a REST API for user management with JWT auth
```
## Next Steps
* [Browse all agents at aitmpl.com](https://aitmpl.com/?type=agents)
* [View development team agents](/categories/development-team)
* [Explore database agents](/categories/database)
* [Check out DevOps agents](/categories/devops-infrastructure)
# Command Components
Source: https://davila7-claude-code-templates-86.mintlify.app/components/commands
225+ custom slash commands for automated workflows and common development tasks
# Command Components
Commands are custom slash commands that automate common development tasks. They execute pre-defined workflows, run scripts, or coordinate multiple operations.
Explore 225+ commands with search and filtering at **aitmpl.com**
## Installation
```bash theme={null}
# Install a single command
npx claude-code-templates@latest --command security-audit
# Install multiple commands
npx claude-code-templates@latest --command setup-testing --command generate-docs
# Install from specific category
npx claude-code-templates@latest --command security/security-audit
```
## Command Categories
### Security Commands
Automated security scanning, auditing, and hardening:
Comprehensive security assessment and vulnerability analysis
```bash theme={null}
npx claude-code-templates@latest --command security-audit
```
Usage: `/security-audit` or `/security-audit --full`
Scan codebase for hardcoded secrets and credentials
```bash theme={null}
npx claude-code-templates@latest --command secrets-scanner
```
Check dependencies for known vulnerabilities
```bash theme={null}
npx claude-code-templates@latest --command dependency-audit
```
Apply security best practices to your application
```bash theme={null}
npx claude-code-templates@latest --command security-hardening
```
Automated penetration testing workflows
```bash theme={null}
npx claude-code-templates@latest --command penetration-test
```
Add authentication system to your application
```bash theme={null}
npx claude-code-templates@latest --command add-authentication-system
```
### Testing Commands
Test generation, automation, and quality assurance:
Configure comprehensive testing infrastructure
```bash theme={null}
npx claude-code-templates@latest --command setup-testing
```
Auto-generate unit and integration tests
```bash theme={null}
npx claude-code-templates@latest --command generate-tests
```
Set up end-to-end testing with Playwright or Cypress
```bash theme={null}
npx claude-code-templates@latest --command e2e-setup
```
Analyze and improve test coverage
```bash theme={null}
npx claude-code-templates@latest --command test-coverage
```
Configure load and performance testing
```bash theme={null}
npx claude-code-templates@latest --command setup-load-testing
```
### Database Commands
Database management, migrations, and optimization:
Create and manage Supabase migrations
```bash theme={null}
npx claude-code-templates@latest --command supabase-migration-assistant
```
Sync database schema with Supabase
```bash theme={null}
npx claude-code-templates@latest --command supabase-schema-sync
```
Optimize Supabase database performance
```bash theme={null}
npx claude-code-templates@latest --command supabase-performance-optimizer
```
Audit Supabase security configuration
```bash theme={null}
npx claude-code-templates@latest --command supabase-security-audit
```
### Git Workflow Commands
Git flow automation and branch management:
Start a new feature branch with git flow
```bash theme={null}
npx claude-code-templates@latest --command feature
```
Create and manage hotfix branches
```bash theme={null}
npx claude-code-templates@latest --command hotfix
```
Manage release branches and versioning
```bash theme={null}
npx claude-code-templates@latest --command release
```
Complete feature/hotfix/release branches
```bash theme={null}
npx claude-code-templates@latest --command finish
```
### Documentation Commands
Auto-generate docs and maintain documentation:
Auto-generate API and code documentation
```bash theme={null}
npx claude-code-templates@latest --command generate-docs
```
### Deployment Commands
Deployment automation and infrastructure:
Deploy Next.js applications to Vercel
```bash theme={null}
npx claude-code-templates@latest --command nextjs-vercel
```
## Command Structure
Commands typically include:
* **Description**: What the command does
* **Allowed Tools**: Tools the command can use (Read, Write, Bash, etc.)
* **Argument Hints**: Expected parameters
* **Workflow Steps**: Pre-defined execution steps
* **Context Loading**: Automatic file and environment loading
## How Commands Work
When you install a command:
1. The command file is downloaded to `.claude/commands/`
2. Use `/command-name` in your Claude Code chat to invoke it
3. The command executes its pre-defined workflow
4. Results are applied to your codebase
## Example Usage
```bash theme={null}
# Install security audit command
npx claude-code-templates@latest --command security-audit
# In Claude Code chat:
# /security-audit
# or with arguments:
# /security-audit --full
```
## Command Arguments
Many commands accept arguments:
```bash theme={null}
# In Claude Code chat:
/security-audit frontend # Focus on frontend security
/generate-tests src/api # Generate tests for specific directory
/feature user-authentication # Start feature branch with name
```
## Next Steps
* [Browse all commands at aitmpl.com](https://aitmpl.com/?type=commands)
* [View security commands](/categories/security)
* [Explore database commands](/categories/database)
* [Check out testing commands](/categories/testing)
# Hook Components
Source: https://davila7-claude-code-templates-86.mintlify.app/components/hooks
45+ automation hooks for git workflows, testing, security scanning, and more
# Hook Components
Hooks are automation triggers that execute before or after specific events. They enable automated workflows, validation, and enforcement of best practices.
Explore 45+ hooks at **aitmpl.com**
## Installation
```bash theme={null}
# Install a single hook
npx claude-code-templates@latest --hook git/conventional-commits
# Install multiple hooks
npx claude-code-templates@latest --hook git/conventional-commits --hook security/secret-scanner
# Install from specific category
npx claude-code-templates@latest --hook security/dangerous-command-blocker
```
## Hook Categories
### Git Hooks
Automate git workflows and enforce commit standards:
Enforce conventional commit message format
```bash theme={null}
npx claude-code-templates@latest --hook git/conventional-commits
```
**Validates:**
* Commit message format (feat:, fix:, docs:, etc.)
* Scope and description
* Breaking change notation
Block direct pushes to protected branches
```bash theme={null}
npx claude-code-templates@latest --hook git/prevent-direct-push
```
**Protects:**
* main/master branches
* production branches
* Enforces PR workflow
Enforce branch naming conventions
```bash theme={null}
npx claude-code-templates@latest --hook git/validate-branch-name
```
**Enforces:**
* feature/, bugfix/, hotfix/ prefixes
* Lowercase with hyphens
* Ticket/issue references
### Security Hooks
Prevent security vulnerabilities and secrets leakage:
Scan commits for hardcoded secrets and API keys
```bash theme={null}
npx claude-code-templates@latest --hook security/secret-scanner
```
**Detects:**
* API keys and tokens
* Private keys and certificates
* Database credentials
* OAuth secrets
Block dangerous commands and operations
```bash theme={null}
npx claude-code-templates@latest --hook security/dangerous-command-blocker
```
**Blocks:**
* Force pushes to main
* Destructive operations
* Unsafe shell commands
Run security scans before commits
```bash theme={null}
npx claude-code-templates@latest --hook security/security-scanner
```
Protect sensitive files from being committed
```bash theme={null}
npx claude-code-templates@latest --hook security/file-protection
```
### Testing Hooks
Automate test execution and validation:
Run tests automatically before commits
```bash theme={null}
npx claude-code-templates@latest --hook testing/test-runner
```
**Features:**
* Pre-commit test execution
* Changed file detection
* Test coverage validation
### Git Workflow Hooks
Advanced git flow automation:
Protect important branches from accidental changes
```bash theme={null}
npx claude-code-templates@latest --hook git-workflow/branch-protection
```
Lint commit messages for quality
```bash theme={null}
npx claude-code-templates@latest --hook git-workflow/commit-linting
```
### Automation Hooks
General automation and notifications:
Send notifications on key events
```bash theme={null}
npx claude-code-templates@latest --hook automation/simple-notifications
```
Auto-generate changelog entries
```bash theme={null}
npx claude-code-templates@latest --hook automation/changelog-generator
```
### Tool Hooks
Execute before or after Claude Code tools:
Validate context before tool execution
```bash theme={null}
npx claude-code-templates@latest --hook pre-tool/validation
```
Clean up after tool execution
```bash theme={null}
npx claude-code-templates@latest --hook post-tool/cleanup
```
### Performance Hooks
Monitor and optimize performance:
Warn on bundle size increases
```bash theme={null}
npx claude-code-templates@latest --hook performance/bundle-size-check
```
Track operation performance
```bash theme={null}
npx claude-code-templates@latest --hook performance/monitor
```
### Monitoring Hooks
Track events and metrics:
Track and report errors
```bash theme={null}
npx claude-code-templates@latest --hook monitoring/error-tracking
```
Collect usage analytics
```bash theme={null}
npx claude-code-templates@latest --hook monitoring/usage-analytics
```
## Hook Types
### Pre-Commit Hooks
Run before a commit is created:
* Validate commit messages
* Run linters and formatters
* Check for secrets
* Run tests
### Pre-Push Hooks
Run before pushing to remote:
* Run full test suite
* Check branch protection
* Validate no uncommitted changes
### Pre-Tool Hooks
Run before Claude Code tool execution:
* Validate environment
* Check permissions
* Load context
### Post-Tool Hooks
Run after Claude Code tool execution:
* Clean up temporary files
* Update metrics
* Send notifications
## Hook Configuration
Hooks are stored in `.claude/hooks/`:
```json theme={null}
{
"name": "conventional-commits",
"description": "Enforce conventional commit messages",
"trigger": "pre-commit",
"command": "python",
"args": [".claude/scripts/conventional-commits.py"]
}
```
## Python Script Hooks
Many hooks use Python scripts for complex logic:
```python theme={null}
# .claude/scripts/secret-scanner.py
import re
import sys
patterns = [
r'(?i)(api[_-]?key|apikey)\s*=\s*["\'][^"\']',
r'(?i)(password|passwd)\s*=\s*["\'][^"\']',
# ... more patterns
]
def scan_file(filepath):
with open(filepath) as f:
content = f.read()
for pattern in patterns:
if re.search(pattern, content):
return True
return False
```
## Example Usage
```bash theme={null}
# Install conventional commits hook
npx claude-code-templates@latest --hook git/conventional-commits
# Now all commits must follow conventional format
git commit -m "feat: add user authentication"
# ✓ Valid
git commit -m "Added authentication"
# ✗ Rejected - must use conventional format
```
## Disabling Hooks
Temporarily bypass hooks when needed:
```bash theme={null}
# Skip git hooks
git commit --no-verify -m "emergency fix"
# Disable specific hook
chmod -x .claude/hooks/conventional-commits.json
```
## Creating Custom Hooks
Create your own hooks:
1. Create JSON config in `.claude/hooks/`
2. Create Python script in `.claude/scripts/` (if needed)
3. Test the hook
4. Share with your team
## Next Steps
* [Browse all hooks at aitmpl.com](https://aitmpl.com/?type=hooks)
* [View security hooks](/categories/security)
* [Explore git workflow hooks](/components/hooks#git-workflow)
* [Learn about testing hooks](/categories/testing)
# MCP Components
Source: https://davila7-claude-code-templates-86.mintlify.app/components/mcps
65+ Model Context Protocol servers for integrating external services with Claude Code
# MCP Components
MCPs (Model Context Protocol servers) enable Claude Code to integrate with external services, databases, APIs, and tools. They extend Claude's capabilities beyond the local codebase.
Explore 65+ MCP integrations at **aitmpl.com**
## Installation
```bash theme={null}
# Install a single MCP
npx claude-code-templates@latest --mcp neon
# Install multiple MCPs
npx claude-code-templates@latest --mcp neon --mcp supabase --mcp web-fetch
# Install from specific category
npx claude-code-templates@latest --mcp database/neon
```
## MCP Categories
### Database MCPs
Connect to databases and manage data:
Neon serverless Postgres integration
```bash theme={null}
npx claude-code-templates@latest --mcp neon
```
**Features:**
* Query databases directly
* Manage schemas and migrations
* Access Neon Management API
Supabase platform integration
```bash theme={null}
npx claude-code-templates@latest --mcp supabase
```
**Features:**
* Database operations
* Authentication management
* Storage and realtime
Direct PostgreSQL database access
```bash theme={null}
npx claude-code-templates@latest --mcp postgresql-integration
```
MySQL database integration
```bash theme={null}
npx claude-code-templates@latest --mcp mysql-integration
```
### Web MCPs
Fetch and interact with web content:
Fetch and parse web content
```bash theme={null}
npx claude-code-templates@latest --mcp web-fetch
```
**Features:**
* HTTP requests
* HTML parsing
* Content extraction
Read and analyze web pages
```bash theme={null}
npx claude-code-templates@latest --mcp web-reader
```
Advanced web search capabilities
```bash theme={null}
npx claude-code-templates@latest --mcp web-search-prime
```
Enhanced web content reading
```bash theme={null}
npx claude-code-templates@latest --mcp zread
```
### Browser Automation MCPs
Automate browser interactions and web scraping:
Browser automation with Puppeteer
```bash theme={null}
npx claude-code-templates@latest --mcp puppeteer
```
**Features:**
* Page navigation
* Form filling
* Screenshot capture
* PDF generation
### Productivity MCPs
Task management, notes, and workflow automation:
Todoist task management integration
```bash theme={null}
npx claude-code-templates@latest --mcp todoist
```
Notion workspace integration
```bash theme={null}
npx claude-code-templates@latest --mcp notion
```
### Development Tools MCPs
Developer utilities and integrations:
GitHub API integration
```bash theme={null}
npx claude-code-templates@latest --mcp github
```
**Features:**
* Repository management
* Issue tracking
* Pull request automation
Docker container management
```bash theme={null}
npx claude-code-templates@latest --mcp docker
```
### Audio MCPs
Audio processing and transcription:
Audio transcription with OpenAI Whisper
```bash theme={null}
npx claude-code-templates@latest --mcp whisper
```
### Marketing MCPs
Marketing automation and analytics:
Google Analytics data access
```bash theme={null}
npx claude-code-templates@latest --mcp google-analytics
```
## MCP Configuration
MCPs are configured in `.claude/.mcp.json`:
```json theme={null}
{
"mcpServers": {
"Neon": {
"description": "MCP server for Neon database",
"command": "npx",
"args": ["-y", "mcp-remote", "https://mcp.neon.tech/mcp"]
}
}
}
```
## How MCPs Work
1. **Installation**: MCP configuration is added to `.mcp.json`
2. **Startup**: Claude Code loads configured MCPs on launch
3. **Tool Access**: MCPs expose tools that Claude can use
4. **Execution**: When Claude uses an MCP tool, it communicates with the external service
## Environment Variables
Many MCPs require API keys or credentials:
```bash theme={null}
# In your .env file
NEON_API_KEY=your_api_key
SUPABASE_URL=your_project_url
SUPABASE_KEY=your_service_key
GITHUB_TOKEN=your_github_token
```
## Example Usage
```bash theme={null}
# Install Neon MCP
npx claude-code-templates@latest --mcp neon
# Add your Neon API key to .env
echo "NEON_API_KEY=your_key" >> .env
# In Claude Code chat:
# "Query my Neon database for all users"
# "Create a new branch in my Neon project"
```
## Popular MCPs
### Neon
Serverless Postgres with branching, instant provisioning, and autoscaling.
### Supabase
Complete backend platform with database, auth, storage, and realtime.
### Web Fetch
Fetch and parse web content for research and analysis.
### GitHub
Manage repositories, issues, pull requests, and workflows.
## Next Steps
* [Browse all MCPs at aitmpl.com](https://aitmpl.com/?type=mcps)
* [View database MCPs](/categories/database)
* [Explore MCP settings](/components/settings)
* [Learn about MCP configuration](https://modelcontextprotocol.io)
# Component Library
Source: https://davila7-claude-code-templates-86.mintlify.app/components/overview
Browse and install 1000+ components for Claude Code - agents, commands, MCPs, hooks, settings, and templates
# Component Library
Claude Code Templates provides a comprehensive library of over 1000 pre-built components to enhance your development workflow. Browse, search, and install components directly from your terminal or through our interactive web browser.
## Component Types
400+ AI specialists for every development task - from frontend development to security audits
225+ custom slash commands for automated workflows and common tasks
65+ Model Context Protocol servers for external service integrations
39+ automation triggers for git workflows, testing, and security
60+ configuration presets for Claude Code behavior and integrations
14+ complete project configurations with pre-installed components
## Quick Start
Install components using the CLI:
```bash theme={null}
# Install a single component
npx claude-code-templates@latest --agent frontend-developer
npx claude-code-templates@latest --command setup-testing
npx claude-code-templates@latest --mcp neon
# Install multiple components
npx claude-code-templates@latest --agent backend-developer --command security-audit --hook git/conventional-commits
# Interactive mode
npx claude-code-templates@latest
```
## Browse Components
Explore all components with search, filtering, and live previews at **aitmpl.com**
### Browse by Category
* [Agents](/components/agents) - AI development specialists
* [Commands](/components/commands) - Slash commands
* [MCPs](/components/mcps) - Service integrations
* [Hooks](/components/hooks) - Automation triggers
* [Settings](/components/settings) - Configuration presets
* [Templates](/components/templates) - Project templates
* [Development Team](/categories/development-team) - Complete dev team agents
* [Security](/categories/security) - Security-focused components
* [Database](/categories/database) - Database tools and integrations
* [DevOps & Infrastructure](/categories/devops-infrastructure) - Cloud and deployment
* [Testing](/categories/testing) - Testing and QA automation
## Component Metadata
All components include:
* **Name**: Unique identifier for installation
* **Description**: Clear explanation of functionality
* **Category**: Organizational grouping
* **Type**: Agent, command, MCP, hook, setting, or template
* **Installation**: Ready-to-use CLI command
## Popular Components
### Top Agents
* `backend-developer` - Senior backend developer for APIs and microservices
* `frontend-developer` - React, Vue, Angular specialist
* `devops-engineer` - Infrastructure and deployment expert
* `security-auditor` - Comprehensive security assessments
### Top Commands
* `setup-testing` - Configure comprehensive test suites
* `security-audit` - Run security vulnerability scans
* `generate-docs` - Auto-generate documentation
* `optimize-performance` - Performance analysis and optimization
### Top MCPs
* `neon` - Neon database integration
* `supabase` - Supabase platform integration
* `web-fetch` - Web content fetching
* `github` - GitHub API integration
## Contributing
Want to contribute your own components? Check out our [contribution guide](https://github.com/johnlindquist/claude-code-templates/blob/main/CONTRIBUTING.md).
## Support
Need help? Join our [Discord community](https://discord.gg/claudecode) or visit the [documentation](/).
# Settings Components
Source: https://davila7-claude-code-templates-86.mintlify.app/components/settings
60+ configuration presets for Claude Code behavior, integrations, and workflow customization
# Settings Components
Settings are configuration presets that customize Claude Code's behavior, integrations, and workflow. They configure everything from model selection to status line displays.
Explore 60+ settings at **aitmpl.com**
## Installation
```bash theme={null}
# Install a single setting
npx claude-code-templates@latest --setting read-only-mode
# Install multiple settings
npx claude-code-templates@latest --setting read-only-mode --setting git/auto-commit
# Install from specific category
npx claude-code-templates@latest --setting mcp/enable-all-project-servers
```
## Setting Categories
### MCP Settings
Configure Model Context Protocol servers:
Enable all MCP servers defined in the project
```bash theme={null}
npx claude-code-templates@latest --setting mcp/enable-all-project-servers
```
Enable only selected MCP servers
```bash theme={null}
npx claude-code-templates@latest --setting mcp/enable-specific-servers
```
Disable MCP servers with dangerous capabilities
```bash theme={null}
npx claude-code-templates@latest --setting mcp/disable-risky-servers
```
Configure timeout settings for MCP servers
```bash theme={null}
npx claude-code-templates@latest --setting mcp/mcp-timeouts
```
### Model Settings
Configure AI model selection and behavior:
Set default model for Claude Code
```bash theme={null}
npx claude-code-templates@latest --setting model/default
```
**Options:**
* claude-4.5-sonnet (balanced)
* claude-opus (complex tasks)
* claude-haiku (fast tasks)
Configure different models for different agents
```bash theme={null}
npx claude-code-templates@latest --setting model/agent-specific
```
### Git Settings
Configure git workflow automation:
Automatically commit changes after operations
```bash theme={null}
npx claude-code-templates@latest --setting git/auto-commit
```
Use templates for commit messages
```bash theme={null}
npx claude-code-templates@latest --setting git/commit-templates
```
Configure protected branches
```bash theme={null}
npx claude-code-templates@latest --setting git/branch-protection
```
### Permission Settings
Control Claude Code's access and capabilities:
Restrict Claude to read-only operations
```bash theme={null}
npx claude-code-templates@latest --setting permissions/read-only-mode
```
**Blocks:**
* File writes and edits
* Git commits
* Destructive commands
Limit bash command execution
```bash theme={null}
npx claude-code-templates@latest --setting permissions/restricted-bash
```
Restrict file access to specific directories
```bash theme={null}
npx claude-code-templates@latest --setting permissions/allowed-directories
```
### Statusline Settings
Customize the status line display:
Show git branch and status in statusline
```bash theme={null}
npx claude-code-templates@latest --setting statusline/git-status
```
Display token usage in statusline
```bash theme={null}
npx claude-code-templates@latest --setting statusline/token-counter
```
Create custom statusline with Python script
```bash theme={null}
npx claude-code-templates@latest --setting statusline/custom
```
### Environment Settings
Configure environment variables and context:
Automatically load .env files
```bash theme={null}
npx claude-code-templates@latest --setting environment/auto-load-env
```
Use .env templates for different environments
```bash theme={null}
npx claude-code-templates@latest --setting environment/templates
```
### API Settings
Configure API endpoints and keys:
Use custom Claude API endpoint
```bash theme={null}
npx claude-code-templates@latest --setting api/custom-endpoint
```
Configure API rate limiting
```bash theme={null}
npx claude-code-templates@latest --setting api/rate-limiting
```
### Telemetry Settings
Control analytics and telemetry:
Disable all telemetry collection
```bash theme={null}
npx claude-code-templates@latest --setting telemetry/disable
```
Enable anonymous usage analytics
```bash theme={null}
npx claude-code-templates@latest --setting telemetry/anonymous
```
### Cleanup Settings
Automatic cleanup and maintenance:
Automatically clean temporary files
```bash theme={null}
npx claude-code-templates@latest --setting cleanup/auto-cleanup
```
Rotate and archive logs
```bash theme={null}
npx claude-code-templates@latest --setting cleanup/log-rotation
```
### Global Settings
System-wide configurations:
Configure editor integration settings
```bash theme={null}
npx claude-code-templates@latest --setting global/editor-integration
```
Set default workspace configurations
```bash theme={null}
npx claude-code-templates@latest --setting global/workspace-defaults
```
## Settings Configuration
Settings are stored in `.claude/settings/` and `.claude/config/`:
```json theme={null}
{
"name": "read-only-mode",
"description": "Restrict Claude to read-only operations",
"config": {
"permissions": {
"allowWrite": false,
"allowBash": false,
"allowGit": false
}
}
}
```
## Statusline with Python
Custom statuslines can use Python scripts:
```python theme={null}
# .claude/scripts/git-status.py
import subprocess
def get_git_status():
branch = subprocess.check_output(['git', 'branch', '--show-current'])
status = subprocess.check_output(['git', 'status', '--short'])
return f"{branch.strip()} | {len(status.splitlines())} changes"
print(get_git_status())
```
## Setting Priorities
Settings are applied in order:
1. **Global settings**: System-wide defaults
2. **Project settings**: Project-specific configs
3. **User settings**: User overrides
4. **Runtime settings**: Temporary overrides
## Example Usage
```bash theme={null}
# Enable read-only mode for safety
npx claude-code-templates@latest --setting read-only-mode
# Claude can now only read files, not modify them
# To disable, remove .claude/settings/read-only-mode.json
```
## Combining Settings
Install multiple related settings:
```bash theme={null}
# Security-focused configuration
npx claude-code-templates@latest \
--setting permissions/read-only-mode \
--setting mcp/disable-risky-servers \
--setting git/branch-protection
```
## Temporary Settings
Some settings can be overridden temporarily:
```bash theme={null}
# In Claude Code, use environment variables
export CLAUDE_ALLOW_WRITE=true
```
## Next Steps
* [Browse all settings at aitmpl.com](https://aitmpl.com/?type=settings)
* [View MCP settings](/components/settings#mcp)
* [Explore permission settings](/components/settings#permissions)
* [Learn about statusline customization](/components/settings#statusline)
# Template Components
Source: https://davila7-claude-code-templates-86.mintlify.app/components/templates
14+ complete project templates with pre-installed components for rapid development
# Template Components
Templates are complete project configurations with pre-installed agents, commands, MCPs, hooks, and settings. They provide ready-to-use setups for specific project types.
Explore 14+ templates at **aitmpl.com**
## Installation
```bash theme={null}
# Install a template
npx claude-code-templates@latest --template fullstack-web
# Templates install all included components automatically
```
## Available Templates
Complete fullstack web development setup
```bash theme={null}
npx claude-code-templates@latest --template fullstack-web
```
**Includes:**
* Frontend developer agent
* Backend developer agent
* Database architect agent
* Testing commands
* Git workflow hooks
* Security scanning
RESTful and GraphQL API development
```bash theme={null}
npx claude-code-templates@latest --template api-development
```
**Includes:**
* API architect agent
* Backend developer agent
* Database integration MCPs
* API documentation commands
* Security audit commands
Maximum security configuration
```bash theme={null}
npx claude-code-templates@latest --template security-hardened
```
**Includes:**
* Security auditor agent
* Secret scanner hooks
* Dependency audit commands
* Read-only mode setting
* Branch protection
Database-intensive application setup
```bash theme={null}
npx claude-code-templates@latest --template database-project
```
**Includes:**
* Database architect agent
* Database optimizer agent
* Neon/Supabase MCPs
* Migration commands
* Performance monitoring
CI/CD and infrastructure automation
```bash theme={null}
npx claude-code-templates@latest --template devops-pipeline
```
**Includes:**
* DevOps engineer agent
* Cloud architect agent
* Terraform specialist agent
* Deployment commands
* Infrastructure monitoring
Comprehensive testing infrastructure
```bash theme={null}
npx claude-code-templates@latest --template testing-suite
```
**Includes:**
* Test generator agent
* E2E testing setup
* Test runner hooks
* Coverage commands
* Performance testing
iOS, Android, and cross-platform mobile
```bash theme={null}
npx claude-code-templates@latest --template mobile-development
```
**Includes:**
* Mobile developer agent
* iOS developer agent
* Flutter developer agent
* Mobile testing commands
* App deployment automation
Machine learning and AI development
```bash theme={null}
npx claude-code-templates@latest --template ai-ml-project
```
**Includes:**
* LLM architect agent
* Prompt engineer agent
* Model evaluator agent
* Data processing commands
* Experiment tracking
Microservices architecture setup
```bash theme={null}
npx claude-code-templates@latest --template microservices
```
**Includes:**
* Microservices architect agent
* Backend developer agent
* Docker/K8s specialists
* Service mesh configuration
* Distributed tracing
Monorepo management and tooling
```bash theme={null}
npx claude-code-templates@latest --template monorepo
```
**Includes:**
* Fullstack developer agent
* Monorepo management commands
* Workspace configuration
* Cross-package testing
* Dependency management
Documentation website creation
```bash theme={null}
npx claude-code-templates@latest --template documentation-site
```
**Includes:**
* Documentation expert agent
* Doc generation commands
* Mintlify/Docusaurus setup
* Search integration
* Versioning automation
E-commerce application setup
```bash theme={null}
npx claude-code-templates@latest --template ecommerce
```
**Includes:**
* Fullstack developer agent
* Payment integration MCPs
* Database architect agent
* Security hardening
* Performance optimization
SaaS application boilerplate
```bash theme={null}
npx claude-code-templates@latest --template saas-starter
```
**Includes:**
* Fullstack developer agent
* Authentication setup
* Subscription management
* Multi-tenancy architecture
* Analytics integration
Lightweight configuration with essentials
```bash theme={null}
npx claude-code-templates@latest --template minimal
```
**Includes:**
* Code architect agent
* Basic git hooks
* Essential commands
* Minimal dependencies
## Template Structure
Templates define components to install:
```json theme={null}
{
"name": "fullstack-web",
"description": "Complete fullstack web development setup",
"components": {
"agents": [
"frontend-developer",
"backend-developer",
"database-architect"
],
"commands": [
"setup-testing",
"security-audit",
"generate-docs"
],
"mcps": [
"neon",
"github"
],
"hooks": [
"git/conventional-commits",
"security/secret-scanner"
],
"settings": [
"git/auto-commit"
]
}
}
```
## How Templates Work
1. **Installation**: Template definition is read
2. **Component Resolution**: All listed components are identified
3. **Batch Install**: Components are installed in order
4. **Configuration**: Template-specific configs are applied
5. **Verification**: Installation is verified
## Customizing Templates
After installing a template, customize it:
```bash theme={null}
# Install template
npx claude-code-templates@latest --template fullstack-web
# Add additional components
npx claude-code-templates@latest --agent mobile-developer
# Remove unwanted components
rm .claude/agents/frontend-developer.md
```
## Template Benefits
### Consistency
* Standardized setups across projects
* Team alignment on tools and workflows
* Best practices baked in
### Speed
* Get started in seconds
* Pre-configured integrations
* No manual setup required
### Completeness
* All necessary components included
* Compatible component combinations
* Tested configurations
## Creating Custom Templates
Create your own templates:
1. Define component list
2. Test component combinations
3. Document template purpose
4. Share with your team
```json theme={null}
{
"name": "my-custom-template",
"description": "Custom setup for our team",
"components": {
"agents": ["..."],
"commands": ["..."],
"mcps": ["..."],
"hooks": ["..."],
"settings": ["..."]
}
}
```
## Template Use Cases
### New Projects
Start new projects with complete setup:
```bash theme={null}
npx claude-code-templates@latest --template saas-starter
```
### Team Onboarding
Get new team members set up quickly:
```bash theme={null}
npx claude-code-templates@latest --template team-standard
```
### Project Migration
Standardize existing projects:
```bash theme={null}
npx claude-code-templates@latest --template security-hardened
```
## Popular Templates
### Fullstack Web
Most comprehensive setup for web applications with frontend, backend, and database.
### Security Hardened
Maximum security for sensitive applications with audit trails and restrictions.
### Minimal Setup
Lightweight starter for simple projects or learning.
## Next Steps
* [Browse all templates at aitmpl.com](https://aitmpl.com/?type=templates)
* [View component library](/components/overview)
* [Learn about agents](/components/agents)
* [Explore commands](/components/commands)
# Agents
Source: https://davila7-claude-code-templates-86.mintlify.app/concepts/agents
AI specialists that extend Claude Code with domain expertise
Agents are specialized AI assistants with deep knowledge in specific domains. They act as expert team members, each with their own skills, tools, and workflows tailored to particular development tasks.
## What Are Agents?
Agents are markdown files (`.md`) stored in `.claude/agents/` that define:
* **Expertise area** - Domain knowledge and specialization
* **Tools** - Which Claude Code tools the agent can use
* **Model** - Which Claude model to use (sonnet, opus, haiku)
* **Instructions** - How the agent approaches tasks
* **Communication patterns** - How the agent interacts with users and other agents
Agents are essentially specialized prompts that Claude Code loads when invoked. They provide consistent, expert-level assistance for specific tasks.
## Agent Structure
Agents use YAML frontmatter followed by markdown instructions:
```markdown theme={null}
---
name: frontend-developer
description: Senior frontend developer specializing in React, Vue, and Angular
tools: Read, Write, Edit, Bash, Glob, Grep
model: sonnet
---
You are a senior frontend developer with expertise in modern web applications...
## Communication Protocol
Always begin by requesting project context from the context-manager...
## Execution Flow
1. Context Discovery
2. Development Execution
3. Handoff and Documentation
```
### Frontmatter Fields
| Field | Required | Description |
| ------------- | -------- | ---------------------------------------------- |
| `name` | Yes | Agent identifier (kebab-case) |
| `description` | Yes | Clear, specific description of agent's purpose |
| `tools` | Yes | Comma-separated list of allowed tools |
| `model` | Yes | `sonnet`, `opus`, or `haiku` |
## Agent Categories
Agents are organized by domain expertise:
Core development specialists:
* **frontend-developer** - React, Vue, Angular expert
* **backend-developer** - API and server-side development
* **fullstack-developer** - End-to-end application development
* **mobile-developer** - iOS and Android applications
* **devops-engineer** - Infrastructure and deployment
```bash theme={null}
npx claude-code-templates@latest --agent development-team/frontend-developer
```
Security and compliance specialists:
* **api-security-audit** - API security vulnerability assessment
* **security-auditor** - Comprehensive security reviews
* **penetration-tester** - Security testing and exploitation
* **compliance-validator** - GDPR, HIPAA, SOC2 compliance
```bash theme={null}
npx claude-code-templates@latest --agent security/api-security-audit
```
Database specialists:
* **postgresql-optimizer** - PostgreSQL performance tuning
* **mysql-expert** - MySQL schema design and optimization
* **mongodb-specialist** - NoSQL database management
* **redis-architect** - Caching and real-time features
```bash theme={null}
npx claude-code-templates@latest --agent database/postgresql-optimizer
```
AI and data science specialists:
* **ml-engineer** - Machine learning model development
* **data-scientist** - Data analysis and visualization
* **nlp-specialist** - Natural language processing
* **computer-vision** - Image and video processing
```bash theme={null}
npx claude-code-templates@latest --agent data-ai/ml-engineer
```
## Using Agents
### Installation
Install agents using the CLI:
```bash theme={null}
# Single agent
npx claude-code-templates@latest --agent frontend-developer
# Multiple agents
npx claude-code-templates@latest \
--agent frontend-developer \
--agent backend-developer \
--agent devops-engineer
# With category prefix
npx claude-code-templates@latest --agent development-team/frontend-developer
```
### Invocation
Once installed, agents are available in Claude Code:
```
@frontend-developer Build a responsive product catalog with filtering
```
Or reference them in conversations:
```
Use the frontend-developer agent to create the React components
```
Agents appear in Claude Code's agent picker automatically after installation.
## Real-World Examples
### Example 1: Frontend Developer Agent
**File**: `.claude/agents/frontend-developer.md`
````markdown theme={null}
---
name: frontend-developer
description: Use when building complete frontend applications across React, Vue, and Angular frameworks
tools: Read, Write, Edit, Bash, Glob, Grep
model: sonnet
---
You are a senior frontend developer specializing in modern web applications with deep expertise in React 18+, Vue 3+, and Angular 15+.
## Communication Protocol
### Required Initial Step: Project Context Gathering
Always begin by requesting project context from the context-manager:
```json
{
"requesting_agent": "frontend-developer",
"request_type": "get_project_context",
"payload": {
"query": "Frontend development context needed: current UI architecture, component ecosystem, design language"
}
}
````
## Execution Flow
1. **Context Discovery** - Map existing frontend landscape
2. **Development Execution** - Build components with TypeScript
3. **Handoff and Documentation** - Deliver with tests and docs
```
**Usage**:
```
@frontend-developer Create a dashboard with real-time data visualization using React and TypeScript
````
### Example 2: API Security Audit Agent
**File**: `.claude/agents/api-security-audit.md`
```markdown
---
name: api-security-audit
description: API security audit specialist. Use for REST API security audits, authentication vulnerabilities, authorization flaws
tools: Read, Write, Edit, Bash
model: sonnet
---
You are an API Security Audit specialist focusing on identifying, analyzing, and resolving security vulnerabilities in REST APIs.
## Core Expertise
- **Authentication Security**: JWT vulnerabilities, token management
- **Authorization Flaws**: RBAC issues, privilege escalation
- **Injection Attacks**: SQL injection, NoSQL injection prevention
- **Data Protection**: Sensitive data exposure, encryption
- **API Security Standards**: OWASP API Top 10
- **Compliance**: GDPR, HIPAA, PCI DSS requirements
## Security Audit Checklist
### Authentication & Authorization
```javascript
// Secure JWT implementation
const jwt = require('jsonwebtoken');
class AuthService {
generateToken(user) {
return jwt.sign(
{ userId: user.id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '15m', issuer: 'your-api' }
);
}
}
````
```
**Usage**:
```
@api-security-audit Review the authentication endpoints in src/api/auth.js
````
## Agent Communication Patterns
Agents can communicate with each other through structured protocols:
### Context Manager Integration
Most agents start by querying the `context-manager` for project information:
```json
{
"requesting_agent": "agent-name",
"request_type": "get_project_context",
"payload": {
"query": "Specific context needed"
}
}
````
This prevents redundant questions and ensures agents have full context.
### Agent-to-Agent Handoffs
Agents can delegate specialized tasks:
```
Status update from frontend-developer:
Components delivered. Requesting backend-developer to create API endpoints for data fetching.
```
## Tool Permissions
Agents specify which tools they need:
| Tool | Purpose |
| ------- | ------------------------------ |
| `Read` | Read files from the filesystem |
| `Write` | Create new files |
| `Edit` | Modify existing files |
| `Bash` | Execute shell commands |
| `Glob` | Find files by pattern |
| `Grep` | Search file contents |
Only grant agents the minimum tools they need. A documentation agent doesn't need `Bash` access.
## Model Selection
Choose the right model for each agent:
**Best for**: Most development tasks
* Balanced performance and cost
* 200K context window
* Strong coding capabilities
* Good for agents that need to read/write code
```yaml theme={null}
model: sonnet
```
**Best for**: Complex analysis and architecture
* Highest reasoning capability
* Large context handling
* Best for security audits, architecture reviews
* Higher cost per request
```yaml theme={null}
model: opus
```
**Best for**: Simple, fast tasks
* Fastest response times
* Lower cost
* Good for linting, formatting, simple edits
* Limited context window
```yaml theme={null}
model: haiku
```
## Creating Custom Agents
You can create your own agents:
Create `.claude/agents/my-agent.md`
Define name, description, tools, and model
Provide clear, specific instructions for the agent's behavior
Invoke the agent in Claude Code: `@my-agent Task description`
For detailed guidance on creating agents, see [Creating Components](/advanced/creating-components).
## Agent Best Practices
### 1. Clear Scope Definition
Define exactly when to use the agent:
```markdown theme={null}
## When to Use This Agent
Use this agent for:
- Comprehensive API security audits
- Authentication and authorization reviews
- Vulnerability assessments
Do NOT use for:
- General code review (use code-reviewer)
- Frontend security (use frontend-security-specialist)
```
### 2. Context Gathering
Always gather context before starting work:
* Query context-manager for project information
* Check existing patterns and conventions
* Validate assumptions with targeted questions
### 3. Structured Communication
Provide clear status updates:
```json theme={null}
{
"agent": "agent-name",
"update_type": "progress",
"current_task": "Task description",
"completed_items": ["Item 1", "Item 2"],
"next_steps": ["Next task"]
}
```
### 4. Documentation
Document all deliverables:
* File locations and purposes
* Integration points
* Configuration changes
* Next steps
## Global Agents
Create agents that work across all projects:
```bash theme={null}
# Create global agent
npx claude-code-templates@latest --create-agent my-global-agent
# List global agents
npx claude-code-templates@latest --list-agents
# Remove global agent
npx claude-code-templates@latest --remove-agent my-global-agent
```
Global agents are stored in `~/.claude/agents/` and available everywhere.
## Next Steps
Explore 400+ available agents
Build your own specialized agents
Learn about custom slash commands
Create globally accessible agents
# Commands
Source: https://davila7-claude-code-templates-86.mintlify.app/concepts/commands
Custom slash commands that extend Claude Code with specialized workflows
Commands are custom slash commands that provide Claude Code with specialized workflows, automation, and context-aware operations. They're like custom macros that execute complex tasks with a simple `/command` syntax.
## What Are Commands?
Commands are markdown files (`.md`) stored in `.claude/commands/` that define:
* **Workflow steps** - Automated sequences of operations
* **Context gathering** - What information to collect before execution
* **Tool usage** - Which Claude Code tools the command needs
* **Output format** - How results are presented
Commands appear in Claude Code's command palette (press `/`) and provide autocomplete with hints.
## Command Structure
Commands use YAML frontmatter followed by markdown instructions:
```markdown theme={null}
---
allowed-tools: Read, Write, Edit, Bash
argument-hint: [pipeline-name] | setup | status | fix
description: Manage and automate CI/CD pipeline configuration with GitHub Actions
---
# CI/CD Pipeline Manager
Manage CI/CD pipeline automation: $ARGUMENTS
## Current Pipeline State
- GitHub Actions: !`find .github/workflows -name "*.yml"`
- CI configuration: @.github/workflows/
- Package scripts: @package.json
## Task
Automate CI/CD pipeline management with comprehensive workflow orchestration.
## Pipeline Operations
### Setup New Pipeline
Create complete CI/CD pipeline with:
...
```
### Frontmatter Fields
| Field | Required | Description |
| --------------- | -------- | --------------------------------------------- |
| `allowed-tools` | Yes | Comma-separated list of tools command can use |
| `argument-hint` | No | Usage hint shown in autocomplete |
| `description` | Yes | Clear description of command's purpose |
### Special Syntax
Commands support special syntax for dynamic context:
* `$ARGUMENTS` - User-provided arguments after command name
* `@path/to/file` - Read and include file contents
* `!\`command\`\` - Execute shell command and include output
## Command Categories
Project setup and configuration commands:
* **setup-testing** - Configure testing framework (Jest, Vitest, etc.)
* **setup-linting** - Set up ESLint, Prettier, and code quality tools
* **setup-typescript** - Initialize TypeScript with optimal config
* **setup-docker** - Create Docker and docker-compose files
```bash theme={null}
npx claude-code-templates@latest --command setup/setup-testing
```
Usage:
```
/setup-testing jest
/setup-linting eslint+prettier
```
Git operations and workflow automation:
* **conventional-commits** - Format commits with conventional commit style
* **branch-strategy** - Implement git-flow or trunk-based development
* **pr-template** - Create pull request templates
* **changelog-generator** - Generate changelog from commits
```bash theme={null}
npx claude-code-templates@latest --command git-workflow/conventional-commits
```
Usage:
```
/conventional-commits feat: add user authentication
/changelog-generator v2.0.0
```
Deployment and infrastructure commands:
* **ci-pipeline** - GitHub Actions CI/CD pipeline setup
* **vercel-deploy** - Vercel deployment configuration
* **docker-deploy** - Docker deployment workflow
* **kubernetes-deploy** - Kubernetes manifests and deployment
```bash theme={null}
npx claude-code-templates@latest --command deployment/ci-pipeline
```
Usage:
```
/ci-pipeline setup
/vercel-deploy production
```
Database operations and migrations:
* **migration-create** - Create database migration files
* **seed-data** - Generate seed data for testing
* **schema-diff** - Compare database schemas
* **query-optimizer** - Analyze and optimize SQL queries
```bash theme={null}
npx claude-code-templates@latest --command database/migration-create
```
Usage:
```
/migration-create add_user_roles
/query-optimizer slow-queries.sql
```
Security analysis and hardening:
* **vulnerability-scan** - Scan dependencies for vulnerabilities
* **security-audit** - Comprehensive security review
* **secrets-check** - Find exposed secrets in code
* **permissions-audit** - Review access controls
```bash theme={null}
npx claude-code-templates@latest --command security/vulnerability-scan
```
Usage:
```
/vulnerability-scan
/security-audit src/api/
```
Documentation generation and maintenance:
* **api-docs** - Generate API documentation from code
* **readme-generator** - Create comprehensive README files
* **changelog-update** - Update changelog with recent changes
* **component-docs** - Document React/Vue components
```bash theme={null}
npx claude-code-templates@latest --command documentation/api-docs
```
Usage:
```
/api-docs src/api/
/readme-generator
```
## Real-World Example: CI/CD Pipeline Command
**File**: `.claude/commands/ci-pipeline.md`
````markdown theme={null}
---
allowed-tools: Read, Write, Edit, Bash
argument-hint: [pipeline-name] | setup | status | fix
description: Manage and automate CI/CD pipeline configuration with GitHub Actions
---
# CI/CD Pipeline Manager
Manage CI/CD pipeline automation: $ARGUMENTS
## Current Pipeline State
- GitHub Actions: !`find .github/workflows -name "*.yml" -o -name "*.yaml" 2>/dev/null | head -5`
- CI configuration: @.github/workflows/
- Package scripts: @package.json
- Recent workflow runs: !`gh run list --limit 5 2>/dev/null || echo "GitHub CLI not available"`
## Task
Automate CI/CD pipeline management with comprehensive workflow orchestration.
## Pipeline Operations
### Setup New Pipeline
Create complete CI/CD pipeline with:
```yaml
name: CI Pipeline
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18, 20]
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- run: npm ci
- run: npm run lint
- run: npm run test:coverage
- run: npm run build
````
### Multi-Environment Deployment
Configure staging and production deployments with environment-specific secrets.
### Security & Quality Gates
* Dependency vulnerability scanning
* Secret detection with TruffleHog
* SAST analysis with Super Linter
```
**Usage**:
```
/ci-pipeline setup
/ci-pipeline status
/ci-pipeline fix
````
## Dynamic Context Gathering
Commands can gather context dynamically:
### File References
Include file contents in command context:
```markdown
Current configuration: @.github/workflows/ci.yml
Package scripts: @package.json
````
When the command runs, Claude reads these files automatically.
### Shell Commands
Execute commands to gather system information:
```markdown theme={null}
Installed dependencies: !`npm list --depth=0`
Git status: !`git status --short`
Recent commits: !`git log --oneline -5`
```
Results are included in the command's context.
### User Arguments
Capture user input after the command:
```markdown theme={null}
Process user request: $ARGUMENTS
```
Usage: `/command arg1 arg2` makes `$ARGUMENTS` equal to "arg1 arg2".
## Using Commands
### Installation
```bash theme={null}
# Single command
npx claude-code-templates@latest --command ci-pipeline
# Multiple commands
npx claude-code-templates@latest \
--command ci-pipeline \
--command vulnerability-scan \
--command api-docs
# With category prefix
npx claude-code-templates@latest --command deployment/ci-pipeline
```
### Invocation
Commands appear in Claude Code's command palette:
```
/ci-pipeline setup
/vulnerability-scan
/api-docs src/api/
```
Press `/` in Claude Code to see all available commands with autocomplete.
## Command Best Practices
### 1. Clear Argument Hints
Provide helpful argument hints:
```yaml theme={null}
argument-hint: | list | status | rollback
```
Shows users exactly how to use the command.
### 2. Context Before Action
Gather context before executing:
```markdown theme={null}
## Current State
- Project type: @package.json
- Existing config: @.eslintrc.js
- Git status: !`git status --short`
```
### 3. Clear Sections
Organize commands into logical sections:
```markdown theme={null}
## Current State
[Context gathering]
## Task
[What the command does]
## Operations
[How to execute]
## Examples
[Usage examples]
```
### 4. Error Handling
Include fallbacks for missing tools:
```markdown theme={null}
Recent runs: !`gh run list --limit 5 2>/dev/null || echo "GitHub CLI not available"`
```
### 5. Tool Permissions
Only request necessary tools:
```yaml theme={null}
allowed-tools: Read, Write, Edit # No Bash if not needed
```
## Creating Custom Commands
Create `.claude/commands/my-command.md`
Define tools, arguments, and description
```yaml theme={null}
---
allowed-tools: Read, Write, Edit, Bash
argument-hint: [options]
description: My custom command for specific workflow
---
```
Specify what information to gather:
```markdown theme={null}
## Current State
- Project files: !`ls -la`
- Config: @config.json
```
Provide clear steps for execution:
```markdown theme={null}
## Task
Execute workflow: $ARGUMENTS
## Steps
1. Analyze current state
2. Execute operation
3. Validate results
```
Use the command in Claude Code:
```
/my-command test
```
## Command vs Agent
When to use commands vs agents:
| Use Command | Use Agent |
| ----------------------------- | ---------------------------- |
| Specific workflow automation | General expertise domain |
| One-time operations | Ongoing conversation |
| Context + instructions format | Natural language interaction |
| `/command syntax` | `@agent syntax` |
Commands are great for repeatable workflows. Agents are better for exploratory tasks and ongoing assistance.
## Advanced Features
### Conditional Execution
Commands can include conditional logic:
```markdown theme={null}
If TypeScript project (@tsconfig.json exists):
- Use TypeScript configuration
Else:
- Use JavaScript configuration
```
### Multi-Tool Workflows
Combine tools for complex operations:
```markdown theme={null}
1. Read current config (Read)
2. Generate new config (Edit)
3. Install dependencies (Bash)
4. Validate setup (Bash)
```
### Integration with Hooks
Commands can be triggered by hooks:
```json theme={null}
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit",
"hooks": [{
"type": "command",
"command": "/validate-code"
}]
}]
}
}
```
## Next Steps
Explore 225+ available commands
Build your own commands
Automate command execution
Combine commands into workflows
# Component System
Source: https://davila7-claude-code-templates-86.mintlify.app/concepts/components
Understanding the Claude Code Templates component architecture
Claude Code Templates provides a powerful component-based system that extends Claude Code with specialized capabilities. Components are modular, reusable building blocks that you can install individually or in batches to enhance your development workflow.
## What Are Components?
Components are pre-built configurations, scripts, and AI specialists that integrate seamlessly with Claude Code. Think of them as plugins that add new capabilities to your AI coding assistant.
AI specialists for every development task
Custom slash commands for workflows
Model Context Protocol integrations
Configuration files for Claude Code
Event-driven automation triggers
Complete project configurations
## Component Architecture
All components live in the `.claude` directory within your project:
```bash theme={null}
.claude/
├── agents/ # AI specialist agents
├── commands/ # Slash command definitions
├── hooks/ # Automation scripts
├── scripts/ # Supporting files for hooks/statuslines
├── settings.json # Project-wide configuration (committed to git)
├── settings.local.json # Personal settings (not committed)
└── .mcp.json # MCP server configurations (project root)
```
The `.claude` directory structure is automatically created when you install your first component.
## Installation Methods
Claude Code Templates supports multiple installation approaches:
Install one component at a time:
```bash theme={null}
npx claude-code-templates@latest --agent frontend-developer
npx claude-code-templates@latest --command ci-pipeline
npx claude-code-templates@latest --mcp web-fetch
```
Install multiple components in one command:
```bash theme={null}
npx claude-code-templates@latest \
--agent security-auditor \
--command security-audit \
--setting read-only-mode
```
Use the interactive menu for guided installation:
```bash theme={null}
npx claude-code-templates@latest
```
Navigate through categories and select components visually.
## Component Categories
Components are organized by type and purpose:
### Agents
AI specialists with domain expertise. Examples:
* **development-team/frontend-developer** - React, Vue, Angular expert
* **security/api-security-audit** - API security specialist
* **database/postgresql-optimizer** - Database performance tuning
### Commands
Slash commands for common workflows. Examples:
* **setup/ci-pipeline** - GitHub Actions automation
* **security/vulnerability-scan** - Security analysis
* **git-workflow/conventional-commits** - Commit message formatting
### MCPs
Model Context Protocol integrations for external services:
* **web/web-fetch** - HTTP requests and web scraping
* **database/postgresql-integration** - Direct database access
* **browser\_automation/playwright** - Browser automation
### Hooks
Event-driven automation that runs before/after tool use:
* **git/git-commit-formatter** - Format commits automatically
* **automation/build-on-change** - Auto-build on file edits
* **security/prevent-force-push** - Block dangerous git operations
### Settings
Configuration files for permissions, models, and behavior:
* **permissions/allow-npm-commands** - Enable npm command execution
* **model/use-sonnet** - Default to Claude Sonnet model
* **statusline/context-monitor** - Real-time context usage tracking
### Templates
Complete project configurations with multiple components:
* **development/react-typescript** - React + TypeScript stack
* **security/security-first** - Security-hardened configuration
* **workflow-automation/git-excellence** - Git workflow automation
## Component Lifecycle
Browse components at [aitmpl.com](https://aitmpl.com) or use the CLI's interactive mode.
Components are downloaded from GitHub and installed to `.claude/` directory.
Settings merge with existing configurations. Choose installation location (user/project/local).
Components are immediately available in Claude Code. No restart required.
Re-run installation command to update components to latest version.
## Component Naming Conventions
All components follow consistent naming patterns:
* **Kebab-case**: `frontend-developer`, `ci-pipeline`, `web-fetch`
* **Category prefixes**: `category/component-name` (e.g., `security/api-security-audit`)
* **Descriptive**: Names clearly indicate purpose and functionality
When installing components with category prefixes (e.g., `development-team/frontend-developer`), the component is installed to the flat `.claude/agents/` directory without category subdirectories.
## Component Configuration
Components can be configured through three settings levels:
1. **User settings** (`~/.claude/settings.json`) - Apply to all projects
2. **Project settings** (`.claude/settings.json`) - Shared with team (committed)
3. **Local settings** (`.claude/settings.local.json`) - Personal overrides (not committed)
Settings cascade from user → project → local, with later settings overriding earlier ones.
## Component Compatibility
Components are designed to work together:
* **Agents** can use **commands** to perform specialized workflows
* **Hooks** can trigger **commands** automatically
* **MCPs** provide data and services that **agents** leverage
* **Settings** control behavior of all component types
* **Templates** bundle multiple components for specific use cases
## Next Steps
Learn about AI specialist agents
Build custom slash commands
Integrate external services
Set up event-driven automation
# Hooks
Source: https://davila7-claude-code-templates-86.mintlify.app/concepts/hooks
Event-driven automation that triggers actions before and after tool use
Hooks are event-driven automation triggers that execute actions automatically when Claude Code uses tools. They enable you to automate repetitive tasks, enforce standards, and create seamless workflows without manual intervention.
## What Are Hooks?
Hooks are JSON configuration files (`.json`) stored in `.claude/hooks/` that define:
* **Trigger events** - When the hook should run (before/after tool use)
* **Matchers** - Which tools trigger the hook (Edit, Bash, Write, etc.)
* **Actions** - What to execute (commands, scripts, notifications)
* **Conditions** - Optional filters for selective triggering
Hooks run automatically in the background. Claude Code executes them without requiring user interaction.
## Hook Types
Claude Code supports two main hook types:
**PreToolUse** hooks run BEFORE Claude executes a tool.
Use cases:
* Validate operations before execution
* Create backups before edits
* Check permissions before dangerous operations
* Block operations that violate policies
```json theme={null}
{
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "echo 'About to run bash command'"
}]
}]
}
}
```
**PostToolUse** hooks run AFTER Claude completes a tool operation.
Use cases:
* Auto-format code after edits
* Run tests after changes
* Commit changes automatically
* Send notifications
* Trigger builds
```json theme={null}
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit",
"hooks": [{
"type": "command",
"command": "npm run format"
}]
}]
}
}
```
## Hook Structure
Hooks are configured in settings files (`.claude/settings.json` or `.claude/settings.local.json`):
```json theme={null}
{
"description": "Hook description",
"hooks": {
"PostToolUse": [
{
"matcher": "Edit",
"hooks": [
{
"type": "command",
"command": "npm run build"
}
]
}
]
}
}
```
### Hook Fields
| Field | Required | Description |
| ------------- | -------- | -------------------------------------------------------- |
| `matcher` | Yes | Which tool triggers this hook (Edit, Bash, Write, etc.) |
| `type` | Yes | Hook type: `command` or `script` |
| `command` | Yes | Shell command or script to execute |
| `description` | No | Human-readable description (removed during installation) |
## Tool Matchers
Hooks can match specific Claude Code tools:
| Matcher | Triggers On |
| ------- | ----------------------- |
| `Edit` | File edits |
| `Write` | File creation |
| `Bash` | Shell command execution |
| `Read` | File reads |
| `Glob` | File pattern searches |
| `Grep` | Content searches |
Use specific matchers to avoid unnecessary hook execution. Matching `Edit` won't trigger on `Bash` commands.
## Hook Categories
Automate git operations:
* **git-commit-formatter** - Format commit messages automatically
* **prevent-force-push** - Block dangerous git operations
* **auto-add-changes** - Stage changes automatically
* **commit-msg-validator** - Enforce commit message standards
```bash theme={null}
npx claude-code-templates@latest --hook git/git-commit-formatter
```
Example:
```json theme={null}
{
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "if [[ $BASH_COMMAND =~ 'git push --force' ]]; then echo 'Force push blocked'; exit 1; fi"
}]
}]
}
}
```
Maintain code standards:
* **format-on-save** - Auto-format code after edits
* **lint-on-change** - Run linters automatically
* **run-tests** - Execute tests after code changes
* **type-check** - Run TypeScript checks
```bash theme={null}
npx claude-code-templates@latest --hook automation/format-on-save
```
Example:
```json theme={null}
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit",
"hooks": [{
"type": "command",
"command": "npx prettier --write $FILE_PATH"
}]
}]
}
}
```
Trigger builds automatically:
* **build-on-change** - Auto-build when files change
* **watch-mode** - Start development server
* **asset-optimization** - Optimize images/assets
* **cache-invalidation** - Clear caches after builds
```bash theme={null}
npx claude-code-templates@latest --hook automation/build-on-change
```
Example:
```json theme={null}
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit",
"hooks": [{
"type": "command",
"command": "if [[ -f package.json ]]; then npm run build 2>/dev/null || true; fi"
}]
}]
}
}
```
Enforce security policies:
* **secret-scanner** - Detect exposed secrets
* **dependency-audit** - Check for vulnerabilities
* **permission-validator** - Verify file permissions
* **sensitive-file-blocker** - Prevent access to sensitive files
```bash theme={null}
npx claude-code-templates@latest --hook security/secret-scanner
```
Example:
```json theme={null}
{
"hooks": {
"PostToolUse": [{
"matcher": "Write",
"hooks": [{
"type": "command",
"command": "trufflehog git file://$FILE_PATH"
}]
}]
}
}
```
Get notified of important events:
* **slack-notifier** - Send Slack messages
* **discord-webhook** - Discord notifications
* **email-alerts** - Email notifications
* **desktop-notifications** - System notifications
```bash theme={null}
npx claude-code-templates@latest --hook automation/slack-notifier
```
Example:
```json theme={null}
{
"hooks": {
"PostToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "curl -X POST $SLACK_WEBHOOK -d '{\"text\":\"Command executed\"}'"
}]
}]
}
}
```
## Real-World Examples
### Example 1: Build on Change Hook
**File**: Component downloaded to settings file
```json theme={null}
{
"description": "Automatically trigger build processes when source files change",
"hooks": {
"PostToolUse": [
{
"matcher": "Edit",
"hooks": [
{
"type": "command",
"command": "if [[ -f package.json ]] && grep -q '\"build\"' package.json; then npm run build 2>/dev/null || yarn build 2>/dev/null || true; elif [[ -f Makefile ]]; then make 2>/dev/null || true; elif [[ -f Cargo.toml ]]; then cargo build 2>/dev/null || true; fi"
}
]
}
]
}
}
```
**Behavior**:
* Triggers after every file edit
* Detects build tool (npm, make, cargo, etc.)
* Runs appropriate build command
* Silent failures (|| true) prevent interruptions
### Example 2: Git Commit Validator Hook
**File**: Component configuration
```json theme={null}
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "if [[ $BASH_COMMAND =~ 'git commit' ]] && [[ ! $BASH_COMMAND =~ '(feat|fix|docs|style|refactor|test|chore):' ]]; then echo 'Error: Commit message must follow conventional commits format'; exit 1; fi"
}
]
}
]
}
}
```
**Behavior**:
* Runs before bash commands
* Checks if command is `git commit`
* Validates conventional commit format
* Blocks commit if format is invalid
### Example 3: Python Script Hook
Some hooks reference external Python scripts:
**Hook Configuration**:
```json theme={null}
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit",
"hooks": [{
"type": "command",
"command": "python3 .claude/hooks/custom-formatter.py $FILE_PATH"
}]
}]
}
}
```
**Supporting Script**: `.claude/hooks/custom-formatter.py`
The CLI automatically downloads supporting scripts when installing hooks.
## Installing Hooks
### Single Hook
```bash theme={null}
npx claude-code-templates@latest --hook git/git-commit-formatter
```
You'll be prompted to choose installation location:
* **User settings** (`~/.claude/settings.json`) - All projects
* **Project settings** (`.claude/settings.json`) - Shared with team
* **Local settings** (`.claude/settings.local.json`) - Personal only
### Multiple Hooks
```bash theme={null}
npx claude-code-templates@latest \
--hook git/git-commit-formatter \
--hook automation/build-on-change \
--hook security/secret-scanner
```
### With Category Prefix
```bash theme={null}
npx claude-code-templates@latest --hook automation/build-on-change
```
Hooks merge with existing settings. Multiple hooks can trigger on the same tool.
## Hook Execution Context
Hooks have access to context variables:
### Environment Variables
| Variable | Description |
| --------------- | ------------------------------------------ |
| `$FILE_PATH` | Path to file being operated on |
| `$TOOL_NAME` | Name of tool that triggered hook |
| `$PROJECT_ROOT` | Project root directory |
| `$BASH_COMMAND` | Command being executed (Bash matcher only) |
Example usage:
```bash theme={null}
echo "File modified: $FILE_PATH"
notify-send "Claude Code" "Tool $TOOL_NAME executed"
```
## Hook Best Practices
### 1. Silent Failures
Prevent hooks from interrupting workflow:
```bash theme={null}
npm run build 2>/dev/null || true
```
The `|| true` ensures the hook never fails.
### 2. Conditional Execution
Only run when necessary:
```bash theme={null}
if [[ -f package.json ]] && grep -q '"test"' package.json; then
npm test
fi
```
### 3. Fast Operations
Hooks should be quick:
```bash theme={null}
# ✅ Good: Fast check
eslint $FILE_PATH
# ❌ Bad: Slow operation
npm run test:all # Runs entire test suite
```
### 4. Idempotent Actions
Hooks should be safe to run multiple times:
```bash theme={null}
# ✅ Good: Safe to repeat
npm run format $FILE_PATH
# ⚠️ Caution: May cause issues
git commit -m "Auto commit" # Creates duplicate commits
```
### 5. Error Handling
Handle errors gracefully:
```bash theme={null}
if ! command -v prettier &> /dev/null; then
echo "Prettier not installed, skipping format"
exit 0
fi
prettier --write $FILE_PATH
```
## Hook Debugging
Debug hooks by adding logging:
```bash theme={null}
echo "Hook triggered: $TOOL_NAME on $FILE_PATH" >> /tmp/hook.log
```
Or use verbose output:
```bash theme={null}
set -x # Enable verbose mode
npm run build
set +x # Disable verbose mode
```
## Disabling Hooks
Temporarily disable hooks:
### Per-Session
Set environment variable:
```bash theme={null}
export CLAUDE_DISABLE_HOOKS=true
```
### Permanent
Remove hook configuration from settings file or comment out:
```json theme={null}
{
"hooks": {
// "PostToolUse": [ ... ] // Disabled
}
}
```
## Hook vs Command
| Hooks | Commands |
| ----------------------- | ----------------- |
| Automatic execution | Manual invocation |
| Event-driven | User-initiated |
| Background operation | Interactive |
| Simple commands/scripts | Complex workflows |
| No user input | Accepts arguments |
Hooks automate repetitive tasks. Commands handle complex workflows that need user input.
## Advanced Hook Patterns
### Chained Hooks
Multiple hooks on same matcher:
```json theme={null}
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit",
"hooks": [
{ "type": "command", "command": "npm run format" },
{ "type": "command", "command": "npm run lint" },
{ "type": "command", "command": "git add $FILE_PATH" }
]
}]
}
}
```
Hooks run sequentially in order.
### Conditional Hooks
Use shell conditionals:
```json theme={null}
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit",
"hooks": [{
"type": "command",
"command": "if [[ $FILE_PATH =~ \\.test\\. ]]; then npm test; fi"
}]
}]
}
}
```
Only runs tests if file is a test file.
### Hook with External Scripts
Call custom scripts:
```json theme={null}
{
"hooks": {
"PostToolUse": [{
"matcher": "Write",
"hooks": [{
"type": "command",
"command": "bash .claude/hooks/post-write.sh $FILE_PATH"
}]
}]
}
}
```
Keep complex logic in external scripts for maintainability.
## Common Hook Recipes
### Auto-format Python
```json theme={null}
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit",
"hooks": [{
"type": "command",
"command": "if [[ $FILE_PATH =~ \\.py$ ]]; then black $FILE_PATH 2>/dev/null || true; fi"
}]
}]
}
}
```
### Run Tests on Change
```json theme={null}
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit",
"hooks": [{
"type": "command",
"command": "if [[ $FILE_PATH =~ src/ ]]; then npm run test:related $FILE_PATH 2>/dev/null || true; fi"
}]
}]
}
}
```
### Notify on Bash Execution
```json theme={null}
{
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "notify-send 'Claude Code' 'Executing: $BASH_COMMAND'"
}]
}]
}
}
```
## Next Steps
Explore 45+ available hooks
Build your own automation
Configure hook behavior
Learn about slash commands
# Model Context Protocol (MCP)
Source: https://davila7-claude-code-templates-86.mintlify.app/concepts/mcps
Integrate external services and tools with Claude Code through MCP servers
Model Context Protocol (MCP) is an open standard that enables Claude Code to connect with external data sources, APIs, and services. MCP servers act as bridges between Claude and the outside world.
## What Are MCPs?
MCPs are JSON configuration files (`.json`) that define server connections:
* **Server configuration** - How to start and connect to MCP servers
* **Command and arguments** - What to execute (npm packages, binaries, scripts)
* **Environment variables** - Configuration and API keys
* **Capabilities** - What tools and resources the server provides
MCP servers run as separate processes and communicate with Claude Code via stdio (standard input/output).
## MCP Architecture
MCP configuration lives in `.mcp.json` at your project root:
```json theme={null}
{
"mcpServers": {
"fetch": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-fetch"]
},
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"POSTGRES_CONNECTION_STRING": "postgresql://user:pass@localhost/db"
}
}
}
}
```
### Configuration Structure
| Field | Required | Description |
| ------------- | -------- | -------------------------------------------------------- |
| `command` | Yes | Executable to run (e.g., `npx`, `node`, `python`) |
| `args` | Yes | Array of command arguments |
| `env` | No | Environment variables for the server |
| `description` | No | Human-readable description (removed during installation) |
## MCP Categories
Access web content and external APIs:
* **web-fetch** - HTTP requests, web scraping, API calls
* **github-integration** - GitHub API access (repos, issues, PRs)
* **slack-integration** - Slack API for messages and channels
```bash theme={null}
npx claude-code-templates@latest --mcp web/web-fetch
```
**Capabilities**:
* Fetch web pages and parse HTML
* Make REST API requests
* Download files and images
* Parse JSON and XML responses
Direct database access and queries:
* **postgresql-integration** - PostgreSQL database access
* **mysql-integration** - MySQL database operations
* **supabase** - Supabase client with auth and storage
* **neon** - Neon serverless Postgres
```bash theme={null}
npx claude-code-templates@latest --mcp database/postgresql-integration
```
**Capabilities**:
* Execute SQL queries
* Inspect database schemas
* Run migrations
* Analyze query performance
Code analysis and development utilities:
* **deepgraph-react** - React component analysis
* **deepgraph-nextjs** - Next.js project insights
* **deepgraph-typescript** - TypeScript codebase analysis
* **sentry** - Error tracking and monitoring
```bash theme={null}
npx claude-code-templates@latest --mcp devtools/deepgraph-react
```
**Capabilities**:
* Analyze component dependencies
* Find unused code
* Track imports and exports
* Visualize code structure
Headless browser control:
* **playwright** - Browser automation with Playwright
* **puppeteer** - Chrome automation
* **selenium** - Multi-browser automation
```bash theme={null}
npx claude-code-templates@latest --mcp browser_automation/playwright
```
**Capabilities**:
* Navigate web pages
* Fill forms and click buttons
* Take screenshots
* Extract data from dynamic sites
Enhanced file operations:
* **filesystem-access** - Extended file system operations
* **memory-integration** - Persistent memory and notes
```bash theme={null}
npx claude-code-templates@latest --mcp filesystem/filesystem-access
```
**Capabilities**:
* Read/write files with advanced options
* Watch file changes
* Search file contents
* Manage permissions
Note-taking and productivity tools:
* **obsidian** - Obsidian vault access
* **notion** - Notion workspace integration
* **google-drive** - Google Drive file access
```bash theme={null}
npx claude-code-templates@latest --mcp productivity/obsidian
```
**Capabilities**:
* Read/write notes
* Search across documents
* Manage tags and links
* Export content
## Real-World Examples
### Example 1: Web Fetch MCP
**File**: `.mcp.json`
```json theme={null}
{
"mcpServers": {
"fetch": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-fetch"]
}
}
}
```
**Usage in Claude Code**:
```
Fetch the latest release notes from https://api.github.com/repos/anthropics/claude-code/releases/latest
```
Claude automatically uses the MCP server to make the HTTP request.
### Example 2: PostgreSQL Database MCP
**File**: `.mcp.json`
```json theme={null}
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"POSTGRES_CONNECTION_STRING": "postgresql://localhost/mydb"
}
}
}
}
```
**Usage in Claude Code**:
```
Query the users table and show me all users created in the last 7 days
```
Claude connects to PostgreSQL and executes the query.
### Example 3: GitHub Integration MCP
**File**: `.mcp.json`
```json theme={null}
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "ghp_your_token_here"
}
}
}
}
```
**Usage in Claude Code**:
```
List all open issues in the main repository and summarize the top 3 by reactions
```
Claude uses the GitHub API via MCP to fetch and analyze issues.
## Installing MCPs
### Single MCP
```bash theme={null}
npx claude-code-templates@latest --mcp web-fetch
```
The MCP configuration merges with your existing `.mcp.json`.
### Multiple MCPs
```bash theme={null}
npx claude-code-templates@latest \
--mcp web-fetch \
--mcp postgresql-integration \
--mcp github-integration
```
### With Category Prefix
```bash theme={null}
npx claude-code-templates@latest --mcp database/postgresql-integration
```
MCP servers are downloaded on-demand when first used. No manual installation required beyond configuration.
## Environment Variables
Many MCPs require API keys or connection strings:
### Secure Configuration
**DON'T** hardcode secrets:
```json theme={null}
{
"env": {
"API_KEY": "sk-1234567890" // ❌ Bad: exposed in git
}
}
```
**DO** use environment variables:
```json theme={null}
{
"env": {
"API_KEY": "${API_KEY}" // ✅ Good: reads from shell environment
}
}
```
Set variables in your shell:
```bash theme={null}
export API_KEY="sk-1234567890"
```
Or use `.env` files (add to `.gitignore`):
```bash theme={null}
# .env
POSTGRES_CONNECTION_STRING=postgresql://localhost/db
GITHUB_TOKEN=ghp_your_token
```
Never commit API keys, database passwords, or tokens to version control. Use environment variables or secret management tools.
## MCP Server Types
### NPM Packages
Most official MCPs are npm packages:
```json theme={null}
{
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-name"]
}
```
The `-y` flag auto-installs packages without prompting.
### Python Scripts
```json theme={null}
{
"command": "python",
"args": ["-m", "mcp_server_name"]
}
```
Requires the Python package to be installed: `pip install mcp-server-name`
### Custom Executables
```json theme={null}
{
"command": "/path/to/custom-server",
"args": ["--config", "./config.json"]
}
```
### Docker Containers
```json theme={null}
{
"command": "docker",
"args": [
"run",
"--rm",
"-i",
"custom/mcp-server:latest"
]
}
```
## MCP Capabilities
MCP servers can provide:
### 1. Tools
Functions that Claude can call:
```typescript theme={null}
// Example: web-fetch provides
fetch(url: string, options?: RequestInit)
html_to_markdown(html: string)
download_file(url: string, path: string)
```
### 2. Resources
Data that Claude can read:
```typescript theme={null}
// Example: postgres provides
schema://tables // List all tables
schema://tables/{name} // Table schema
query://{sql} // Query results
```
### 3. Prompts
Pre-built prompt templates:
```typescript theme={null}
// Example: github provides
analyze-repo // Analyze repository structure
review-pr // Review pull request
```
## Creating Custom MCP Servers
You can build custom MCP servers:
Use the MCP SDK for TypeScript or Python:
```bash theme={null}
npm install @modelcontextprotocol/sdk
```
Create server with tools and resources:
```typescript theme={null}
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
const server = new Server({
name: 'my-server',
version: '1.0.0'
});
server.tool('my-tool', async (args) => {
// Tool implementation
return { result: 'success' };
});
```
Add your server configuration:
```json theme={null}
{
"mcpServers": {
"my-server": {
"command": "node",
"args": ["./mcp-servers/my-server.js"]
}
}
}
```
Use your custom server in Claude Code:
```
Use my-tool to process the data
```
For detailed MCP development guides, see [MCP Documentation](https://modelcontextprotocol.io).
## MCP Best Practices
### 1. Security First
* Never hardcode credentials
* Use environment variables for secrets
* Validate all inputs
* Limit server permissions
* Use read-only access when possible
### 2. Error Handling
Servers should handle errors gracefully:
```typescript theme={null}
server.tool('fetch-data', async (args) => {
try {
const response = await fetch(args.url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (error) {
return {
error: true,
message: error.message
};
}
});
```
### 3. Resource Management
* Close connections properly
* Implement timeouts
* Clean up resources
* Handle server shutdown gracefully
### 4. Documentation
Document your MCP tools clearly:
```typescript theme={null}
server.tool(
'search-database',
{
description: 'Search database with SQL query',
parameters: {
query: { type: 'string', description: 'SQL query to execute' },
limit: { type: 'number', description: 'Max results', default: 100 }
}
},
async (args) => { /* ... */ }
);
```
## Troubleshooting MCPs
### Server Won't Start
Check the command and arguments:
```json theme={null}
{
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-fetch"]
}
```
Test manually:
```bash theme={null}
npx -y @modelcontextprotocol/server-fetch
```
### Environment Variables Not Working
Ensure variables are exported:
```bash theme={null}
export DATABASE_URL="postgresql://localhost/db"
echo $DATABASE_URL # Should print the URL
```
Check variable syntax:
```json theme={null}
{
"env": {
"DATABASE_URL": "${DATABASE_URL}" // Must use ${VAR} syntax
}
}
```
### Connection Errors
Verify network access:
* Database servers are running
* Firewall allows connections
* Credentials are correct
* Connection strings are properly formatted
### Permission Denied
Ensure executable permissions:
```bash theme={null}
chmod +x ./mcp-servers/my-server.js
```
## MCP vs Claude Code Tools
| MCP Servers | Claude Code Tools |
| ----------------------- | --------------------- |
| External services | Built-in capabilities |
| Requires configuration | Always available |
| Custom capabilities | Standard operations |
| Network/database access | File system access |
| Community-built | Official tools |
MCPs extend Claude's capabilities beyond the built-in tools. Use them to connect Claude with your specific services and data sources.
## Official MCP Servers
Anthropics maintains official MCP servers:
* `@modelcontextprotocol/server-fetch` - HTTP requests
* `@modelcontextprotocol/server-filesystem` - File operations
* `@modelcontextprotocol/server-github` - GitHub API
* `@modelcontextprotocol/server-postgres` - PostgreSQL
* `@modelcontextprotocol/server-sqlite` - SQLite
Browse all at [MCP Registry](https://github.com/modelcontextprotocol/servers).
## Next Steps
Explore 65+ available MCPs
Official MCP specification
Build custom MCP servers
Configure Claude Code behavior
# Settings
Source: https://davila7-claude-code-templates-86.mintlify.app/concepts/settings
Configure Claude Code behavior with permissions, models, and automation
Settings control how Claude Code behaves in your projects. They define permissions, model preferences, environment variables, hook configurations, and advanced features like status lines and context monitoring.
## What Are Settings?
Settings are JSON configuration files that customize Claude Code:
* **Permissions** - What Claude can and cannot do
* **Environment variables** - Configuration values and secrets
* **Hooks** - Event-driven automation
* **Model preferences** - Which Claude model to use
* **Status lines** - Real-time monitoring and feedback
* **Advanced features** - Telemetry, retention, and more
Settings cascade from user → project → local, with later settings overriding earlier ones.
## Settings Hierarchy
Claude Code uses three levels of settings:
**Location**: `~/.claude/settings.json`
**Scope**: All projects for the current user
**Use for**:
* Personal preferences (editor, model)
* Global API keys
* User-specific automation
```bash theme={null}
# Install to user settings
npx claude-code-templates@latest --setting use-sonnet
# Choose "User settings" when prompted
```
**Committed**: No (personal file)
**Location**: `.claude/settings.json`
**Scope**: Current project, shared with team
**Use for**:
* Team conventions
* Project-specific permissions
* Shared automation
* CI/CD configuration
```bash theme={null}
# Install to project settings
npx claude-code-templates@latest --setting allow-npm-commands
# Choose "Project settings" when prompted
```
**Committed**: Yes (shared with team via git)
**Location**: `.claude/settings.local.json`
**Scope**: Current project, personal overrides
**Use for**:
* Personal overrides for project settings
* Local API keys and secrets
* Development-only hooks
```bash theme={null}
# Install to local settings (default)
npx claude-code-templates@latest --setting context-monitor
# Choose "Local settings" when prompted
```
**Committed**: No (add to `.gitignore`)
Local settings override project settings, which override user settings. This allows personal customization without affecting the team.
## Settings Structure
Settings files use JSON format:
```json theme={null}
{
"permissions": {
"allow": ["Bash(npm run test)"],
"deny": ["Bash(rm -rf)"],
"ask": ["Bash(git push)"]
},
"env": {
"NODE_ENV": "development",
"API_KEY": "${API_KEY}"
},
"hooks": {
"PostToolUse": [{
"matcher": "Edit",
"hooks": [{
"type": "command",
"command": "npm run format"
}]
}]
},
"statusLine": {
"type": "command",
"command": "python3 .claude/scripts/context-monitor.py"
},
"model": "sonnet",
"telemetry": true
}
```
## Settings Categories
Control what Claude can execute:
* **allow-npm-commands** - Enable npm/yarn operations
* **read-only-mode** - Prevent all file modifications
* **deny-sensitive-files** - Block access to secrets
* **allow-git-operations** - Enable git commands
```bash theme={null}
npx claude-code-templates@latest --setting permissions/allow-npm-commands
```
**Configuration**:
```json theme={null}
{
"permissions": {
"allow": [
"Bash(npm run lint)",
"Bash(npm run test:*)",
"Bash(npm run build)",
"Bash(npm start)"
]
}
}
```
**Permission Types**:
* `allow` - Always permit these operations
* `deny` - Always block these operations
* `ask` - Prompt user before executing
Choose which Claude model to use:
* **use-sonnet** - Claude 3.5 Sonnet (balanced, default)
* **use-opus** - Claude 3 Opus (most capable)
* **use-haiku** - Claude 3.5 Haiku (fastest, cheapest)
```bash theme={null}
npx claude-code-templates@latest --setting model/use-sonnet
```
**Configuration**:
```json theme={null}
{
"model": "sonnet"
}
```
**Model Comparison**:
| Model | Speed | Cost | Best For |
| ------ | -------- | ------- | ------------------------------ |
| Haiku | Fastest | Lowest | Simple tasks, formatting |
| Sonnet | Balanced | Medium | Most development work |
| Opus | Slowest | Highest | Complex analysis, architecture |
Real-time monitoring and feedback:
* **context-monitor** - Track context usage with progress bars
* **token-counter** - Display token consumption
* **session-tracker** - Monitor session duration and cost
```bash theme={null}
npx claude-code-templates@latest --setting statusline/context-monitor
```
**Configuration**:
```json theme={null}
{
"statusLine": {
"type": "command",
"command": "python3 .claude/scripts/context-monitor.py"
}
}
```
**Features**:
* Visual progress bars
* Color-coded alerts (green/yellow/red)
* Session analytics (cost, duration, lines changed)
* Auto-compact warnings
Set environment variables:
* **env-development** - Development environment vars
* **env-production** - Production configuration
* **api-keys** - External service credentials
```bash theme={null}
npx claude-code-templates@latest --setting environment/env-development
```
**Configuration**:
```json theme={null}
{
"env": {
"NODE_ENV": "development",
"DEBUG": "true",
"API_URL": "http://localhost:3000",
"DATABASE_URL": "${DATABASE_URL}"
}
}
```
Never hardcode secrets. Use `${VAR}` syntax to reference shell environment variables.
Control usage tracking:
* **enable-telemetry** - Send anonymous usage data
* **disable-telemetry** - Opt out of tracking
```bash theme={null}
npx claude-code-templates@latest --setting telemetry/disable-telemetry
```
**Configuration**:
```json theme={null}
{
"telemetry": false
}
```
Telemetry helps improve Claude Code but is optional.
Control conversation history:
* **retention-7-days** - Keep 7 days of history
* **retention-30-days** - Keep 30 days of history
* **retention-90-days** - Keep 90 days of history
```bash theme={null}
npx claude-code-templates@latest --setting cleanup/retention-7-days
```
**Configuration**:
```json theme={null}
{
"retention": {
"days": 7,
"autoCleanup": true
}
}
```
Automatically removes old conversations to save disk space.
## Real-World Examples
### Example 1: Allow NPM Commands
**File**: Settings configuration
```json theme={null}
{
"description": "Allow common npm development commands (lint, test, build, start)",
"permissions": {
"allow": [
"Bash(npm run lint)",
"Bash(npm run test:*)",
"Bash(npm run build)",
"Bash(npm start)"
]
}
}
```
**Behavior**:
* Claude can run `npm run lint`, `npm run test:unit`, `npm run build`, `npm start`
* User is not prompted for permission
* Wildcard `*` matches any suffix (e.g., `test:unit`, `test:integration`)
### Example 2: Context Monitor Statusline
**File**: Settings configuration
```json theme={null}
{
"description": "Real-time Claude Code context usage monitor with visual progress bars",
"statusLine": {
"type": "command",
"command": "python3 .claude/scripts/context-monitor.py"
}
}
```
**Supporting Script**: `.claude/scripts/context-monitor.py`
The CLI automatically downloads the Python script when installing this setting.
**Display Output**:
```
Context: [=========> ] 67% (134k/200k tokens)
Session: 12m 34s | Cost: $0.45 | 127 lines changed
```
### Example 3: Read-Only Mode
**File**: Settings configuration
```json theme={null}
{
"permissions": {
"deny": [
"Write(*)",
"Edit(*)",
"Bash(*)"
],
"allow": [
"Read(*)",
"Glob(*)",
"Grep(*)"
]
}
}
```
**Behavior**:
* Claude can only read files and search
* All write operations are blocked
* No shell commands allowed
* Useful for code review and analysis
## Installing Settings
### Single Setting
```bash theme={null}
npx claude-code-templates@latest --setting allow-npm-commands
```
You'll be prompted to choose installation location:
1. User settings (\~/.claude/settings.json)
2. Project settings (.claude/settings.json)
3. Local settings (.claude/settings.local.json)
4. Enterprise managed settings (requires admin)
### Multiple Settings
```bash theme={null}
npx claude-code-templates@latest \
--setting use-sonnet \
--setting allow-npm-commands \
--setting context-monitor
```
### Batch Installation to Specific Location
Skip prompts by using shared locations:
```bash theme={null}
# Install all to local settings
npx claude-code-templates@latest \
--setting use-sonnet \
--setting context-monitor \
--location local
```
Settings merge with existing configuration. Conflicting settings prompt for confirmation.
## Permission Patterns
Use wildcards and patterns for flexible permissions:
### Wildcard Matching
```json theme={null}
{
"permissions": {
"allow": [
"Bash(npm run test:*)" // Matches test:unit, test:integration, etc.
],
"deny": [
"Write(*.env*)" // Blocks .env, .env.local, .env.production
]
}
}
```
### Tool-Level Permissions
```json theme={null}
{
"permissions": {
"allow": [
"Read(*)", // Allow all file reads
"Glob(*)", // Allow all file searches
"Grep(*)" // Allow all content searches
],
"deny": [
"Bash(*)" // Block all shell commands
]
}
}
```
### Path-Based Permissions
```json theme={null}
{
"permissions": {
"allow": [
"Edit(src/*)", // Allow edits in src/
"Write(tests/*)", // Allow creating test files
"Bash(npm run test)" // Allow test execution
],
"deny": [
"Edit(node_modules/*)", // Prevent node_modules edits
"Write(.env*)" // Prevent .env file creation
]
}
}
```
## Environment Variable Best Practices
### Use Variable Substitution
**DON'T** hardcode secrets:
```json theme={null}
{
"env": {
"API_KEY": "sk-1234567890" // ❌ Exposed in git
}
}
```
**DO** reference environment variables:
```json theme={null}
{
"env": {
"API_KEY": "${API_KEY}" // ✅ Reads from shell
}
}
```
### Use .env Files
Create `.env` file (add to `.gitignore`):
```bash theme={null}
API_KEY=sk-1234567890
DATABASE_URL=postgresql://localhost/db
```
Reference in settings:
```json theme={null}
{
"env": {
"API_KEY": "${API_KEY}",
"DATABASE_URL": "${DATABASE_URL}"
}
}
```
Load with dotenv:
```bash theme={null}
export $(cat .env | xargs)
```
## Conflict Resolution
When installing settings that conflict with existing configuration:
1. **Conflict Detection** - CLI identifies conflicting values
2. **User Prompt** - Shows current vs new values
3. **User Choice** - Overwrite or skip
4. **Merge Strategy** - Arrays merge, objects overwrite
Example conflict prompt:
```
⚠️ Conflicts detected:
• Setting "model" (current: "opus", new: "sonnet")
• Environment variable "NODE_ENV" (current: "production", new: "development")
Do you want to overwrite the existing configuration? (y/N)
```
## Settings Merging
### Array Merging
Permission arrays merge uniquely:
**Existing**:
```json theme={null}
{
"permissions": {
"allow": ["Bash(npm test)"]
}
}
```
**New**:
```json theme={null}
{
"permissions": {
"allow": ["Bash(npm build)"]
}
}
```
**Result**:
```json theme={null}
{
"permissions": {
"allow": [
"Bash(npm test)",
"Bash(npm build)"
]
}
}
```
### Object Overwriting
Top-level settings overwrite:
**Existing**:
```json theme={null}
{
"model": "opus"
}
```
**New**:
```json theme={null}
{
"model": "sonnet"
}
```
**Result**:
```json theme={null}
{
"model": "sonnet" // Overwrites
}
```
## Enterprise Settings
Enterprise managed settings enforce organization-wide policies:
**Locations**:
* macOS: `/Library/Application Support/ClaudeCode/managed-settings.json`
* Linux: `/etc/claude-code/managed-settings.json`
* Windows: `C:\ProgramData\ClaudeCode\managed-settings.json`
**Requires**: Administrator privileges
**Use cases**:
* Security policies
* Compliance requirements
* Organization standards
Enterprise settings override all other settings and cannot be modified by users.
## Settings Best Practices
### 1. Principle of Least Privilege
Only grant necessary permissions:
```json theme={null}
{
"permissions": {
"allow": [
"Bash(npm run test)" // Specific command
]
}
}
```
Not:
```json theme={null}
{
"permissions": {
"allow": [
"Bash(*)" // Too permissive
]
}
}
```
### 2. Separate Concerns
* **User settings**: Personal preferences
* **Project settings**: Team conventions
* **Local settings**: Secrets and overrides
### 3. Document Settings
Add comments (in description field during installation):
```json theme={null}
{
"permissions": {
"allow": ["Bash(npm run test)"] // Required for CI/CD pipeline
}
}
```
### 4. Version Control
**Commit**:
* `.claude/settings.json` (project settings)
**Don't commit**:
* `.claude/settings.local.json` (personal overrides)
* `~/.claude/settings.json` (user settings)
Add to `.gitignore`:
```
.claude/settings.local.json
```
## Viewing Current Settings
Check active settings:
```bash theme={null}
# View project settings
cat .claude/settings.json
# View local settings
cat .claude/settings.local.json
# View user settings
cat ~/.claude/settings.json
```
Settings cascade: user → project → local.
## Removing Settings
Manually edit settings files to remove configurations:
```bash theme={null}
# Edit project settings
code .claude/settings.json
# Edit local settings
code .claude/settings.local.json
```
Remove unwanted sections or reset to `{}`.
## Next Steps
Explore 60+ available settings
Configure Claude Code settings
Automate with event-driven triggers
Complete project configurations
# Templates
Source: https://davila7-claude-code-templates-86.mintlify.app/concepts/templates
Complete project configurations with multiple components bundled together
Templates are pre-configured bundles that install multiple components at once. They provide complete setups for specific use cases, frameworks, or workflows, saving time on initial configuration.
## What Are Templates?
Templates are curated collections of components that work together:
* **Language-specific** - Optimized for JavaScript, Python, Go, etc.
* **Framework-focused** - React, Next.js, Django, FastAPI, etc.
* **Workflow-oriented** - Git excellence, security-first, testing-focused
* **Use-case driven** - API development, full-stack apps, microservices
Templates are essentially installation recipes that install multiple agents, commands, hooks, MCPs, and settings in one command.
## Template Categories
Comprehensive setups for programming languages:
### JavaScript/TypeScript
* **Agents**: frontend-developer, backend-developer, fullstack-developer
* **Commands**: setup-testing, setup-linting, ci-pipeline
* **Hooks**: format-javascript-files, eslint-on-save
* **MCPs**: web-fetch, filesystem-access
* **Settings**: allow-npm-commands, use-sonnet
```bash theme={null}
npx claude-code-templates@latest --language javascript-typescript
```
### Python
* **Agents**: python-expert, ml-engineer, api-developer
* **Commands**: setup-pytest, virtual-env-manager
* **Hooks**: format-python-files (Black), run-tests-on-save
* **MCPs**: postgresql-integration, filesystem-access
* **Settings**: allow-pip-commands, use-sonnet
```bash theme={null}
npx claude-code-templates@latest --language python
```
### Go
* **Agents**: go-expert, microservices-architect
* **Commands**: setup-go-testing, module-manager
* **Hooks**: gofmt-on-save, go-vet-on-change
* **MCPs**: database integrations
* **Settings**: allow-go-commands
```bash theme={null}
npx claude-code-templates@latest --language go
```
Framework-specific configurations:
### React + TypeScript
```bash theme={null}
npx claude-code-templates@latest \
--language javascript-typescript \
--framework react
```
**Includes**:
* frontend-developer agent
* Component testing commands
* ESLint + Prettier hooks
* TypeScript configuration
* React-specific linting rules
### Next.js
```bash theme={null}
npx claude-code-templates@latest \
--language javascript-typescript \
--framework nextjs
```
**Includes**:
* Next.js specialist agent
* Vercel deployment commands
* API route development tools
* Image optimization helpers
* Edge function configuration
### Django + PostgreSQL
```bash theme={null}
npx claude-code-templates@latest \
--language python \
--framework django
```
**Includes**:
* Django expert agent
* Migration management commands
* PostgreSQL MCP
* Django-specific linting
* Settings for database access
Specialized workflows:
### Git Excellence
```bash theme={null}
npx claude-code-templates@latest --workflow git-excellence
```
**Includes**:
* git-expert agent
* conventional-commits command
* commit-msg-validator hook
* branch-strategy command
* changelog-generator command
* Git operation permissions
### Security First
```bash theme={null}
npx claude-code-templates@latest --workflow security-first
```
**Includes**:
* security-auditor agent
* vulnerability-scan command
* secret-scanner hook
* dependency-audit command
* Read-only mode settings
* Security-focused permissions
### Testing Excellence
```bash theme={null}
npx claude-code-templates@latest --workflow testing-excellence
```
**Includes**:
* qa-expert agent
* setup-testing command
* run-tests-on-change hook
* coverage-reporter command
* Test execution permissions
Complete setups for specific use cases:
### API Development
```bash theme={null}
npx claude-code-templates@latest --use-case api-development
```
**Includes**:
* api-developer agent
* api-security-audit agent
* api-docs command
* postgresql-integration MCP
* API testing commands
* Rate limiting configuration
### Full-Stack Application
```bash theme={null}
npx claude-code-templates@latest --use-case fullstack-app
```
**Includes**:
* frontend-developer agent
* backend-developer agent
* database specialist agent
* Full CI/CD pipeline
* Database MCPs
* Comprehensive permissions
### Microservices
```bash theme={null}
npx claude-code-templates@latest --use-case microservices
```
**Includes**:
* microservices-architect agent
* docker-deploy command
* kubernetes-deploy command
* Service mesh configuration
* Container orchestration tools
## Interactive Template Selection
Use interactive mode for guided template selection:
```bash theme={null}
npx claude-code-templates@latest
```
Select your primary programming language:
* Common (language-agnostic)
* JavaScript/TypeScript
* Python
* Go
* Rust
* Java
Select your framework (optional):
* None
* React
* Next.js
* Vue.js
* Django
* FastAPI
Choose AI specialists for your project:
* frontend-developer
* backend-developer
* devops-engineer
* security-auditor
Choose automation hooks:
* format-on-save
* run-tests-on-change
* git-commit-formatter
Choose service integrations:
* web-fetch
* postgresql-integration
* github-integration
Review selections and confirm installation.
## Template Installation
### Auto-Detection Mode
Claude Code automatically detects your project type:
```bash theme={null}
cd my-react-app
npx claude-code-templates@latest --yes
```
**Detection logic**:
* Checks `package.json` for React/Next.js/etc.
* Looks for `requirements.txt` or `pyproject.toml` for Python
* Finds `go.mod` for Go projects
* Detects framework from dependencies
Installs appropriate template automatically.
### Manual Template Selection
```bash theme={null}
# Specific language
npx claude-code-templates@latest --language python
# Language + Framework
npx claude-code-templates@latest \
--language javascript-typescript \
--framework nextjs
# With custom agents
npx claude-code-templates@latest \
--language python \
--agent ml-engineer \
--agent data-scientist
```
### Dry Run Mode
Preview what will be installed:
```bash theme={null}
npx claude-code-templates@latest \
--language javascript-typescript \
--framework react \
--dry-run
```
Shows list of files that would be created without actually installing.
## Template Components
### Language: JavaScript/TypeScript
**Default Installation**:
```yaml theme={null}
Agents:
- frontend-developer
- backend-developer
- fullstack-developer
Commands:
- setup-testing
- setup-linting
- ci-pipeline
Hooks:
- format-javascript-files
- eslint-on-save
MCPs:
- web-fetch
- filesystem-access
Settings:
- allow-npm-commands
- use-sonnet
```
**Files Created**:
```
.claude/
├── agents/
│ ├── frontend-developer.md
│ ├── backend-developer.md
│ └── fullstack-developer.md
├── commands/
│ ├── setup-testing.md
│ ├── setup-linting.md
│ └── ci-pipeline.md
├── settings.json
└── settings.local.json
.mcp.json
```
### Language: Python
**Default Installation**:
```yaml theme={null}
Agents:
- python-expert
- api-developer
- ml-engineer
Commands:
- setup-pytest
- virtual-env-manager
- requirements-updater
Hooks:
- format-python-files (Black)
- run-tests-on-save
MCPs:
- postgresql-integration
- filesystem-access
Settings:
- allow-pip-commands
- use-sonnet
```
## Customizing Templates
After installation, customize components:
### Add More Components
```bash theme={null}
# Add additional agent
npx claude-code-templates@latest --agent security-auditor
# Add MCP integration
npx claude-code-templates@latest --mcp github-integration
# Add automation hook
npx claude-code-templates@latest --hook git/commit-validator
```
New components merge with existing configuration.
### Modify Settings
Edit `.claude/settings.json` or `.claude/settings.local.json`:
```bash theme={null}
code .claude/settings.json
```
Change permissions, add environment variables, or configure hooks.
### Remove Components
Delete unwanted component files:
```bash theme={null}
# Remove agent
rm .claude/agents/unwanted-agent.md
# Remove command
rm .claude/commands/unwanted-command.md
```
## Template Best Practices
### 1. Start with Base Template
Install language/framework template first:
```bash theme={null}
npx claude-code-templates@latest --language python --framework django
```
Then add specialized components:
```bash theme={null}
npx claude-code-templates@latest --agent security-auditor
```
### 2. Separate Team vs Personal Settings
**Commit to git** (team settings):
* `.claude/agents/`
* `.claude/commands/`
* `.claude/settings.json`
* `.mcp.json`
**Don't commit** (personal settings):
* `.claude/settings.local.json`
### 3. Document Your Template
Create `CLAUDE.md` in your project:
```markdown theme={null}
# Claude Code Setup
## Installed Components
- **Agents**: frontend-developer, backend-developer
- **Commands**: ci-pipeline, setup-testing
- **Hooks**: format-on-save, run-tests
- **MCPs**: web-fetch, postgresql-integration
## Usage
Invoke agents: `@frontend-developer Build the dashboard`
Run commands: `/ci-pipeline setup`
```
### 4. Version Control Template Configuration
Commit `.claude/` directory:
```bash theme={null}
git add .claude/
git commit -m "Add Claude Code template configuration"
```
Team members get the same setup when they clone.
## Template Migration
Update to newer template versions:
```bash theme={null}
# Re-run installation
npx claude-code-templates@latest --language javascript-typescript
```
CLI merges new components with existing ones, prompting for conflicts.
## Creating Custom Templates
Share your template configuration:
### 1. Export Current Setup
Your `.claude/` directory IS your template:
```bash theme={null}
# Package template
tar -czf my-template.tar.gz .claude/ .mcp.json
# Share with team
cp my-template.tar.gz /shared/drive/
```
### 2. Install from Archive
```bash theme={null}
# Extract template
tar -xzf my-template.tar.gz
# Components are ready to use
```
### 3. Publish Template Workflow
Create workflow hash for easy sharing:
```bash theme={null}
# Create workflow YAML
cat > my-workflow.yml <
For detailed workflow creation, see [Workflows Guide](/guides/workflows).
## Common Template Use Cases
### Startup MVP
```bash theme={null}
npx claude-code-templates@latest \
--language javascript-typescript \
--framework nextjs \
--agent fullstack-developer \
--mcp web-fetch \
--mcp supabase
```
**Result**: Full-stack Next.js setup with database and API integration.
### Enterprise API
```bash theme={null}
npx claude-code-templates@latest \
--language python \
--framework fastapi \
--agent api-developer \
--agent security-auditor \
--mcp postgresql-integration \
--setting read-only-mode
```
**Result**: Secure API development environment with database access.
### Data Science Project
```bash theme={null}
npx claude-code-templates@latest \
--language python \
--agent ml-engineer \
--agent data-scientist \
--mcp postgresql-integration \
--command data-pipeline
```
**Result**: ML/data science environment with database integration.
### Open Source Project
```bash theme={null}
npx claude-code-templates@latest \
--workflow git-excellence \
--agent documentation-expert \
--command changelog-generator \
--mcp github-integration
```
**Result**: Git workflow automation with documentation and GitHub integration.
## Template Limitations
### Not Supported
* Custom file templates (React components, etc.)
* Project scaffolding (create-react-app, etc.)
* Package installation (npm install, pip install)
* Code generation
### Workarounds
Use commands for custom workflows:
```bash theme={null}
# Create command that scaffolds components
npx claude-code-templates@latest --command scaffold-react-component
# Use in Claude Code
/scaffold-react-component Button
```
## Health Check
Verify template installation:
```bash theme={null}
npx claude-code-templates@latest --health
```
Checks:
* `.claude/` directory exists
* Agents are valid markdown
* Commands are valid markdown
* Settings are valid JSON
* MCP configuration is valid
* Hooks are properly configured
Run health check after template installation to catch configuration issues early.
## Next Steps
Get started with a template
Explore individual components
Bundle components into workflows
Use guided template selection
# Adding Components
Source: https://davila7-claude-code-templates-86.mintlify.app/contributing/adding-components
How to create and add new components to Claude Code Templates
This guide covers how to create and add individual components like agents, commands, MCPs, settings, hooks, and skills to the Claude Code Templates project.
## Component Types Overview
| Type | Count | Format | Description |
| ------------ | ------- | -------------- | --------------------------------------- |
| **Agents** | 400+ | Markdown | AI specialists for specific domains |
| **Commands** | 225+ | Markdown | Custom slash commands for workflows |
| **MCPs** | 65+ | JSON | External service integrations |
| **Settings** | 60+ | JSON | Claude Code configuration files |
| **Hooks** | 39+ | JSON + Scripts | Automation triggers for events |
| **Skills** | Growing | Markdown | Modular capabilities (Anthropic format) |
## Adding Agents
Agents are AI specialists for specific domains like security, performance, frameworks, etc.
### 1. Create Agent File
```bash theme={null}
# Navigate to appropriate category
cd cli-tool/components/agents/[category]/
# Create your agent file
touch your-agent-name.md
```
### 2. Agent File Structure
Agents use Markdown with YAML frontmatter:
```markdown theme={null}
---
name: frontend-developer
description: Frontend development specialist for React applications and responsive design
tools: Read, Write, Edit, Bash, Glob, Grep
model: sonnet
---
You are a senior frontend developer specializing in modern web applications...
## Communication Protocol
Always begin by requesting project context from the context-manager...
## Execution Flow
### 1. Context Discovery
...
```
### 3. Available Categories
* `development-team/` - Full-stack developers, architects
* `domain-experts/` - Security, performance, accessibility specialists
* `creative-team/` - Content creators, designers
* `business-team/` - Product managers, analysts
* `development-tools/` - Tool specialists, DevOps experts
### 4. Real Example: Frontend Developer
Location: `cli-tool/components/agents/development-team/frontend-developer.md`
```markdown theme={null}
---
name: frontend-developer
description: "Use when building complete frontend applications across React, Vue, and Angular frameworks..."
tools: Read, Write, Edit, Bash, Glob, Grep
model: sonnet
---
You are a senior frontend developer specializing in modern web applications with deep expertise in React 18+, Vue 3+, and Angular 15+.
## Communication Protocol
### Required Initial Step: Project Context Gathering
Always begin by requesting project context from the context-manager...
```
See the full example at `~/workspace/source/cli-tool/components/agents/development-team/frontend-developer.md`
## Adding Commands
Commands are custom slash commands that extend Claude Code functionality.
### 1. Create Command File
```bash theme={null}
cd cli-tool/components/commands/[category]/
touch your-command-name.md
```
### 2. Command File Structure
Commands use Markdown with YAML frontmatter:
```markdown theme={null}
---
allowed-tools: Read, Write, Edit, Bash
argument-hint: [file-path] | [component-name]
description: Generate comprehensive test suite with unit, integration, and edge case coverage
---
# Generate Tests
Generate comprehensive test suite for: $ARGUMENTS
## Current Testing Setup
- Test framework: @package.json or @jest.config.js
- Existing tests: !`find . -name "*.test.*" | head -5`
- Target file: @$ARGUMENTS
## Task
I'll analyze the target code and create complete test coverage...
```
### 3. Command Categories
* `testing/` - Test generation, validation, coverage
* `utilities/` - Code analysis, optimization, debugging
* `setup/` - Environment setup, configuration
* `team/` - Collaboration, planning, documentation
* `sync/` - Integration with external tools
* `simulation/` - Scenario modeling and analysis
### 4. Real Example: Generate Tests
Location: `cli-tool/components/commands/testing/generate-tests.md`
```markdown theme={null}
---
allowed-tools: Read, Write, Edit, Bash
argument-hint: [file-path] | [component-name]
description: Generate comprehensive test suite with unit, integration, and edge case coverage
---
# Generate Tests
Generate comprehensive test suite for: $ARGUMENTS
## Process
1. Analyze the target file/component structure
2. Identify all testable functions, methods, and behaviors
3. Examine existing test patterns in the project
4. Create test files following project naming conventions
5. Implement comprehensive test cases with proper setup/teardown
```
## Adding MCPs
MCPs provide external service integrations for Claude Code.
### 1. Create MCP File
```bash theme={null}
cd cli-tool/components/mcps/[category]/
touch your-service-mcp.json
```
### 2. MCP File Structure
```json theme={null}
{
"mcpServers": {
"service-name": {
"command": "npx",
"args": ["-y", "@your-org/mcp-server"],
"description": "What this MCP provides",
"env": {
"API_KEY": "",
"BASE_URL": "https://api.service.com"
}
}
}
}
```
### 3. MCP Categories
* `audio/` - Audio processing, text-to-speech, transcription
* `integration/` - GitHub, GitLab, Jira
* `database/` - PostgreSQL, MySQL, MongoDB
* `cloud/` - AWS, Azure, GCP services
* `devtools/` - Build tools, testing frameworks
* `ai-services/` - OpenAI, Anthropic, other AI APIs
Never hardcode actual API keys in MCP files. Use placeholder format: ``
## Adding Settings
Settings configure Claude Code behavior and performance.
### 1. Create Settings File
```bash theme={null}
cd cli-tool/components/settings/[category]/
touch your-setting-name.json
```
### 2. Settings File Structure
```json theme={null}
{
"setting-category": {
"parameter": "value",
"description": "What this setting controls"
}
}
```
### 3. Settings Categories
* `performance/` - Memory, timeout, cache settings
* `ui/` - Interface customization, themes
* `mcp/` - MCP server configurations
* `security/` - Access control, permissions
## Adding Hooks
Hooks provide automation triggers for different development events.
### 1. Create Hook File
```bash theme={null}
cd cli-tool/components/hooks/[category]/
touch your-hook-name.json
```
### 2. Hook File Structure
```json theme={null}
{
"description": "Send simple desktop notifications when operations complete",
"hooks": {
"PostToolUse": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "if command -v osascript >/dev/null 2>&1; then osascript -e 'display notification \"Tool completed\" with title \"Claude Code\"'; fi"
}
]
}
]
}
}
```
### 3. Hook Categories
* `git/` - Pre-commit, post-commit, pre-push
* `development-tools/` - File changes, formatting, linting
* `testing/` - Test execution, coverage checks
* `automation/` - Notifications, deployments, monitoring
* `security/` - Security scanning, secret detection
* `performance/` - Performance monitoring, budget guards
### 4. Real Example: Simple Notifications
Location: `cli-tool/components/hooks/automation/simple-notifications.json`
```json theme={null}
{
"description": "Send simple desktop notifications when Claude Code operations complete. Works on macOS and Linux systems.",
"hooks": {
"PostToolUse": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "if command -v osascript >/dev/null 2>&1; then osascript -e 'display notification \"Tool: $CLAUDE_TOOL_NAME completed\" with title \"Claude Code\"'; elif command -v notify-send >/dev/null 2>&1; then notify-send 'Claude Code' \"Tool: $CLAUDE_TOOL_NAME completed\"; fi"
}
]
}
]
}
}
```
### 5. Hook Types
* **PreToolUse** - Runs before a tool is executed
* **PostToolUse** - Runs after a tool completes
* **OnError** - Runs when an error occurs
* **OnSessionStart** - Runs when Claude Code session starts
* **OnSessionEnd** - Runs when Claude Code session ends
## Adding Skills
Skills are modular capabilities using Anthropic's progressive disclosure pattern.
### 1. Create Skill Directory
```bash theme={null}
cd cli-tool/components/skills/[category]/
mkdir your-skill-name
cd your-skill-name
```
### 2. Skill Structure
```
your-skill-name/
├── SKILL.md # Main skill instructions
├── references/ # Reference files (loaded on demand)
└── scripts/ # Executable scripts (not loaded in context)
```
### 3. SKILL.md Format
```markdown theme={null}
# Skill Name
## Overview
Brief description of what this skill does.
## When to Use
When the user requests...
## Instructions
Detailed instructions for Claude...
## References
Files in the references/ directory that can be loaded on demand.
```
## Creating New Categories
If your component doesn't fit existing categories, create a new one:
```bash theme={null}
# Example: Create new agent category
cd cli-tool/components/agents/
mkdir your-new-category
# Add your component
cd your-new-category/
touch your-component-name.md
```
New categories are automatically detected when the component catalog is regenerated.
## Next Steps
After creating your component:
```bash theme={null}
# CRITICAL: Use the component-reviewer agent
# See Component Guidelines for details
```
```bash theme={null}
npx claude-code-templates@latest --agent your-agent --dry-run
```
```bash theme={null}
python scripts/generate_components_json.py
```
See [Publishing Workflow](/contributing/publishing) for details
## Resources
* [Component Guidelines](/contributing/component-guidelines) - Best practices and quality standards
* [Testing Workflow](/contributing/testing) - How to test your components
* [Code Standards](/contributing/code-standards) - Coding conventions and style guide
* [Browse existing components](https://aitmpl.com) - See examples and patterns
# Project Architecture
Source: https://davila7-claude-code-templates-86.mintlify.app/contributing/architecture
Overview of the Claude Code Templates project architecture
This guide provides an overview of the Claude Code Templates project architecture, including the CLI tool, component system, website, and infrastructure.
## Project Structure
```bash theme={null}
claud-code-templates/
├── cli-tool/ # CLI tool for component installation
│ ├── bin/ # Executable scripts
│ ├── src/ # Source code
│ │ ├── index.js # Main CLI logic
│ │ ├── analytics/ # Analytics dashboard
│ │ ├── chats/ # Chat monitor
│ │ └── health-checks/ # Health check diagnostics
│ ├── components/ # Component library
│ │ ├── agents/ # AI specialists (400+)
│ │ ├── commands/ # Slash commands (225+)
│ │ ├── mcps/ # MCP integrations (65+)
│ │ ├── settings/ # Configuration files (60+)
│ │ ├── hooks/ # Automation triggers (39+)
│ │ └── skills/ # Modular capabilities
│ └── package.json # CLI dependencies
├── docs/ # Static website
│ ├── index.html # Component browser
│ ├── components.json # Component catalog (~2MB)
│ ├── blog/ # Blog articles
│ └── js/ # Vanilla JavaScript
├── api/ # Vercel Serverless Functions
│ ├── track-download-supabase.js
│ ├── discord/ # Discord bot
│ └── claude-code-check.js # Release monitoring
├── dashboard/ # Astro dashboard (app.aitmpl.com)
│ ├── src/
│ │ ├── pages/ # Astro pages
│ │ ├── components/ # React islands
│ │ └── styles/ # Tailwind CSS
│ └── package.json
├── cloudflare-workers/ # Cloudflare Workers
│ ├── docs-monitor/ # Documentation monitoring
│ └── pulse/ # Weekly KPI reports
├── scripts/ # Build and utility scripts
│ ├── generate_components_json.py # Catalog generation
│ └── deploy.sh # Deployment automation
└── package.json # Root package configuration
```
## CLI Tool Architecture
### Main Entry Point
Location: `cli-tool/src/index.js`
The CLI tool is a Node.js application that:
1. Parses command-line arguments using `commander`
2. Fetches component files from GitHub
3. Installs components to the user's project
4. Tracks downloads via API
5. Provides interactive installation mode
### Installation Flow
```mermaid theme={null}
graph TD
A[User runs npx claude-code-templates] --> B[Parse CLI arguments]
B --> C{Installation type?}
C -->|Interactive| D[Show interactive menu]
C -->|Direct| E[Fetch component from GitHub]
D --> E
E --> F[Download component files]
F --> G[Install to project directory]
G --> H[Track download via API]
H --> I[Show success message]
```
### Component System
#### Component Types
**Agents** (`cli-tool/components/agents/`)
* Format: Markdown with YAML frontmatter
* Installation: `.claude/agents/{name}.md`
* Purpose: AI specialists for specific domains
**Commands** (`cli-tool/components/commands/`)
* Format: Markdown with YAML frontmatter
* Installation: `.claude/commands/{name}.md`
* Purpose: Custom slash commands for workflows
**MCPs** (`cli-tool/components/mcps/`)
* Format: JSON
* Installation: `.mcp.json` (merged)
* Purpose: External service integrations
**Settings** (`cli-tool/components/settings/`)
* Format: JSON
* Installation: `.claude/settings.json` (merged)
* Purpose: Claude Code configuration
**Hooks** (`cli-tool/components/hooks/`)
* Format: JSON + optional scripts
* Installation: `.claude/settings.json` + `.claude/hooks/`
* Purpose: Automation triggers for events
**Skills** (`cli-tool/components/skills/`)
* Format: Markdown + references + scripts
* Installation: `.claude/skills/{name}/`
* Purpose: Modular capabilities (Anthropic format)
#### Component Categories
Components are organized by category:
```bash theme={null}
agents/
├── development-team/ # Full-stack developers
├── domain-experts/ # Security, performance specialists
├── creative-team/ # Content creators, designers
├── business-team/ # Product managers, analysts
└── development-tools/ # Tool specialists, DevOps
commands/
├── testing/ # Test generation, validation
├── utilities/ # Code analysis, debugging
├── setup/ # Environment setup
├── team/ # Collaboration, planning
└── sync/ # External tool integration
hooks/
├── git/ # Git workflow automation
├── development-tools/ # File changes, formatting
├── testing/ # Test execution
├── automation/ # Notifications, deployments
├── security/ # Security scanning
└── performance/ # Performance monitoring
```
## Analytics Dashboard
Location: `cli-tool/src/analytics/`
Real-time monitoring dashboard for Claude Code sessions.
### Architecture
```bash theme={null}
src/analytics/
├── core/ # Business logic
│ ├── StateCalculator.js # Conversation state detection
│ ├── ProcessDetector.js # Running process detection
│ ├── ConversationAnalyzer.js # Message parsing
│ └── FileWatcher.js # Real-time file monitoring
├── data/ # Data management
│ └── DataCache.js # Multi-level caching
├── notifications/ # Real-time communication
│ ├── WebSocketServer.js # Server-side WebSocket
│ └── NotificationManager.js # Event-driven notifications
└── utils/ # Utilities
└── PerformanceMonitor.js # System health monitoring
```
### Features
* Real-time conversation monitoring
* State detection (active, idle, stopped)
* Process detection (running commands)
* Performance metrics
* WebSocket-based live updates
* Multi-level caching for performance
### Usage
```bash theme={null}
# Start analytics dashboard
npm run analytics:start
# Access at http://localhost:3333
# API endpoints
GET /api/health # Health check
GET /api/conversations # List conversations
GET /api/conversation/:id # Get conversation details
POST /api/cache/clear # Clear cache
GET /api/refresh # Refresh data
```
## Website Architecture
Location: `docs/`
Static website at [aitmpl.com](https://aitmpl.com) for browsing components.
### Data Flow
1. **Component Scanning**: `scripts/generate_components_json.py` scans `cli-tool/components/`
2. **Catalog Generation**: Generates `docs/components.json` with embedded content
3. **Website Loading**: Browser loads JSON and renders component cards
4. **Download Tracking**: Installation tracked via `/api/track-download-supabase`
### Component Catalog Format
```json theme={null}
{
"agents": [
{
"name": "frontend-developer",
"category": "development-team",
"description": "Frontend development specialist...",
"content": "Full markdown content...",
"downloads": 1234,
"tools": ["Read", "Write", "Edit", "Bash"],
"model": "sonnet"
}
],
"commands": [...],
"mcps": [...],
"settings": [...],
"hooks": [...],
"skills": [...]
}
```
## API Architecture
Location: `api/`
Vercel Serverless Functions for backend operations.
### Critical Endpoints
**`/api/track-download-supabase`**
* Tracks component downloads for analytics
* Used by CLI on every installation
* Database: Supabase (`component_downloads` table)
**`/api/discord/interactions`**
* Discord bot slash commands
* Features: `/search`, `/info`, `/install`, `/popular`
**`/api/claude-code-check`**
* Monitors Claude Code releases
* Vercel Cron: every 30 minutes
* Database: Neon (version tracking)
## Dashboard Architecture
Location: `dashboard/`
Astro + React + Tailwind dashboard at [app.aitmpl.com](https://app.aitmpl.com).
### Architecture
* **Framework**: Astro 5 with React islands
* **Auth**: Clerk (user collections)
* **Styling**: Tailwind v4
* **Data**: Fetches from `https://www.aitmpl.com/components.json`
* **API Proxy**: Proxies to main site API
### Directory Structure
```bash theme={null}
dashboard/
├── src/
│ ├── pages/ # Astro pages
│ │ ├── index.astro # Home page
│ │ └── api/ # API proxy routes
│ ├── components/ # React islands
│ │ ├── ComponentGrid.tsx
│ │ ├── SearchBar.tsx
│ │ └── CollectionManager.tsx
│ ├── layouts/ # Layout components
│ └── styles/ # Tailwind CSS
├── public/ # Static assets
└── package.json
```
## Cloudflare Workers
Location: `cloudflare-workers/`
Independent serverless functions on Cloudflare.
### docs-monitor
Monitors [code.claude.com/docs](https://code.claude.com/docs) for changes:
* Runs every hour
* Sends Telegram notifications
* Tracks documentation updates
### pulse
Weekly KPI reports:
* Runs Sundays at 14:00 UTC
* Collects metrics from multiple sources:
* GitHub (stars, forks, commits)
* Discord (members, messages)
* Supabase (downloads)
* Vercel (deployments)
* Google Analytics (traffic)
* Sends consolidated Telegram report
## Deployment Architecture
### Vercel Projects
Two separate Vercel projects:
| Project | Domain | Root Directory | Purpose |
| ------------------ | ---------------- | -------------- | --------------- |
| `aitmpl` | `www.aitmpl.com` | `/` | Main site + API |
| `aitmpl-dashboard` | `app.aitmpl.com` | `dashboard` | Dashboard app |
### CI/CD Pipeline
GitHub Actions (`.github/workflows/deploy.yml`):
* Changes in `docs/`, `api/`, or `vercel.json` → Deploy main site
* Changes in `dashboard/` → Deploy dashboard
* Auto-deploy on push to `main` branch
### Deployment Commands
```bash theme={null}
# Deploy main site
npm run deploy:site
# Deploy dashboard
npm run deploy:dashboard
# Deploy both
npm run deploy:all
```
Always use the deployer agent (`.claude/agents/deployer.md`) for deployments. It runs pre-deploy checks and handles the pipeline safely.
## Database Architecture
### Supabase
**Purpose**: Download tracking and analytics
**Tables**:
* `component_downloads` - Track component installations
* `id`, `component_type`, `component_name`, `component_category`
* `installed_at`, `user_id`, `project_id`
### Neon (PostgreSQL)
**Purpose**: Claude Code release monitoring
**Tables**:
* `claude_code_versions` - Version history
* `claude_code_changes` - Change tracking
* `discord_notifications_log` - Notification history
* `monitoring_metadata` - Monitoring state
## Security Architecture
### Environment Variables
All secrets stored in environment variables:
```bash theme={null}
# Vercel
SUPABASE_URL
SUPABASE_SERVICE_ROLE_KEY
NEON_DATABASE_URL
DISCORD_BOT_TOKEN
# Cloudflare Workers
TELEGRAM_BOT_TOKEN
TELEGRAM_CHAT_ID
GITHUB_TOKEN
```
NEVER hardcode secrets in code. Always use environment variables. See [Code Standards](/contributing/code-standards) for details.
### Path Security
* Use relative paths only
* No absolute paths in components
* No hardcoded home directories
* Use `$CLAUDE_PROJECT_DIR` for dynamic paths
## Performance Considerations
### Component Catalog
* Generated catalog is \~2MB (compressed)
* Loaded once and cached in browser
* Components filtered client-side for speed
### Analytics Dashboard
* Multi-level caching (memory + disk)
* WebSocket for real-time updates (not polling)
* Efficient file watching (chokidar)
* Performance monitoring built-in
### API Endpoints
* Serverless functions (fast cold starts)
* Database connection pooling
* Response caching where appropriate
## Monitoring and Observability
### Vercel Logs
```bash theme={null}
# Monitor logs
vercel logs aitmpl.com --follow
# Check specific deployment
vercel logs
```
### Health Checks
* Analytics dashboard: `GET /api/health`
* API endpoints: Built-in error logging
* Cloudflare Workers: Error tracking
### Metrics Tracking
* Component downloads (Supabase)
* Website traffic (Google Analytics)
* API usage (Vercel analytics)
* GitHub activity (pulse worker)
## Next Steps
Best practices for creating components
Coding conventions and style guide
How to test your contributions
Complete publishing process
# Code Standards
Source: https://davila7-claude-code-templates-86.mintlify.app/contributing/code-standards
Coding conventions and style guidelines for contributors
This guide covers the coding standards, conventions, and best practices for contributing to Claude Code Templates.
## Security Guidelines
**CRITICAL: NEVER hardcode secrets or IDs in code.** This is the most important rule.
### Never Hardcode Secrets
NEVER write these in code:
* API keys, tokens, passwords
* Project IDs, organization IDs
* Vercel project/org IDs
* Supabase URLs
* Discord IDs
* Database connection strings
* Any infrastructure identifier
ALL secrets must go in `.env` files.
```javascript theme={null}
// ❌ WRONG - Hardcoded secret
const API_KEY = "AIzaSy...";
const SUPABASE_URL = "https://xyz.supabase.co";
// ✅ CORRECT - Environment variable
const API_KEY = process.env.GOOGLE_API_KEY;
const SUPABASE_URL = process.env.SUPABASE_URL;
```
### Using Environment Variables
For Node.js:
```javascript theme={null}
// Load environment variables
require('dotenv').config();
// Use process.env
const apiKey = process.env.API_KEY;
const dbUrl = process.env.DATABASE_URL;
// Always check for missing variables
if (!apiKey) {
throw new Error('API_KEY environment variable is required');
}
```
For Python:
```python theme={null}
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Use os.environ.get()
api_key = os.environ.get('API_KEY')
db_url = os.environ.get('DATABASE_URL')
# Always check for missing variables
if not api_key:
raise ValueError('API_KEY environment variable is required')
```
### .env File Structure
Create `.env.example` with placeholder values:
```bash theme={null}
# .env.example
API_KEY=
DATABASE_URL=
SUPABASE_URL=
SUPABASE_SERVICE_ROLE_KEY=
```
Verify `.env` is in `.gitignore`:
```bash theme={null}
# .gitignore
.env
.env.local
.env.*.local
```
### If You Accidentally Commit a Secret
If you commit a secret, it's compromised FOREVER (git history). Act immediately.
Immediately revoke the exposed key/token in the service.
Create a new key/token in the service.
Update your `.env` file with the new key.
The old key is compromised forever. Never reuse it.
## Path Handling
### Always Use Relative Paths
```bash theme={null}
# ✅ Correct - Relative paths
.claude/scripts/
.claude/hooks/
.claude/agents/
$CLAUDE_PROJECT_DIR/.claude/
# ❌ Wrong - Absolute paths
/Users/username/.claude/
/home/user/project/.claude/
~/project/.claude/
C:\Users\username\.claude\
```
### Cross-Platform Compatibility
Use `path.join()` for cross-platform paths:
```javascript theme={null}
const path = require('path');
// ✅ Correct - Cross-platform
const configPath = path.join('.claude', 'settings.json');
const scriptPath = path.join(process.env.CLAUDE_PROJECT_DIR, '.claude', 'scripts', 'hook.py');
// ❌ Wrong - Unix-only
const configPath = '.claude/settings.json';
const scriptPath = process.env.CLAUDE_PROJECT_DIR + '/.claude/scripts/hook.py';
```
### Path Constants
Define path constants for reusability:
```javascript theme={null}
const PATHS = {
CLAUDE_DIR: '.claude',
AGENTS_DIR: path.join('.claude', 'agents'),
COMMANDS_DIR: path.join('.claude', 'commands'),
HOOKS_DIR: path.join('.claude', 'hooks'),
SCRIPTS_DIR: path.join('.claude', 'scripts'),
SETTINGS_FILE: path.join('.claude', 'settings.json'),
MCP_FILE: '.mcp.json'
};
// Use constants
const agentPath = path.join(PATHS.AGENTS_DIR, `${agentName}.md`);
```
## Naming Conventions
### File Names
```bash theme={null}
# JavaScript/TypeScript files
kebab-case.js # ✅ Utility files, scripts
PascalCase.js # ✅ Class definitions
index.js # ✅ Module entry points
# Component files (Markdown)
frontend-developer.md # ✅ Kebab-case
generate-tests.md # ✅ Kebab-case
# JSON configuration files
settings.json # ✅ Lowercase
package.json # ✅ Standard
components.json # ✅ Lowercase
# Python files
generate_components_json.py # ✅ Snake case
data_processor.py # ✅ Snake case
```
### Variables and Functions
```javascript theme={null}
// Variables: camelCase
const userName = 'John';
const componentList = [];
let isActive = false;
// Functions: camelCase
function getUserData() { }
function processComponent(name) { }
const fetchAgents = async () => { };
// Constants: UPPER_SNAKE_CASE
const MAX_RETRIES = 3;
const API_BASE_URL = 'https://api.example.com';
const DEFAULT_TIMEOUT = 30000;
// Classes: PascalCase
class ComponentProcessor { }
class DataCache { }
class WebSocketServer { }
// Private variables: _prefix
class Example {
constructor() {
this._privateData = null;
}
}
```
### Component Names
```bash theme={null}
# Agent names: kebab-case
frontend-developer
api-security-auditor
database-optimizer
# Command names: kebab-case
generate-tests
setup-development-environment
code-review
# Hook names: kebab-case
simple-notifications
prevent-force-push
format-on-save
# Category names: kebab-case
development-team
domain-experts
code-generation
```
## Code Style
### JavaScript/Node.js
#### General Guidelines
```javascript theme={null}
// Use const by default, let when reassignment needed
const config = loadConfig();
let counter = 0;
// Use arrow functions for callbacks
array.map(item => item.name);
array.filter(item => item.active);
// Use template literals
const message = `Hello, ${userName}!`;
const path = `${baseDir}/${fileName}`;
// Use async/await over promises
async function fetchData() {
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
console.error('Failed to fetch:', error);
throw error;
}
}
// Use destructuring
const { name, age } = user;
const [first, second] = array;
// Use spread operator
const newArray = [...oldArray, newItem];
const newObject = { ...oldObject, newKey: 'value' };
```
#### Error Handling
```javascript theme={null}
// Always use try/catch for async operations
async function processComponent(name) {
try {
const component = await fetchComponent(name);
const result = await installComponent(component);
return result;
} catch (error) {
// Log with context
console.error(`Failed to process component ${name}:`, error);
// Provide helpful error message
throw new Error(`Component installation failed: ${error.message}`);
}
}
// Validate input parameters
function installAgent(name) {
if (!name || typeof name !== 'string') {
throw new TypeError('Agent name must be a non-empty string');
}
if (name.includes('/')) {
throw new Error('Agent name cannot contain slashes');
}
// Proceed with installation
}
// Use fallback mechanisms
function getConfig() {
try {
return JSON.parse(fs.readFileSync('config.json', 'utf8'));
} catch (error) {
console.warn('Config file not found, using defaults');
return DEFAULT_CONFIG;
}
}
```
#### Async Operations
```javascript theme={null}
// Use Promise.all for parallel operations
const [agents, commands, hooks] = await Promise.all([
fetchAgents(),
fetchCommands(),
fetchHooks()
]);
// Use Promise.allSettled to handle failures gracefully
const results = await Promise.allSettled([
downloadAgent('agent1'),
downloadAgent('agent2'),
downloadAgent('agent3')
]);
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`Agent ${index} downloaded successfully`);
} else {
console.error(`Agent ${index} failed:`, result.reason);
}
});
```
### Python
#### General Guidelines
```python theme={null}
# Use type hints
def process_component(name: str, category: str) -> dict:
"""Process a component and return metadata."""
return {'name': name, 'category': category}
# Use f-strings for formatting
message = f"Processing {component_name} in {category}"
path = f"{base_dir}/{file_name}"
# Use list comprehensions
names = [agent['name'] for agent in agents]
active_users = [u for u in users if u.is_active]
# Use context managers
with open('file.txt', 'r') as f:
content = f.read()
# Use pathlib for paths
from pathlib import Path
base_dir = Path('cli-tool/components')
agent_file = base_dir / 'agents' / 'development-team' / 'frontend-developer.md'
```
#### Error Handling
```python theme={null}
# Use specific exception types
try:
component = load_component(name)
except FileNotFoundError:
print(f"Component {name} not found")
return None
except json.JSONDecodeError as e:
print(f"Invalid JSON in component: {e}")
return None
except Exception as e:
print(f"Unexpected error: {e}")
raise
# Provide context in error messages
if not component_name:
raise ValueError("Component name cannot be empty")
if '/' in component_name:
raise ValueError(f"Invalid component name: {component_name}")
```
## Documentation Standards
### Code Comments
```javascript theme={null}
// Good comments explain WHY, not WHAT
// ❌ Bad comment - explains obvious WHAT
// Loop through agents
for (const agent of agents) { }
// ✅ Good comment - explains WHY
// Process agents in parallel batches to avoid rate limiting
for (const batch of agentBatches) {
await Promise.all(batch.map(processAgent));
}
// Document complex logic
/**
* Merges hook configurations from multiple sources.
* Priority: User config > Template config > Default config
*
* @param {Object} userHooks - User-defined hooks
* @param {Object} templateHooks - Template default hooks
* @returns {Object} Merged hook configuration
*/
function mergeHooks(userHooks, templateHooks) {
// Implementation
}
```
### JSDoc Comments
```javascript theme={null}
/**
* Install a component to the user's project.
*
* @param {string} componentType - Type of component (agent, command, hook, etc.)
* @param {string} componentName - Name of the component to install
* @param {Object} options - Installation options
* @param {boolean} options.dryRun - If true, don't actually install
* @param {boolean} options.force - If true, overwrite existing files
* @returns {Promise