# 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} Installation result with status and files created * @throws {Error} If component not found or installation fails */ async function installComponent(componentType, componentName, options = {}) { // Implementation } ``` ### Python Docstrings ```python theme={null} def generate_component_catalog(component_dir: str, output_file: str) -> dict: """ Generate a JSON catalog of all components. Scans the component directory for agents, commands, hooks, etc. and generates a comprehensive JSON catalog with metadata and content. Args: component_dir: Path to the cli-tool/components directory output_file: Path where the catalog JSON should be written Returns: Dictionary with component counts by type Raises: FileNotFoundError: If component directory doesn't exist ValueError: If output path is invalid """ # Implementation ``` ## Testing Standards ### Test Structure ```javascript theme={null} // Use descriptive test names describe('ComponentInstaller', () => { describe('installAgent', () => { it('should install agent to .claude/agents/ directory', async () => { // Test implementation }); it('should throw error if agent name is invalid', async () => { // Test implementation }); it('should not overwrite existing agent without force flag', async () => { // Test implementation }); }); }); // Follow AAA pattern: Arrange, Act, Assert it('should merge hook configurations correctly', () => { // Arrange const userHooks = { PreToolUse: ['hook1'] }; const templateHooks = { PostToolUse: ['hook2'] }; // Act const result = mergeHooks(userHooks, templateHooks); // Assert expect(result.PreToolUse).toEqual(['hook1']); expect(result.PostToolUse).toEqual(['hook2']); }); ``` ### Test Coverage Goals * Aim for **70%+ code coverage** * Test all critical paths * Test error handling * Test edge cases * Test boundary conditions ## Git Workflow ### Commit Messages ```bash theme={null} # Use conventional commits format feat: Add new security-auditor agent fix: Correct path handling in Windows docs: Update contributing guidelines chore: Bump version to 1.28.17 refactor: Simplify hook installation logic test: Add tests for component validation # Provide context in commit body git commit -m "feat: Add PostgreSQL MCP integration" -m "Adds Model Context Protocol server for PostgreSQL database access. Includes connection pooling and query execution support." ``` ### Branch Naming ```bash theme={null} feature/add-rust-template fix/windows-path-handling docs/update-testing-guide chore/update-dependencies refactor/simplify-installer ``` ## Performance Considerations ### Caching ```javascript theme={null} // Cache expensive operations const componentCache = new Map(); async function getComponent(name) { if (componentCache.has(name)) { return componentCache.get(name); } const component = await fetchComponent(name); componentCache.set(name, component); return component; } // Clear cache when needed function clearCache() { componentCache.clear(); } ``` ### Async Optimization ```javascript theme={null} // Parallelize independent operations const [catalog, downloads, stats] = await Promise.all([ loadComponentCatalog(), fetchDownloadStats(), calculateStatistics() ]); // Use streaming for large files const stream = fs.createReadStream('large-file.json'); stream.pipe(parser).on('data', processChunk); ``` ## Next Steps Best practices for creating components Complete testing guide Project architecture overview Publishing to npm # Component Guidelines Source: https://davila7-claude-code-templates-86.mintlify.app/contributing/component-guidelines Best practices and quality standards for creating components This guide covers the quality standards, best practices, and review process for contributing components to Claude Code Templates. ## Critical: Component Reviewer Agent **ALWAYS use the component-reviewer agent before submitting components.** This is a mandatory step that validates format, security, naming conventions, and best practices. ### When to Use Component Reviewer Use the `component-reviewer` agent for ALL component changes: ```bash theme={null} # After creating a new agent Use the component-reviewer agent to review cli-tool/components/agents/development-team/react-expert.md # Before committing hook changes Use the component-reviewer agent to review cli-tool/components/hooks/git/prevent-force-push.json # For PR reviews with multiple components Use the component-reviewer agent to review all modified components in cli-tool/components/ ``` ### What the Component Reviewer Checks The agent validates: * ✅ Valid YAML frontmatter and required fields * ✅ Proper kebab-case naming conventions * ✅ No hardcoded secrets (API keys, tokens, passwords) * ✅ Relative paths only (no absolute paths) * ✅ Supporting files exist (for hooks with scripts) * ✅ Clear, specific descriptions * ✅ Correct category placement * ✅ Security best practices ### Review Feedback Levels The agent provides prioritized feedback: * **❌ Critical Issues**: Must fix before merge (security, missing fields) * **⚠️ Warnings**: Should fix (clarity, best practices) * **📋 Suggestions**: Nice to have improvements ## Component Creation Workflow Create your component file in the appropriate directory: ```bash theme={null} cli-tool/components/{type}/{category}/{name}.md ``` Use kebab-case (lowercase with hyphens): * ✅ `frontend-developer.md` * ✅ `generate-tests.md` * ❌ `FrontendDeveloper.md` * ❌ `generate_tests.md` Include clear descriptions and usage examples in the component. **CRITICAL**: Review with the component-reviewer agent: ```bash theme={null} Use the component-reviewer agent to review [component-path] ``` Address any critical issues or warnings identified by the reviewer. Run the Python script to update the component catalog: ```bash theme={null} python scripts/generate_components_json.py ``` ## Naming Conventions ### File Names All component files must use **kebab-case**: ```bash theme={null} # ✅ Correct frontend-developer.md generate-tests.md simple-notifications.json api-security-audit.md # ❌ Wrong FrontendDeveloper.md generate_tests.md SimpleNotifications.json API-Security-Audit.md ``` ### Component Names (in frontmatter) Component names in YAML frontmatter must match the filename: ```yaml theme={null} # ✅ Correct (file: frontend-developer.md) name: frontend-developer # ❌ Wrong (file: frontend-developer.md) name: FrontendDeveloper name: frontend_developer ``` ## Security Requirements **NEVER hardcode secrets in components.** This includes API keys, tokens, passwords, URLs, project IDs, or any sensitive identifier. ### Prohibited Content ```json theme={null} // ❌ WRONG - Hardcoded API key { "mcpServers": { "service": { "env": { "API_KEY": "sk-proj-abc123xyz" } } } } // ✅ CORRECT - Placeholder format { "mcpServers": { "service": { "env": { "API_KEY": "" } } } } ``` ### Path Requirements Use **relative paths** only: ```bash theme={null} # ✅ Correct .claude/scripts/ .claude/hooks/ $CLAUDE_PROJECT_DIR/.claude/ # ❌ Wrong /Users/username/.claude/ /home/user/project/.claude/ ~/project/.claude/ ``` ## Component-Specific Guidelines ### Agents #### Required Fields ```yaml theme={null} --- name: frontend-developer description: Frontend development specialist for React applications tools: Read, Write, Edit, Bash, Glob, Grep model: sonnet --- ``` #### Description Quality Descriptions must be: * **Specific** - Not generic ("helps with frontend" ❌) * **Comprehensive** - Explain full capabilities * **Example-driven** - Include use cases ```yaml theme={null} # ❌ Generic description description: "Frontend developer agent" # ✅ Specific description description: "Frontend development specialist for React applications with expertise in responsive design, state management, TypeScript, and testing. Use for building complete frontend applications with 85%+ test coverage." ``` #### Content Structure Agents should include: 1. **Clear role definition** - What the agent does 2. **Communication protocol** - How to interact with other agents 3. **Execution flow** - Step-by-step process 4. **Best practices** - Guidelines and standards 5. **Deliverables** - What the agent produces ### Commands #### Required Fields ```yaml 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 --- ``` #### Allowed Tools Specification Be specific about permitted bash commands: ```yaml theme={null} # ✅ Specific permissions allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*) # ⚠️ Too broad (only if necessary) allowed-tools: Bash ``` #### Argument Hints Provide clear usage syntax: ```yaml theme={null} # ✅ Clear argument patterns argument-hint: [file-path] | [component-name] argument-hint: [message] | --no-verify | --amend argument-hint: [--include-tests] # ❌ Vague argument-hint: options ``` #### Current State Queries Use `!` syntax for dynamic values: ```markdown theme={null} ## Current Testing Setup - Test framework: @package.json or @jest.config.js - Existing tests: !`find . -name "*.test.*" | head -5` - Test coverage: !`npm run test:coverage 2>/dev/null || echo "No coverage script"` - Target file: @$ARGUMENTS ``` ### Hooks #### Required Structure ```json theme={null} { "description": "Clear description of what the hook does", "hooks": { "PostToolUse": [ { "matcher": "*", "hooks": [ { "type": "command", "command": "command to execute" } ] } ] } } ``` #### Supporting Scripts If your hook references a Python or shell script: 1. **Create the script file** with matching name 2. **Use correct file extension** (`.py`, `.sh`) 3. **Use relative paths** in the hook JSON 4. **Make scripts executable** for `.sh` files ```bash theme={null} # Hook file structure cli-tool/components/hooks/git/ ├── prevent-force-push.json # Hook configuration └── prevent-force-push.py # Supporting script ``` #### Hook Matchers Valid matcher values: * `*` - All tools * `Bash` - Bash commands * `Read` - File reads * `Write` - File writes * `Edit` - File edits ### MCPs #### Environment Variables Always use placeholder format: ```json theme={null} { "env": { "API_KEY": "", "BASE_URL": "", "DATABASE_URL": "" } } ``` #### Include Description Every MCP server configuration should include a description: ```json theme={null} { "mcpServers": { "github": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "description": "GitHub integration for repository management, issues, and PRs", "env": { "GITHUB_TOKEN": "" } } } } ``` ## Quality Standards ### Documentation All components must include: * Clear purpose and use cases * Usage examples * Configuration instructions * Required dependencies (if any) * Expected behavior ### Testing Before submitting: ```bash theme={null} # Test dry-run installation npx claude-code-templates@latest --agent your-agent --dry-run npx claude-code-templates@latest --command your-command --dry-run npx claude-code-templates@latest --hook your-category/your-hook --dry-run # Verify no errors occur ``` ### Comprehensive Configuration For templates: * Include all necessary Claude Code setup files * Well-documented CLAUDE.md with examples * Useful slash commands for the domain * Relevant external integrations (MCPs) ## Common Issues and Fixes ### Invalid YAML Frontmatter ```yaml theme={null} # ❌ Wrong - Missing closing --- --- name: my-agent # ✅ Correct --- name: my-agent --- ``` ### Missing Required Fields ```yaml theme={null} # ❌ Missing model field --- name: my-agent description: Does things tools: Read, Write --- # ✅ Complete --- name: my-agent description: Does things tools: Read, Write model: sonnet --- ``` ### Incorrect File Location ```bash theme={null} # ❌ Wrong - No category cli-tool/components/agents/my-agent.md # ✅ Correct - In proper category cli-tool/components/agents/domain-experts/my-agent.md ``` ## Update Component Catalog After creating or modifying components, update the catalog: ```bash theme={null} python scripts/generate_components_json.py ``` This script: 1. Scans all components in `cli-tool/components/` 2. Validates format and structure 3. Generates `docs/components.json` with embedded content 4. Updates the website component browser The `generate_components_json.py` script automatically validates component format and detects common issues during catalog generation. ## Next Steps After following these guidelines: 1. Review with component-reviewer agent 2. Fix any issues identified 3. Update component catalog 4. Test installation with `--dry-run` 5. Submit pull request See the [Testing Workflow](/contributing/testing) for comprehensive testing instructions. # Getting Started with Contributing Source: https://davila7-claude-code-templates-86.mintlify.app/contributing/getting-started Learn how to start contributing to Claude Code Templates We welcome contributions to Claude Code Templates! This guide will help you get started with contributing components, templates, and improvements to the project. ## Quick Start ```bash theme={null} # Fork the repository on GitHub # Then clone your fork git clone https://github.com/your-username/claude-code-templates.git cd claude-code-templates ``` ```bash theme={null} # Navigate to CLI tool directory cd cli-tool # Install dependencies npm install # Link for local testing npm link ``` ```bash theme={null} git checkout -b feature/your-contribution ``` Follow the guidelines in this documentation for your specific contribution type. ## What Can You Contribute? There are several ways to contribute to the project: ### Individual Components The easiest way to contribute is by adding individual components: * **Agents** (400+) - AI specialists for specific domains * **Commands** (225+) - Custom slash commands for workflows * **MCPs** (65+) - External service integrations * **Settings** (60+) - Claude Code configuration files * **Hooks** (45+) - Automation triggers * **Skills** - Modular capabilities using Anthropic's progressive disclosure pattern ### Complete Templates Templates are complete project configurations that include `CLAUDE.md`, `.claude/*` files, and `.mcp.json`. ### Additional Tools For advanced contributors, you can improve CLI tools like: * Analytics dashboard * Health check diagnostics * Chat monitor interface ## Before You Start Read our [Code of Conduct](https://github.com/davila7/claude-code-templates/blob/main/CODE_OF_CONDUCT.md) to ensure a respectful and inclusive environment for all contributors. ### Browse Existing Components Before creating a new component: 1. Visit [aitmpl.com](https://aitmpl.com) to browse existing components 2. Check if a similar component already exists 3. Review successful components for structure reference 4. Understand the naming conventions and patterns ### Prerequisites * **Node.js 14+** for the CLI tool * **npm or yarn** for package management * **Git** for version control * **Python 3.x** (optional, for component catalog generation) ## Your First Contribution All components must be reviewed using the `component-reviewer` agent before submitting. See [Component Guidelines](/contributing/component-guidelines) for details. A good first contribution is adding a simple agent or command: ```bash theme={null} # Create a new agent file cd cli-tool/components/agents/domain-experts/ touch your-agent-name.md ``` See the [Adding Components](/contributing/adding-components) guide for detailed instructions. ## Testing Your Changes Before submitting a pull request: ```bash theme={null} # Test component installation npx claude-code-templates@latest --agent your-agent --dry-run # Run test suite npm test ``` See the [Testing](/contributing/testing) guide for comprehensive testing workflows. ## Getting Help ### Community Support * **GitHub Issues** - [Report bugs or request features](https://github.com/davila7/claude-code-templates/issues) * **GitHub Discussions** - [Join community discussions](https://github.com/davila7/claude-code-templates/discussions) * **Documentation** - [Complete guides at docs.aitmpl.com](https://docs.aitmpl.com/) ### Quick Start Guides * Browse existing components at [aitmpl.com](https://aitmpl.com) * Check component examples in the repository * Review successful templates for best practices ## What We're Looking For ### High Priority Components * **Security Agents** - Security auditing, vulnerability scanning * **Performance Commands** - Optimization, profiling, monitoring * **Cloud MCPs** - AWS, Azure, GCP integrations * **Framework Agents** - React, Vue, Angular, Next.js specialists ### High Priority Templates * **Modern Frameworks** - Svelte, SvelteKit, Astro, Qwik * **Backend Frameworks** - NestJS, Fastify, Hono, tRPC * **Full-Stack** - T3 Stack, create-remix-app, SvelteKit * **Mobile** - React Native, Expo, Flutter ### Medium Priority Tools * **Analytics Enhancements** - Better visualizations, export options * **Chat Monitor Features** - Search, filtering, conversation history * **Health Check Improvements** - More diagnostic categories, fix suggestions ## Next Steps Learn how to create agents, commands, MCPs, hooks, and settings Best practices and quality standards for components Complete testing guide before submitting contributions Learn the process for publishing to npm ## Recognition All contributors are recognized in: * GitHub Contributors page * Release Notes for significant contributions * Community Discussions for helpful contributions Thank you for helping make Claude Code Templates better for everyone! # Publishing Workflow Source: https://davila7-claude-code-templates-86.mintlify.app/contributing/publishing Complete guide to publishing components and releases to npm This guide covers the complete publishing workflow for releasing components and updates to npm. ## Publishing Overview The Claude Code Templates project publishes to npm as [`claude-code-templates`](https://www.npmjs.com/package/claude-code-templates). The package provides the CLI tool that users run with `npx claude-code-templates@latest`. Current version: Check [package.json](https://github.com/davila7/claude-code-templates/blob/main/package.json) or run `npm view claude-code-templates version` ## Prerequisites ### 1. npm Account Setup * Create account at [npmjs.com](https://www.npmjs.com) * Request access to the `claude-code-templates` package (for maintainers) ### 2. npm Authentication Classic npm tokens were revoked in December 2025. You MUST use **granular access tokens**. Create a granular access token: 1. Go to [npmjs.com/settings/\~/tokens](https://www.npmjs.com/settings/~/tokens) 2. Click "Generate New Token" → "Granular Access Token" 3. Configure: * **Permissions**: Read and Write * **Packages**: Select `claude-code-templates` * **IP Allowlist**: Optional (for security) * **Bypass 2FA**: Enable (required for publishing) ```bash theme={null} # Store in environment variable (recommended) export NPM_TOKEN="npm_xxx..." # Or configure npm npm config set //registry.npmjs.org/:_authToken=$NPM_TOKEN ``` Never commit tokens to the repository. Always clean up after publishing: ```bash theme={null} npm config delete //registry.npmjs.org/:_authToken ``` ## Complete Publishing Workflow ### Step 1: Update Component Catalog Before publishing, regenerate the component catalog to include all changes: ```bash theme={null} # Generate updated catalog python scripts/generate_components_json.py # Verify catalog was updated ls -lh docs/components.json # Check for errors in output # Should show component counts and no errors ``` The script: * Scans all components in `cli-tool/components/` * Validates format and structure * Generates `docs/components.json` (\~2MB) * Runs security validation ### Step 2: Run Tests Ensure all tests pass before publishing: ```bash theme={null} # Run CLI test suite cd cli-tool npm test # Run API tests cd ../api npm install npm test # Test component installation cd .. npx claude-code-templates@latest --agent frontend-developer --dry-run ``` All tests must pass. Fix any failures before continuing. ### Step 3: Version Management Determine and update the version number: ```bash theme={null} # Check current published version npm view claude-code-templates version # Check local version cat package.json | grep '"version"' # Decide on version bump # - patch: 1.28.16 → 1.28.17 (bug fixes, minor updates) # - minor: 1.28.16 → 1.29.0 (new features, backward compatible) # - major: 1.28.16 → 2.0.0 (breaking changes) ``` #### Manual Version Update Edit `package.json` to bump the version: ```json theme={null} { "name": "claude-code-templates", "version": "1.28.17", // Increment this // ... } ``` #### Automated Version Bump Or use npm version command: ```bash theme={null} # Patch version (1.28.16 → 1.28.17) npm version patch # Minor version (1.28.16 → 1.29.0) npm version minor # Major version (1.28.16 → 2.0.0) npm version major ``` The local `package.json` version may drift from npm if published from CI. Always check `npm view claude-code-templates version` first. ### Step 4: Commit Version Bump Commit the version change: ```bash theme={null} # Stage version change git add package.json # If catalog was updated git add docs/components.json # Commit with version message git commit -m "chore: Bump version to 1.28.17" # Push to main git push origin main ``` ### Step 5: Publish to npm Publishing is irreversible. Double-check version and changes before publishing. ```bash theme={null} # Configure npm with token npm config set //registry.npmjs.org/:_authToken=$NPM_TOKEN # Publish to npm npm publish # Clean up token (IMPORTANT) npm config delete //registry.npmjs.org/:_authToken unset NPM_TOKEN ``` Expected output: ```bash theme={null} npm notice npm notice 📦 claude-code-templates@1.28.17 npm notice === Tarball Contents === npm notice 2.1kB package.json npm notice 11.2kB README.md npm notice === Tarball Details === npm notice name: claude-code-templates npm notice version: 1.28.17 npm notice package size: 123.4 kB npm notice unpacked size: 456.7 kB npm notice total files: 234 npm notice + claude-code-templates@1.28.17 ``` ### Step 6: Tag Release Create a Git tag for the release: ```bash theme={null} # Create tag git tag v1.28.17 # Push tag to GitHub git push origin v1.28.17 # Verify tag was created git tag -l ``` ### Step 7: Deploy Website Deploy the updated website with new components: ```bash theme={null} # Deploy to Vercel production vercel --prod # Or use deployment script npm run deploy:site # Monitor deployment vercel logs aitmpl.com --follow ``` For production deployments, always use the deployer agent (`.claude/agents/deployer.md`) which runs pre-deploy checks. ### Step 8: Verify Release Verify the release was successful: ```bash theme={null} # Check npm shows new version npm view claude-code-templates version # Should show: 1.28.17 # Test installation from npm npx claude-code-templates@latest --version # Test component installation npx claude-code-templates@latest --agent frontend-developer # Check website shows updated components curl https://aitmpl.com/components.json | jq '.agents | length' ``` ## Publishing Components Only If you're adding components without changing the CLI: ```bash theme={null} # 1. Update component catalog python scripts/generate_components_json.py # 2. Commit changes git add docs/components.json cli-tool/components/ git commit -m "feat: Add new agent for X" git push origin main # 3. Deploy website (no npm publish needed) vercel --prod ``` Users will see new components immediately on the website. The CLI will fetch them from GitHub. ## Version Numbering Guidelines ### Patch Version (x.x.X) Increment for: * Bug fixes * Documentation updates * Minor component improvements * Security patches ### Minor Version (x.X.0) Increment for: * New components added * New features (backward compatible) * Significant improvements * New CLI options ### Major Version (X.0.0) Increment for: * Breaking changes * Major architecture changes * Incompatible API changes * CLI breaking changes ## Rollback Procedure If a release has issues: ### 1. Deprecate Bad Version ```bash theme={null} # Deprecate the problematic version npm deprecate claude-code-templates@1.28.17 "This version has issues, use 1.28.16 instead" ``` ### 2. Publish Fixed Version ```bash theme={null} # Fix the issue # Bump to next patch version # Publish new version npm version patch npm publish ``` ### 3. Rollback Website ```bash theme={null} # List deployments vercel ls # Promote previous deployment vercel promote ``` npm does NOT allow unpublishing versions after 72 hours. You can only deprecate them. ## Common Issues ### "Version already exists" ```bash theme={null} # Error: This version already exists on npm # Solution: Bump version number npm version patch npm publish ``` ### "401 Unauthorized" ```bash theme={null} # Error: Authentication failed # Solution: Check token configuration npm config get //registry.npmjs.org/:_authToken # Reconfigure with correct token npm config set //registry.npmjs.org/:_authToken=$NPM_TOKEN ``` ### "403 Forbidden" ```bash theme={null} # Error: No permission to publish # Solution: Ensure token has correct permissions: # - Read and Write access # - Bypass 2FA enabled # - Correct package selected # Request maintainer access if needed ``` ### "EPUBLISHCONFLICT" ```bash theme={null} # Error: Another publish in progress # Solution: Wait a few minutes and retry # Or check npm for the published version npm view claude-code-templates version ``` ## npm Publishing Notes ### Granular Access Tokens * **Classic tokens** were revoked December 2025 * Use **granular access tokens** from [npmjs.com/settings/\~/tokens](https://www.npmjs.com/settings/~/tokens) * Token must have: * **Read and Write** permissions for `claude-code-templates` * **"Bypass 2FA"** enabled (required for publishing) * Always remove token after publishing: `npm config delete` ### Package Scope Package is unscoped (`claude-code-templates` not `@org/claude-code-templates`): * Simpler installation: `npx claude-code-templates` * No organization required * Public package (not private) ### .npmignore Files excluded from npm package: ```bash theme={null} # See .npmignore in project root .git/ .github/ node_modules/ tests/ *.test.js .env ``` ## Publishing Checklist Before publishing: ```bash theme={null} python scripts/generate_components_json.py ``` ✅ No errors during generation ```bash theme={null} npm test cd api && npm test ``` ✅ All tests passing ```bash theme={null} # Check version is incremented cat package.json | grep version ``` ✅ Version bumped correctly ```bash theme={null} git status ``` ✅ All changes committed and pushed ```bash theme={null} npm config get //registry.npmjs.org/:_authToken ``` ✅ Token configured correctly ```bash theme={null} npm publish ``` ✅ Published successfully ```bash theme={null} git tag v1.28.17 && git push origin v1.28.17 ``` ✅ Git tag created ```bash theme={null} vercel --prod ``` ✅ Website deployed ```bash theme={null} npm config delete //registry.npmjs.org/:_authToken ``` ✅ Token removed ```bash theme={null} npm view claude-code-templates version npx claude-code-templates@latest --version ``` ✅ Version verified on npm ## Post-Publishing After successful publishing: ### 1. Announce Release * Update GitHub Discussions * Post in Discord community * Tweet about new features (if significant) ### 2. Monitor for Issues ```bash theme={null} # Monitor npm downloads npm view claude-code-templates # Monitor GitHub issues # Check for new issues related to release # Monitor Vercel logs vercel logs aitmpl.com --follow ``` ### 3. Update Documentation * Update CHANGELOG.md with release notes * Update README.md if features changed * Update docs site if needed ## Next Steps Best practices for creating components Complete testing guide Project architecture overview Coding conventions and style # Testing Workflow Source: https://davila7-claude-code-templates-86.mintlify.app/contributing/testing Complete testing guide for component contributions This guide covers the testing workflow for components, templates, and tools before submitting contributions. ## Testing Philosophy All components must be tested before submission. Testing ensures components install correctly, work as expected, and don't break existing functionality. Aim for **70%+ test coverage** on critical paths and error handling. ## Component Testing ### Dry-Run Installation Test component installation without making changes: ```bash theme={null} # Test agent installation npx claude-code-templates@latest --agent your-agent --dry-run # Test command installation npx claude-code-templates@latest --command your-command --dry-run # Test hook installation npx claude-code-templates@latest --hook automation/your-hook --dry-run # Test MCP installation npx claude-code-templates@latest --mcp your-mcp --dry-run # Test setting installation npx claude-code-templates@latest --setting your-setting --dry-run ``` Dry-run should: * Download component files successfully * Show what would be installed * Not create any files * Not show any errors ### Actual Installation Test Test real installation in a test project: ```bash theme={null} # Create test directory mkdir /tmp/test-project cd /tmp/test-project # Initialize a basic project git init npm init -y # Install your component npx claude-code-templates@latest --agent your-agent # Verify installation ls -la .claude/agents/ cat .claude/agents/your-agent.md # Test the component works # (Component-specific testing) # Cleanup cd .. rm -rf test-project ``` ### Component-Specific Testing #### Testing Agents ```bash theme={null} # After installing agent cd /tmp/test-project # 1. Verify file was created test -f .claude/agents/your-agent.md && echo "✅ Agent file exists" || echo "❌ Agent file missing" # 2. Verify YAML frontmatter is valid head -20 .claude/agents/your-agent.md # 3. Test with Claude Code (if available) # Use the agent in a real Claude Code session ``` #### Testing Commands ```bash theme={null} # After installing command cd /tmp/test-project # 1. Verify file was created test -f .claude/commands/your-command.md && echo "✅ Command file exists" || echo "❌ Command file missing" # 2. Verify YAML frontmatter is valid head -20 .claude/commands/your-command.md # 3. Test command execution (if Claude Code available) # Use /your-command in Claude Code session ``` #### Testing Hooks ```bash theme={null} # After installing hook cd /tmp/test-project # 1. Verify hook was installed test -f .claude/settings.json && echo "✅ Settings file exists" || echo "❌ Settings file missing" # 2. Check hook configuration in settings cat .claude/settings.json | grep -A 5 "hooks" # 3. Verify supporting scripts (if any) if [ -f .claude/hooks/your-hook.py ]; then echo "✅ Supporting script exists" # Test script syntax python3 -m py_compile .claude/hooks/your-hook.py fi # 4. Test hook execution (trigger the event) # For PostToolUse hooks: trigger a tool use # For PreToolUse hooks: trigger before tool use ``` #### Testing MCPs ```bash theme={null} # After installing MCP cd /tmp/test-project # 1. Verify MCP configuration test -f .mcp.json && echo "✅ MCP config exists" || echo "❌ MCP config missing" # 2. Validate JSON structure cat .mcp.json | jq . > /dev/null && echo "✅ Valid JSON" || echo "❌ Invalid JSON" # 3. Check MCP server configuration cat .mcp.json | jq '.mcpServers' # 4. Test MCP connection (if service available) # This requires the actual service to be running ``` #### Testing Settings ```bash theme={null} # After installing setting cd /tmp/test-project # 1. Verify settings file test -f .claude/settings.json && echo "✅ Settings file exists" || echo "❌ Settings file missing" # 2. Validate JSON structure cat .claude/settings.json | jq . > /dev/null && echo "✅ Valid JSON" || echo "❌ Invalid JSON" # 3. Verify setting is properly merged cat .claude/settings.json | jq . ``` ## Template Testing Test complete template installations: ```bash theme={null} # Test template installation (dry-run) npx claude-code-templates@latest --template your-template --dry-run # Test with specific scenarios npm start -- --language python --framework django --dry-run npm start -- --language javascript --framework react --dry-run # Test actual installation mkdir /tmp/test-template cd /tmp/test-template npx claude-code-templates@latest --template your-template # Verify all files were created ls -la cat CLAUDE.md cat .claude/settings.json cat .mcp.json # Test template-specific commands # Use template commands in Claude Code session ``` ### Template Quality Checks * [ ] CLAUDE.md is comprehensive and well-documented * [ ] All referenced files exist * [ ] Commands work as expected * [ ] MCPs are properly configured * [ ] Settings are valid and complete * [ ] No hardcoded secrets or paths * [ ] Documentation includes usage examples ## Tool Testing For contributors working on additional tools (analytics, health check, chat monitor): ### Analytics Dashboard ```bash theme={null} cd cli-tool # Start analytics dashboard npm run analytics:start # In another terminal, test API endpoints curl http://localhost:3333/api/health curl http://localhost:3333/api/conversations # Clear cache during testing curl -X POST http://localhost:3333/api/cache/clear \ -H "Content-Type: application/json" \ -d '{"type":"all"}' # Refresh data curl http://localhost:3333/api/refresh # Test WebSocket connection # Open browser to http://localhost:3333 # Verify real-time updates work # Restart server completely pkill -f analytics && sleep 3 && npm run analytics:start ``` ### Chat Monitor ```bash theme={null} cd cli-tool # Start chat monitor npm run chats:start # Test with tunnel (requires cloudflared) npm run chats:start -- --tunnel # Test mobile interface npm run chats:test # Verify mobile responsiveness # Open on mobile device or use browser dev tools ``` ### Health Check ```bash theme={null} cd cli-tool # Run health check npm run health-check # Test with various scenarios # - Fresh installation # - Existing project with components # - Project with issues # - Project with optimal setup # Verify all checks run # Verify recommendations are helpful # Verify no false positives ``` ## Automated Testing ### Running Test Suite ```bash theme={null} cd cli-tool # Run all tests npm test # Run in watch mode npm run test:watch # Run with coverage npm run test:coverage # View coverage report open coverage/index.html ``` ### API Endpoint Testing ALWAYS test API endpoints before deploying to production. Broken endpoints can affect download tracking and analytics. ```bash theme={null} cd api # Install dependencies npm install # Run API tests npm test # Test specific endpoints curl -X POST http://localhost:3000/api/track-download-supabase \ -H "Content-Type: application/json" \ -d '{ "component_type": "agent", "component_name": "test-agent", "component_category": "test" }' ``` ## Component Reviewer Validation This is a REQUIRED step before submitting any component. Use the component-reviewer agent to validate your component: ```bash theme={null} # Review single component Use the component-reviewer agent to review cli-tool/components/agents/development-team/your-agent.md # Review multiple components Use the component-reviewer agent to review all modified components in cli-tool/components/ ``` The reviewer checks: * ✅ Valid format and structure * ✅ Required fields present * ✅ Proper naming conventions * ✅ No security issues * ✅ Supporting files exist * ✅ Best practices followed Fix all critical issues before proceeding. ## Integration Testing Test how your component works with existing components: ```bash theme={null} # Install your component with related components npx claude-code-templates@latest \ --agent your-agent \ --command related-command \ --hook automation/notifications # Verify they work together # Test agent uses command properly # Test hooks trigger correctly # Test no conflicts occur ``` ## Performance Testing For components that may affect performance: ```bash theme={null} # Test installation speed time npx claude-code-templates@latest --agent your-agent # Test file size du -h .claude/agents/your-agent.md # Test catalog generation time python scripts/generate_components_json.py # Check catalog size du -h docs/components.json ``` ## Regression Testing Ensure your changes don't break existing functionality: ```bash theme={null} # Test existing components still work npx claude-code-templates@latest --agent frontend-developer npx claude-code-templates@latest --command generate-tests # Test batch installation npx claude-code-templates@latest \ --agent frontend-developer \ --command generate-tests \ --setting read-only-mode # Test interactive mode npx claude-code-templates@latest # Navigate through menus # Verify all options work ``` ## Pre-Submission Checklist Before submitting your pull request: ```bash theme={null} Use the component-reviewer agent to review [your-component] ``` Fix all critical issues. ```bash theme={null} npx claude-code-templates@latest --[type] your-component --dry-run ``` Verify no errors. ```bash theme={null} # In test project npx claude-code-templates@latest --[type] your-component ``` Verify files created correctly. ```bash theme={null} python scripts/generate_components_json.py ``` Verify no errors during generation. ```bash theme={null} npm test ``` All tests should pass. ```bash theme={null} cd api && npm test ``` Verify endpoints still work. ## Common Testing Issues ### Component Not Found ```bash theme={null} # Issue: Component not in catalog # Fix: Regenerate catalog python scripts/generate_components_json.py # Verify component appears cat docs/components.json | jq '.agents[] | select(.name=="your-agent")' ``` ### Installation Fails ```bash theme={null} # Issue: Installation errors # Check: File paths are correct # Check: No hardcoded absolute paths # Check: Required fields present # Check: JSON/YAML is valid # Debug with dry-run npx claude-code-templates@latest --agent your-agent --dry-run ``` ### Hook Not Triggering ```bash theme={null} # Issue: Hook doesn't execute # Check: Hook is in settings.json cat .claude/settings.json | jq '.hooks' # Check: Matcher is correct # Check: Command syntax is valid # Check: Supporting scripts have correct permissions ls -la .claude/hooks/ ``` ## Next Steps After successful testing: 1. Commit your changes 2. Push to your fork 3. Submit pull request See the [Publishing Workflow](/contributing/publishing) for the complete submission process. # Batch Component Installation Source: https://davila7-claude-code-templates-86.mintlify.app/guides/batch-installation Install multiple agents, commands, MCPs, settings, and hooks in a single command for faster setup # Batch Component Installation Batch installation allows you to install multiple components across different types in a single command. This is ideal for setting up new projects, sharing team configurations, or deploying standardized development environments. ## Why Batch Install? Install 10 components in one command instead of running 10 separate commands Ensure all team members have the same components installed Script entire project setups in CI/CD pipelines Share component bundles with colleagues via single command ## Basic Batch Installation Combine multiple component flags in a single command: ```bash theme={null} npx claude-code-templates@latest \ --agent security-auditor \ --agent frontend-developer \ --command setup-testing \ --mcp filesystem \ --setting enable-telemetry ``` **Flag Order**: Component flags can appear in any order. The CLI installs them sequentially. ## Multi-Type Installation ### Install Agents and Commands ```bash theme={null} npx claude-code-templates@latest \ --agent backend-developer \ --agent database-expert \ --command docker-setup \ --command git-setup ``` Installs: * `.claude/agents/backend-developer.md` * `.claude/agents/database-expert.md` * `.claude/commands/docker-setup.md` * `.claude/commands/git-setup.md` ### Add MCPs and Settings ```bash theme={null} npx claude-code-templates@latest \ --agent security-auditor \ --mcp web-fetch \ --mcp filesystem \ --setting read-only-mode ``` Installs: * `.claude/agents/security-auditor.md` * Merges MCP configs into `.mcp.json` * Prompts for settings installation location ### Include Hooks ```bash theme={null} npx claude-code-templates@latest \ --agent code-reviewer \ --command lint-code \ --hook git/prevent-force-push \ --setting use-sonnet ``` Installs: * Agent and command files * Hook configuration in settings * Model preference setting ## Comma-Separated Values You can use comma-separated values for the same component type: ```bash theme={null} npx claude-code-templates@latest \ --agent "security-auditor,frontend-developer,backend-developer" \ --command "docker-setup,git-setup,setup-testing" ``` **Quoting Required**: When using commas, wrap the entire value in quotes to prevent shell interpretation. ## Batch with Directory Target Install all components to a specific project: ```bash theme={null} npx claude-code-templates@latest \ --agent security-auditor \ --agent performance-optimizer \ --command security-scan \ --directory ./my-project ``` ## Batch with Auto-Confirm Skip all prompts using `--yes`: ```bash theme={null} npx claude-code-templates@latest \ --agent security-auditor \ --mcp web-fetch \ --setting enable-telemetry \ --yes ``` The `--yes` flag: * Uses default installation locations for settings/hooks (local settings) * Auto-confirms all merge operations * Skips interactive prompts * Ideal for CI/CD and scripted installations ## Settings and Hooks Location When batch installing settings or hooks, you can pre-specify the installation location: ### Method 1: Interactive (Default) ```bash theme={null} npx claude-code-templates@latest \ --setting enable-telemetry \ --hook git/pre-commit-lint ``` You'll be prompted once for where to install ALL settings and hooks: ```bash theme={null} ? Where would you like to install these components? ◯ User settings (~/.claude/settings.json) ◯ Project settings (.claude/settings.json) ◉ Local settings (.claude/settings.local.json) ``` ### Method 2: Auto with --yes ```bash theme={null} npx claude-code-templates@latest \ --setting enable-telemetry \ --hook git/pre-commit-lint \ --yes ``` Automatically installs to **local settings** (`.claude/settings.local.json`). ## Use Cases ### New Project Setup Complete development environment in one command: ```bash Full-Stack Setup theme={null} npx claude-code-templates@latest \ --agent frontend-developer \ --agent backend-developer \ --agent database-expert \ --command docker-setup \ --command setup-testing \ --mcp filesystem \ --mcp web-fetch \ --setting use-sonnet \ --directory ./new-project ``` ```bash Security-Focused Setup theme={null} npx claude-code-templates@latest \ --agent security-auditor \ --agent penetration-tester \ --command security-scan \ --command vulnerability-check \ --setting read-only-mode \ --hook security/secrets-detection \ --yes ``` ```bash Data Science Setup theme={null} npx claude-code-templates@latest \ --agent data-scientist \ --agent ml-engineer \ --agent data-analyst \ --command notebook-setup \ --mcp database \ --setting retention-90-days ``` ### Team Standardization Ensure all team members have consistent tooling: ```bash theme={null} # Add to README.md or onboarding script npx claude-code-templates@latest \ --agent code-reviewer \ --agent documentation-writer \ --command lint-code \ --command generate-tests \ --hook git/pre-commit-lint \ --hook automation/simple-notifications \ --yes ``` ### CI/CD Pipeline Script component installation in your CI pipeline: ```yaml GitHub Actions theme={null} name: Setup Claude Code on: [push] jobs: setup: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install Claude Code Components run: | npx claude-code-templates@latest \ --agent code-reviewer \ --command lint-code \ --command security-scan \ --yes ``` ```yaml GitLab CI theme={null} setup-claude: stage: setup script: - npx claude-code-templates@latest --agent security-auditor --command vulnerability-check --mcp filesystem --yes only: - main ``` ```groovy Jenkins theme={null} stage('Setup Claude Code') { steps { sh ''' npx claude-code-templates@latest \ --agent performance-optimizer \ --command profile-app \ --yes ''' } } ``` ### Docker Container Setup Include in your Dockerfile: ```dockerfile theme={null} FROM node:20-alpine WORKDIR /app # Install Claude Code components RUN npx claude-code-templates@latest \ --agent backend-developer \ --command docker-setup \ --mcp filesystem \ --yes COPY . . CMD ["npm", "start"] ``` ## Component Discovery for Batch Installation ### Use the Shopping Cart 1. Visit [aitmpl.com](https://aitmpl.com) 2. Browse and add components to cart 3. Click "View Cart" 4. Copy the generated batch command ```bash theme={null} # Example generated command npx claude-code-templates@latest \ --agent security-auditor \ --agent frontend-developer \ --command setup-testing \ --mcp web-fetch ``` ### Share Cart URLs The cart URL contains all selected components: ``` https://aitmpl.com/?cart=agent:security-auditor,agent:frontend-developer,command:setup-testing ``` Share this URL with teammates to install the same component set. ### Export from Interactive Mode Run interactive mode and export your selection: ```bash theme={null} npx claude-code-templates@latest ``` 1. Select "Project Setup" 2. Choose components interactively 3. At the end, get the equivalent batch command ## Batch Installation Output The CLI provides detailed progress for batch installations: ```bash theme={null} $ npx claude-code-templates@latest \ --agent security-auditor \ --command security-scan \ --mcp web-fetch 🤖 Installing agent: security-auditor 📥 Downloading from GitHub (main branch)... ✅ Agent "security-auditor" installed successfully! 📁 Installed to: .claude/agents/security-auditor.md ⚡ Installing command: security-scan 📥 Downloading from GitHub (main branch)... ✅ Command "security-scan" installed successfully! 📁 Installed to: .claude/commands/security-scan.md 🔌 Installing MCP: web-fetch 📥 Downloading from GitHub (main branch)... 📝 Existing .mcp.json found, merging configurations... ✅ MCP "web-fetch" installed successfully! 📁 Configuration merged into: .mcp.json 🎉 Batch installation complete! Installed 3 components. ``` ## Error Handling Batch installations handle errors gracefully: ### Partial Success If one component fails, others continue: ```bash theme={null} ✅ Agent "security-auditor" installed successfully! ❌ Command "non-existent-command" not found ✅ MCP "web-fetch" installed successfully! ⚠️ Batch installation completed with errors. Successful: 2/3 components Failed: 1/3 components ``` ### Rollback Not Supported **No Automatic Rollback**: If a component fails, previously installed components are NOT automatically removed. This is intentional to prevent data loss. To undo: ```bash theme={null} # Manually remove installed components rm .claude/agents/security-auditor.md rm .claude/commands/security-scan.md ``` ## Best Practices ### 1. Group by Purpose Organize batch commands by project type: ```bash theme={null} # Save as scripts/setup-frontend.sh npx claude-code-templates@latest \ --agent frontend-developer \ --agent ui-ux-designer \ --command setup-react \ --command setup-testing \ --mcp web-fetch \ --yes ``` ### 2. Document in README Add setup instructions to your project: ```markdown theme={null} ## Claude Code Setup Install required components: \`\`\`bash npx claude-code-templates@latest \ --agent backend-developer \ --command docker-setup \ --mcp database \ --yes \`\`\` ``` ### 3. Use Version Pinning For reproducibility, pin to a specific version: ```bash theme={null} npx claude-code-templates@1.2.3 \ --agent security-auditor \ --command security-scan ``` ### 4. Separate Concerns Split personal vs. team components: ```bash theme={null} # Team setup (in repo docs) npx claude-code-templates@latest \ --agent code-reviewer \ --command lint-code \ --yes # Personal setup (in private notes) npx claude-code-templates@latest \ --agent ai-assistant \ --setting theme-dark \ --yes ``` ## Combining with Workflows You can combine batch installation with workflow YAML: ```bash theme={null} # Install components and apply workflow npx claude-code-templates@latest \ --agent security-auditor \ --command security-scan \ --workflow "$(cat workflow.yaml | base64)" ``` See [Workflows Guide](/guides/workflows) for details. ## Troubleshooting ### Command Too Long If your batch command is very long: **Solution 1: Use a Script** ```bash theme={null} #!/bin/bash # setup-components.sh npx claude-code-templates@latest \ --agent security-auditor \ --agent frontend-developer \ --agent backend-developer \ --command docker-setup \ --command setup-testing \ --mcp filesystem \ --mcp web-fetch \ --yes ``` ```bash theme={null} chmod +x setup-components.sh ./setup-components.sh ``` **Solution 2: Use Workflow Hashes** Create a workflow at [aitmpl.com/workflows](https://aitmpl.com/workflows) and use the short hash: ```bash theme={null} npx claude-code-templates@latest --workflow:#abc123def456 ``` ### Permission Issues If batch install fails on specific components: ```bash theme={null} ✅ Agent installed ❌ Failed to write settings: Permission denied ✅ MCP installed ``` **Solution**: Install settings to user directory: ```bash theme={null} npx claude-code-templates@latest \ --setting enable-telemetry \ --yes # Auto-installs to local settings ``` ### Network Timeouts Large batch installs may timeout: ```bash theme={null} ❌ Error: Request timeout after 30s ``` **Solution**: Split into smaller batches: ```bash theme={null} # Batch 1: Agents npx claude-code-templates@latest \ --agent security-auditor \ --agent frontend-developer \ --yes # Batch 2: Commands and MCPs npx claude-code-templates@latest \ --command docker-setup \ --mcp filesystem \ --yes ``` ## Next Steps Use the visual component selector Create reusable installation workflows Create globally accessible agents Browse all available components # Global Agents Source: https://davila7-claude-code-templates-86.mintlify.app/guides/global-agents Create globally accessible AI agents that can be executed from any directory on your system # Global Agents Global agents are AI specialists that you can execute from anywhere on your system, just like any other terminal command. Instead of navigating to a project directory to use an agent, you can invoke it from any location. ## What are Global Agents? Global agents transform Claude Code agents into standalone CLI commands: * **Regular Agent**: Only works in the directory where installed (`.claude/agents/`) * **Global Agent**: Works from any directory, like `npm`, `git`, or `docker` Run from any directory without navigating to project Automatically detects project type and includes relevant files No need for Claude Code to be open Use in npm scripts, CI/CD, and shell scripts ## How Global Agents Work ### Installation Process 1. Download agent from GitHub 2. Store in `~/.claude-code-templates/agents/` 3. Generate executable wrapper script 4. Install to system bin directory (`/usr/local/bin` or `~/.claude-code-templates/bin`) 5. Add to PATH (if needed) ### Execution Flow 1. You run: `security-auditor "check this code"` 2. Wrapper script: * Loads agent system prompt from `~/.claude-code-templates/agents/security-auditor.md` * Detects project context (language, framework) * Auto-includes relevant files * Calls Claude CLI with agent context 3. Claude executes with agent persona and project awareness ## Creating Global Agents ### Basic Creation ```bash theme={null} npx claude-code-templates@latest --create-agent security-auditor ``` Output: ```bash theme={null} 🤖 Creating global agent: security-auditor 🌍 Installing to system directory (immediately available) 📥 Downloading agent from GitHub... ✅ Agent downloaded successfully ✅ Global agent 'security-auditor' created successfully! 📦 Usage: security-auditor "your prompt here" 🎉 Ready to use immediately! No setup required. 💡 Works in scripts, npm tasks, CI/CD, etc. ``` Now you can run from anywhere: ```bash theme={null} cd ~/projects/my-app security-auditor "audit this codebase for vulnerabilities" ``` ### With Category Path If the agent name is ambiguous, use the full category path: ```bash theme={null} npx claude-code-templates@latest --create-agent development-team/frontend-developer ``` ### Creating Multiple Global Agents Create several agents at once: ```bash theme={null} # Create security suite npx claude-code-templates@latest --create-agent security-auditor npx claude-code-templates@latest --create-agent penetration-tester npx claude-code-templates@latest --create-agent code-reviewer ``` ## Using Global Agents ### Basic Usage ```bash theme={null} "your prompt" ``` Examples: ```bash Security Audit theme={null} security-auditor "check this file for SQL injection vulnerabilities" ``` ```bash Code Review theme={null} code-reviewer "review the auth.js file for best practices" ``` ```bash Performance Analysis theme={null} performance-optimizer "analyze this React component for performance issues" ``` ```bash Documentation theme={null} documentation-writer "generate API documentation for this endpoint" ``` ### Auto-Context Detection Global agents automatically detect your project type and include relevant files: ```bash theme={null} cd ~/projects/my-react-app frontend-developer "add error boundary to this component" ``` The agent automatically: * Detects React project (from `package.json`) * Includes `src/`, `components/`, `pages/` directories * Understands React patterns and conventions * Can read files using the Read tool **Supported Project Types**: * **JavaScript/Node**: Detects from `package.json`, includes `src/`, `lib/`, `components/` * **Python**: Detects from `requirements.txt` or `pyproject.toml`, includes `*.py` files * **Go**: Detects from `go.mod`, includes `*.go`, `cmd/`, `internal/`, `pkg/` * **Rust**: Detects from `Cargo.toml`, includes `src/`, `Cargo.toml` * **React/Vue/Next.js**: Framework detection from dependencies ### Explicit File Selection Override auto-detection by specifying files: ```bash theme={null} security-auditor --file auth.js --file database.js "check these files" ``` ### Directory Targeting ```bash theme={null} code-reviewer --dir src/components "review all components" ``` ### Disable Auto-Detection For general advice without project context: ```bash theme={null} security-auditor --no-auto "explain OAuth 2.0 best practices" ``` ### Verbose Mode See what the agent is doing: ```bash theme={null} security-auditor --verbose "audit this code" ``` Outputs: ```bash theme={null} 🔍 DEBUG MODE - Command Details: ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 📝 User Input: audit this code 📁 Project Context: Auto-detected 🎯 Final Prompt Length: 234 characters 🤖 System Prompt Preview: You are a security auditor... ⚡ Claude Command: claude -p "audit this code..." --system-prompt "..." ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ``` ## Managing Global Agents ### List Installed Agents ```bash theme={null} npx claude-code-templates@latest --list-agents ``` Output: ```bash theme={null} 📋 Installed Global Agents: ✅ Found 3 global agent(s): ✅ security-auditor (🌍 system) Usage: security-auditor "your prompt" Created: 2/28/2026 ✅ frontend-developer (👤 user) Usage: frontend-developer "your prompt" Created: 2/27/2026 ✅ code-reviewer (🌍 system) Usage: code-reviewer "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 ``` ### Remove an Agent ```bash theme={null} npx claude-code-templates@latest --remove-agent security-auditor ``` Output: ```bash theme={null} 🗑️ Removing global agent: security-auditor ✅ Removed system executable: security-auditor ✅ Removed agent file: security-auditor.md 🎉 Global agent 'security-auditor' removed successfully! ``` ### Update an Agent Fetch the latest version from GitHub: ```bash theme={null} npx claude-code-templates@latest --update-agent security-auditor ``` Output: ```bash theme={null} 🔄 Updating global agent: security-auditor 🔄 Re-downloading latest version... 🌍 Installing to system directory (immediately available) 📥 Downloading agent from GitHub... ✅ Agent downloaded successfully ✅ Global agent 'security-auditor' created successfully! ``` ## Installation Locations ### System Directory (Recommended) If you have write access to `/usr/local/bin`, agents are installed there: ```bash theme={null} /usr/local/bin/security-auditor ~/.claude-code-templates/agents/security-auditor.md ``` ✅ **Advantages**: * Immediately available in PATH * No shell configuration needed * Works in all terminals and IDEs ### User Directory (Fallback) If system directory is not writable, uses user directory: ```bash theme={null} ~/.claude-code-templates/bin/security-auditor ~/.claude-code-templates/agents/security-auditor.md ``` ⚠️ **Requires PATH Setup**: The CLI automatically adds to your shell config: ```bash ~/.bashrc or ~/.zshrc theme={null} # Claude Code Templates - Global Agents export PATH="$HOME/.claude-code-templates/bin:$PATH" ``` Restart your terminal or run: ```bash theme={null} source ~/.bashrc # or ~/.zshrc ``` ## Advanced Usage ### In npm Scripts Add global agents to package.json: ```json package.json theme={null} { "scripts": { "audit": "security-auditor 'audit for vulnerabilities'", "review": "code-reviewer 'review src/ for improvements'", "optimize": "performance-optimizer 'analyze bundle size'" } } ``` ```bash theme={null} npm run audit npm run review npm run optimize ``` ### In Shell Scripts Create automation scripts: ```bash pre-commit.sh theme={null} #!/bin/bash # Run code review before commit code-reviewer "review staged changes" || exit 1 # Check for security issues security-auditor "scan staged files for vulnerabilities" || exit 1 echo "✅ Pre-commit checks passed" ``` ```bash theme={null} chmod +x pre-commit.sh ./pre-commit.sh ``` ### In CI/CD Pipelines ```yaml GitHub Actions theme={null} name: Code Review on: [pull_request] jobs: review: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Global Agent run: | npx claude-code-templates@latest --create-agent code-reviewer echo "$HOME/.claude-code-templates/bin" >> $GITHUB_PATH - name: Run Code Review run: code-reviewer "review all changes in this PR" ``` ```yaml GitLab CI theme={null} code-review: stage: test script: - npx claude-code-templates@latest --create-agent code-reviewer - export PATH="$HOME/.claude-code-templates/bin:$PATH" - code-reviewer "review MR changes" only: - merge_requests ``` ### In Docker Containers ```dockerfile theme={null} FROM node:20-alpine WORKDIR /app # Install global agent RUN npx claude-code-templates@latest --create-agent security-auditor ENV PATH="$HOME/.claude-code-templates/bin:$PATH" COPY . . # Use agent in container RUN security-auditor "audit codebase" CMD ["npm", "start"] ``` ## Custom Global Agents You can create custom global agents by: 1. Creating a custom agent in `.claude/agents/` 2. Publishing to GitHub 3. Installing as global agent ### Create Custom Agent ```markdown .claude/agents/my-custom-agent.md theme={null} --- name: my-custom-agent description: Custom agent for my specific needs tools: Read, Write, Bash model: sonnet --- You are a custom agent that specializes in... [Agent instructions here] ``` ### Publish to GitHub ```bash theme={null} # Push to your repo git add .claude/agents/my-custom-agent.md git commit -m "Add custom agent" git push ``` ### Install as Global Currently, global agents must be in the official repository. For custom agents: **Workaround**: Manually create global wrapper: ```bash theme={null} # 1. Copy agent to global location mkdir -p ~/.claude-code-templates/agents cp .claude/agents/my-custom-agent.md ~/.claude-code-templates/agents/ # 2. Create wrapper script cat > ~/.claude-code-templates/bin/my-custom-agent << 'EOF' #!/usr/bin/env node const { execSync } = require('child_process'); const fs = require('fs'); const os = require('os'); const path = require('path'); const agentPath = path.join(os.homedir(), '.claude-code-templates/agents/my-custom-agent.md'); const systemPrompt = fs.readFileSync(agentPath, 'utf8').replace(/^---[\s\S]*?---\n/, '').trim(); const userInput = process.argv.slice(2).join(' '); if (!userInput) { console.error('Usage: my-custom-agent "your prompt"'); process.exit(1); } const cmd = `claude -p "${userInput}" --system-prompt "${systemPrompt}"`; execSync(cmd, { stdio: 'inherit' }); EOF # 3. Make executable chmod +x ~/.claude-code-templates/bin/my-custom-agent # 4. Use it my-custom-agent "your prompt" ``` ## Troubleshooting ### Command Not Found If you get `command not found` after creating a global agent: ```bash theme={null} $ security-auditor "test" bash: security-auditor: command not found ``` **Solutions**: 1. **Check PATH**: ```bash theme={null} echo $PATH | grep -q ".claude-code-templates" && echo "PATH OK" || echo "PATH missing" ``` 2. **Add to PATH manually**: ```bash theme={null} # Add to ~/.bashrc or ~/.zshrc export PATH="$HOME/.claude-code-templates/bin:$PATH" # Reload shell config source ~/.bashrc # or source ~/.zshrc ``` 3. **Use absolute path**: ```bash theme={null} ~/.claude-code-templates/bin/security-auditor "test" ``` ### Permission Denied ```bash theme={null} $ security-auditor "test" bash: /usr/local/bin/security-auditor: Permission denied ``` **Solution**: Make executable: ```bash theme={null} sudo chmod +x /usr/local/bin/security-auditor ``` ### Claude CLI Not Found Global agents require Claude CLI: ```bash theme={null} ❌ Claude CLI not found in PATH 💡 Install Claude CLI: https://claude.ai/code 💡 Or install via npm: npm install -g @anthropic-ai/claude-code ``` **Solution**: Install Claude CLI: ```bash theme={null} npm install -g @anthropic-ai/claude-code # Verify claude --version ``` ### Agent File Not Found ```bash theme={null} ❌ Agent file not found: ~/.claude-code-templates/agents/security-auditor.md ``` **Solution**: Recreate the global agent: ```bash theme={null} npx claude-code-templates@latest --create-agent security-auditor ``` ### Context Detection Not Working If the agent doesn't detect your project: ```bash theme={null} security-auditor --verbose "test" # Check if "Project type: unknown" in debug output ``` **Solution**: Manually specify files: ```bash theme={null} security-auditor --file auth.js --file api.js "audit these files" ``` ## Best Practices ### 1. Name Agents Descriptively ✅ Good: ```bash theme={null} security-auditor frontend-developer api-documentation-writer ``` ❌ Bad: ```bash theme={null} sa dev docs ``` ### 2. Use for Specialized Tasks Global agents work best for: * Security audits * Code reviews * Documentation generation * Performance analysis * Compliance checks Not ideal for: * General chatting * Multi-step projects * Interactive sessions ### 3. Combine with Shell Aliases ```bash ~/.bashrc theme={null} alias audit="security-auditor" alias review="code-reviewer" alias docs="documentation-writer" ``` ```bash theme={null} audit "check auth.js" review "analyze src/" docs "generate API docs" ``` ### 4. Create Agent Sets Install related agents together: ```bash theme={null} # Security suite npx claude-code-templates@latest --create-agent security-auditor npx claude-code-templates@latest --create-agent penetration-tester npx claude-code-templates@latest --create-agent compliance-checker # Development suite npx claude-code-templates@latest --create-agent frontend-developer npx claude-code-templates@latest --create-agent backend-developer npx claude-code-templates@latest --create-agent devops-engineer ``` ### 5. Document in Team README ```markdown README.md theme={null} ## Global Agents This project uses global Claude Code agents: \`\`\`bash # Setup (one-time) npx claude-code-templates@latest --create-agent security-auditor npx claude-code-templates@latest --create-agent code-reviewer # Usage security-auditor "audit for vulnerabilities" code-reviewer "review my changes" \`\`\` ``` ## Next Steps Learn about regular component installation Install multiple components at once Create reusable installation workflows Browse all available agents # Installing Individual Components Source: https://davila7-claude-code-templates-86.mintlify.app/guides/installing-components Learn how to install individual agents, commands, MCPs, settings, hooks, and skills from the Claude Code Templates library # Installing Individual Components Claude Code Templates provides over 600 individual components that you can install one at a time. Each component type serves a specific purpose in your development workflow. ## Component Types Before installing, understand what each component type does: * **Agents** (162+) - AI specialists for specific tasks (e.g., `security-auditor`, `frontend-developer`) * **Commands** (210+) - Custom slash commands for workflows (e.g., `/setup-testing`, `/docker-setup`) * **MCPs** (65+) - Model Context Protocol integrations for external services * **Settings** (60+) - Configuration files for Claude Code behavior * **Hooks** (45+) - Automation triggers for events (e.g., before bash, after file edit) * **Skills** - Specialized knowledge domains for Claude to reference ## Installation Syntax All components follow the same installation pattern: ```bash Individual Component theme={null} npx claude-code-templates@latest --{type} {component-name} ``` ```bash With Directory theme={null} npx claude-code-templates@latest --{type} {component-name} --directory ./my-project ``` ```bash Skip Prompts theme={null} npx claude-code-templates@latest --{type} {component-name} --yes ``` ## Installing Agents Agents are AI specialists stored in `.claude/agents/`. ### Browse Available Agents Visit [aitmpl.com](https://aitmpl.com) and filter by "Agents" to explore 162+ available agents organized by category: * **Development Team** - Full-stack, frontend, backend developers * **Security** - Security auditors, penetration testers * **Data/AI** - ML engineers, data scientists * **DevOps** - Cloud architects, infrastructure specialists * **Business** - Product managers, project managers ### Install an Agent ```bash theme={null} npx claude-code-templates@latest --agent frontend-developer ``` You can use either the component name or the full category path: ```bash theme={null} # Both work npx claude-code-templates@latest --agent frontend-developer npx claude-code-templates@latest --agent development-team/frontend-developer ``` ### Verify Installation ```bash theme={null} ls .claude/agents/ # Should show: frontend-developer.md ``` ### Use the Agent In Claude Code, reference the agent: ``` Use the frontend-developer agent to review this React component for performance issues ``` **Agent Discovery**: Can't find an agent? Use the search on [aitmpl.com](https://aitmpl.com) to search by description, category, or use case. ## Installing Commands Commands are custom slash commands stored in `.claude/commands/`. ### Find a Command Browse commands by category at [aitmpl.com/commands](https://aitmpl.com): * **Automation** - CI/CD, workflow automation * **Development** - Git, testing, project setup * **DevOps** - Docker, deployment, infrastructure * **Security** - Vulnerability scanning, audit tools ### Install a Command ```bash theme={null} npx claude-code-templates@latest --command setup-testing ``` ### View Command Details ```bash theme={null} cat .claude/commands/setup-testing.md ``` ### Execute the Command In Claude Code: ``` /setup-testing jest ``` ## Installing MCPs MCPs (Model Context Protocols) enable external service integrations. They merge into `.mcp.json`. ### Install an MCP ```bash theme={null} npx claude-code-templates@latest --mcp filesystem ``` **Automatic Merging**: MCP configurations are automatically merged with your existing `.mcp.json`. The CLI will prompt if conflicts are detected. ### Verify MCP Configuration ```bash theme={null} cat .mcp.json ``` Expected output: ```json theme={null} { "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"] } } } ``` ### Restart Claude Code MCP changes require a restart to take effect. ## Installing Settings Settings configure Claude Code behavior. You can install them at multiple levels. ### Install a Setting ```bash theme={null} npx claude-code-templates@latest --setting enable-telemetry ``` ### Choose Installation Location The CLI will prompt you to select one or more locations: * **User settings** (`~/.claude/settings.json`) - Applies to all projects * **Project settings** (`.claude/settings.json`) - Shared with team via git * **Local settings** (`.claude/settings.local.json`) - Personal, gitignored * **Enterprise settings** - System-wide policy (requires admin) Settings are loaded in this order (later overrides earlier): 1. Enterprise managed settings 2. User settings (`~/.claude/settings.json`) 3. Project settings (`.claude/settings.json`) 4. Local settings (`.claude/settings.local.json`) This allows personal preferences to override team settings. ### Verify Settings ```bash theme={null} cat .claude/settings.local.json ``` **Conflict Detection**: The CLI checks for conflicts when merging settings. If a setting already exists with a different value, you'll be prompted to confirm overwrite. ## Installing Hooks Hooks enable event-driven automation. They're stored in settings files. ### Install a Hook ```bash theme={null} npx claude-code-templates@latest --hook automation/simple-notifications ``` ### Choose Hook Location Same as settings, you'll choose where to install: ```bash theme={null} ? Where would you like to install this hook? ◯ User settings - Applies to all projects ◯ Project settings - Shared with team ◉ Local settings - Personal only ``` ### View Hook Configuration ```bash theme={null} cat .claude/settings.local.json ``` Expected structure: ```json theme={null} { "hooks": { "SessionStart": [ { "matcher": "startup", "hooks": [ { "type": "command", "command": "echo 'Session started!'" } ] } ] } } ``` ### Test the Hook Restart Claude Code or trigger the hook event to see it in action. ## Installing Skills Skills provide specialized knowledge domains for Claude to reference. ### Install a Skill ```bash theme={null} npx claude-code-templates@latest --skill typescript-expert ``` ### Verify Installation ```bash theme={null} ls .claude/skills/ # Should show skill directory with SKILL.md and references/ ``` ### Use the Skill In Claude Code: ``` Use the typescript-expert skill to help me configure strict TypeScript ``` ## Component Naming Conventions All components follow **kebab-case** naming: ✅ **Correct**: ```bash theme={null} --agent frontend-developer --command setup-testing --mcp web-fetch ``` ❌ **Incorrect**: ```bash theme={null} --agent frontendDeveloper --agent Frontend-Developer --agent frontend_developer ``` ## Common Installation Flags ### Directory Target Install to a specific directory: ```bash theme={null} npx claude-code-templates@latest --agent security-auditor --directory /path/to/project ``` ### Skip Prompts Use defaults without confirmation: ```bash theme={null} npx claude-code-templates@latest --agent security-auditor --yes ``` ### Dry Run Preview what would be installed without making changes: ```bash theme={null} npx claude-code-templates@latest --agent security-auditor --dry-run ``` ### Verbose Logging Enable detailed installation logs: ```bash theme={null} npx claude-code-templates@latest --agent security-auditor --verbose ``` ## Viewing Component Details Before installing, you can view component details on the web: ### Visit the Component Browser Go to [aitmpl.com](https://aitmpl.com) ### Search or Filter * Use the search bar for keywords * Filter by type (agents, commands, etc.) * Filter by category (development, security, etc.) ### Click a Component View: * Full description * Installation command * Source code preview * Download statistics * GitHub link ### Copy Installation Command Click "Copy" next to the installation command and run in your terminal. ## Troubleshooting ### Component Not Found If you get a 404 error: ```bash theme={null} ❌ Agent "frontend-dev" not found ``` **Solutions**: 1. Check spelling - component names are exact 2. Search on [aitmpl.com](https://aitmpl.com) for the correct name 3. Verify the component exists in the catalog ### Permission Errors If installation fails with permission errors: ```bash theme={null} # Run with sudo (Linux/Mac) sudo npx claude-code-templates@latest --agent security-auditor # Or install to user directory npx claude-code-templates@latest --agent security-auditor --directory ~/projects/my-app ``` ### Merge Conflicts If settings/hooks conflict with existing config: ```bash theme={null} ⚠️ Conflicts detected: • Setting "telemetry" (current: false, new: true) Do you want to overwrite? (y/N) ``` Choose: * `y` - Replace existing value with new value * `N` - Keep existing value, skip installation ## File Locations Reference | Component Type | Installation Path | Format | | -------------- | ---------------------------- | --------- | | Agents | `.claude/agents/{name}.md` | Markdown | | Commands | `.claude/commands/{name}.md` | Markdown | | MCPs | `.mcp.json` (merged) | JSON | | Settings | `.claude/settings*.json` | JSON | | Hooks | `.claude/settings*.json` | JSON | | Skills | `.claude/skills/{name}/` | Directory | ## Next Steps Install multiple components at once Use the visual component selector Create reusable installation workflows Create agents you can run from anywhere # Interactive Mode Source: https://davila7-claude-code-templates-86.mintlify.app/guides/interactive-mode Use the interactive CLI menu to browse, select, and install components with a visual interface # Interactive Mode Interactive mode provides a terminal-based visual interface for browsing and installing components. It's perfect when you don't know exactly which components you need or want to explore what's available. ## Launching Interactive Mode Run the CLI without any flags: ```bash theme={null} npx claude-code-templates@latest ``` You'll see the branded welcome screen: ``` ════════════════════════════════════════════════════════════════ 🔮 Claude Code Templates Your starting point for Claude Code projects ════════════════════════════════════════════════════════════════ 🚀 Setup Claude Code for any project language 🚀 v1.2.3 🌐 Templates: https://aitmpl.com 📖 Documentation: https://docs.aitmpl.com ``` ## Main Menu The main menu offers several options: ```bash theme={null} ? What would you like to do? 📊 Analytics Dashboard - Monitor your Claude Code usage and sessions 💬 Chats Mobile - AI-first mobile interface for conversations 🤖 Agents Dashboard - View and analyze Claude conversations with agent tools ❯ ⚙️ Project Setup - Configure Claude Code for your project 🔍 Health Check - Verify your Claude Code setup and configuration ``` * **Analytics Dashboard** - Opens a web dashboard showing your usage statistics, session history, and download metrics * **Chats Mobile** - Launches a mobile-optimized chat interface for Claude conversations * **Agents Dashboard** - Opens agent management interface with conversation analysis * **Project Setup** - Starts the component installation workflow (most common choice) * **Health Check** - Scans your project for configuration issues and recommends fixes ## Project Setup Flow Selecting "Project Setup" starts the component selection wizard. ### Project Detection ```bash theme={null} ⠋ Detecting project type... ✔ Project detection complete Target directory: /Users/you/projects/my-app ``` The CLI automatically detects: * Programming language (from `package.json`, `requirements.txt`, etc.) * Framework (React, Next.js, Django, etc.) * Existing Claude Code configuration ### Template Selection ```bash theme={null} ? Select a template for your project: ❯ common - Universal Claude Code setup for any language javascript-typescript - Node.js, TypeScript, React, Vue python - Python, Django, Flask, FastAPI ruby - Ruby, Rails java - Java, Spring, Maven, Gradle go - Go, Gin, Echo rust - Rust, Cargo ``` **Template Recommendation**: If your language is detected, it will be pre-selected. You can change it if needed. ### Agent Selection ```bash theme={null} ? Select agents to install (Space to select, Enter to continue): Development Team ◯ frontend-developer - React, Vue, Angular specialist ◉ backend-developer - Node.js, Python, API development ◯ full-stack-developer - End-to-end web development Security ◉ security-auditor - Security analysis and vulnerability detection ◯ penetration-tester - Security testing and exploitation Data/AI ◯ ml-engineer - Machine learning model development ◯ data-scientist - Data analysis and visualization ``` **Navigation**: * **Arrow keys** - Move selection up/down * **Space** - Toggle selection on/off * **Enter** - Confirm and continue * **Ctrl+C** - Cancel and exit ### Command Selection ```bash theme={null} ? Select commands to install: Development ◉ docker-setup - Docker and docker-compose configuration ◉ setup-testing - Jest, Pytest, or other test frameworks ◯ git-setup - Git configuration and hooks DevOps ◯ ci-pipeline - GitHub Actions, GitLab CI setup ◯ deploy-vercel - Vercel deployment configuration ``` Same navigation as agent selection. ### MCP Selection ```bash theme={null} ? Select MCP servers to install: ◉ filesystem - File system access for Claude ◉ web-fetch - HTTP requests and web scraping ◯ database - PostgreSQL/MySQL integration ◯ github-integration - GitHub API access ``` **MCP Dependencies**: Some MCPs require additional setup (API keys, etc.). Check the documentation after installation. ### Hooks Selection ```bash theme={null} ? Select automation hooks to install: Git Workflow ◉ git/pre-commit-lint - Run linting before git commit ◯ git/prevent-force-push - Block git push --force Automation ◉ automation/simple-notifications - Desktop notifications ◯ automation/build-on-change - Auto-build on file save ``` ### Settings Selection ```bash theme={null} ? Select settings to configure: ◉ enable-telemetry - Share usage data to improve Claude Code ◯ use-sonnet - Use Claude Sonnet model (faster) ◯ use-opus - Use Claude Opus model (more powerful) ◯ read-only-mode - Prevent file modifications ``` ### Installation Location For settings and hooks: ```bash theme={null} ? Where would you like to install settings and hooks? ◯ User settings (~/.claude/settings.json) - All projects ◯ Project settings (.claude/settings.json) - This project, shared with team ◉ Local settings (.claude/settings.local.json) - This project, personal only ``` ### Confirmation ```bash theme={null} 📋 Installation Summary: Agents (2): • backend-developer • security-auditor Commands (2): • docker-setup • setup-testing MCPs (2): • filesystem • web-fetch Hooks (2): • git/pre-commit-lint • automation/simple-notifications Settings (1): • enable-telemetry ? Proceed with installation? (Y/n) ``` ### Installation Progress ```bash theme={null} ⠋ Copying template files... ✔ Template files copied successfully 🤖 Installing Claude Code agents... ✅ Agent "backend-developer" installed successfully! ✅ Agent "security-auditor" installed successfully! ⚡ Installing commands... ✅ Command "docker-setup" installed successfully! ✅ Command "setup-testing" installed successfully! 🔌 Installing MCPs... ✅ MCP "filesystem" installed successfully! ✅ MCP "web-fetch" installed successfully! 🪝 Installing hooks... ✅ Hook "git/pre-commit-lint" installed successfully! ✅ Hook "automation/simple-notifications" installed successfully! ⚙️ Configuring settings... ✅ Setting "enable-telemetry" installed successfully! ✅ Claude Code configuration setup complete! ``` ### Post-Installation Summary ```bash theme={null} 📚 Next steps: 1. Review the generated CLAUDE.md file 2. Customize the configuration for your project 3. Start using Claude Code with: claude 🌐 View all available templates at: https://aitmpl.com/ 📖 Read the complete documentation at: https://docs.aitmpl.com/ 💡 Language-specific features for javascript-typescript have been configured 🎯 Framework-specific commands for react are available 🔧 4 automation hooks have been configured 🔧 2 MCP servers have been configured ``` ## Interactive Features ### Back Navigation You can go back to previous steps using **Ctrl+C** and restarting, or by using the back option in some prompts. ### Search and Filter When selecting components, you can filter by typing: ```bash theme={null} ? Select agents to install: Filter: security ▊ Security ◯ security-auditor ◯ penetration-tester ◯ security-researcher ``` Type to filter, press **Backspace** to clear filter. ### Select All / Deselect All Some prompts support bulk selection: * **Ctrl+A** - Select all visible items * **Ctrl+D** - Deselect all items ### Component Details Some interactive prompts show component descriptions when you hover over them. ## Health Check Mode Selecting "Health Check" from the main menu: ### Run Diagnostics ```bash theme={null} 🔍 Running Health Check... ✔ Claude CLI detected ✔ Project directory accessible ✔ .claude directory exists ⚠ No agents installed ⚠ No commands installed ✔ .mcp.json configured correctly ⚠ No hooks configured ``` ### Review Recommendations ```bash theme={null} 📋 Health Check Results: ✅ Passed: 3/6 checks ⚠️ Warnings: 3/6 checks ❌ Errors: 0/6 checks 💡 Recommendations: • Install at least one agent for task automation • Consider adding development commands • Configure automation hooks for better workflow ? Would you like to run Project Setup now? (Y/n) ``` ### Auto-Fix (Optional) If you select "Yes", it automatically launches Project Setup with recommended components pre-selected. ## Analytics Dashboard Selecting "Analytics Dashboard" opens a web interface: ```bash theme={null} 📊 Launching Claude Code Analytics Dashboard... 🌐 Dashboard available at: http://localhost:3001 ``` The dashboard shows: * Session history and duration * Component usage statistics * Download counts for your installed components * Trending components in the community * Agent conversation analytics **Tunnel Mode**: Add `--tunnel` flag to expose the dashboard publicly via Cloudflare: ```bash theme={null} npx claude-code-templates@latest --analytics --tunnel ``` ## Chats Mobile Interface Selecting "Chats Mobile" launches a mobile-optimized chat interface: ```bash theme={null} 💬 Launching Claude Code Mobile Chats... 🌐 Interface available at: http://localhost:3002 ``` Optimized for: * Touch interactions * Small screens * Conversation history * Quick component installation ## Non-Interactive Equivalent Every interactive selection can be replicated with CLI flags: ```bash Interactive theme={null} npx claude-code-templates@latest # ... make selections ... ``` ```bash Non-Interactive (Equivalent) theme={null} npx claude-code-templates@latest \ --template javascript-typescript \ --agent backend-developer \ --agent security-auditor \ --command docker-setup \ --command setup-testing \ --mcp filesystem \ --mcp web-fetch \ --hook git/pre-commit-lint \ --setting enable-telemetry \ --yes ``` The CLI prints the equivalent command after installation for future automation. ## Customizing Interactive Mode ### Pre-select Components You can start interactive mode with some components already specified: ```bash theme={null} npx claude-code-templates@latest \ --agent security-auditor \ --mcp filesystem # Interactive mode opens with these pre-selected ``` ### Skip Specific Prompts Use `--yes` to skip confirmation prompts: ```bash theme={null} npx claude-code-templates@latest --yes # Skips "Proceed with installation?" confirmation ``` ### Target Directory Specify directory before launching interactive mode: ```bash theme={null} npx claude-code-templates@latest --directory ./my-project # Interactive mode installs to ./my-project ``` ## Keyboard Shortcuts Reference | Shortcut | Action | | ----------------- | ------------------------------- | | **Arrow Up/Down** | Navigate options | | **Space** | Toggle selection (checkboxes) | | **Enter** | Confirm and continue | | **Ctrl+C** | Cancel and exit | | **Ctrl+A** | Select all (where supported) | | **Ctrl+D** | Deselect all (where supported) | | **Backspace** | Clear filter text | | **Tab** | Auto-complete (in some prompts) | ## Troubleshooting Interactive Mode ### Terminal Display Issues If the interface looks broken: ```bash theme={null} # Force UTF-8 encoding export LANG=en_US.UTF-8 export LC_ALL=en_US.UTF-8 npx claude-code-templates@latest ``` ### Arrow Keys Not Working Some terminals (especially in Docker) don't support interactive prompts: **Solution**: Use non-interactive mode with flags instead: ```bash theme={null} npx claude-code-templates@latest \ --agent security-auditor \ --command docker-setup \ --yes ``` ### Session Timeout If you wait too long on a prompt: ```bash theme={null} ⚠️ Session timeout. Exiting... ``` **Solution**: Restart and proceed quickly, or use `--yes` flag. ### Component List Not Loading If components don't appear: ```bash theme={null} ⚠️ Failed to load components. Please check your internet connection. ``` **Solution**: Check internet connection and retry. Components are fetched from GitHub. ## Best Practices ### First-Time Users 1. **Run Health Check First**: Understand your current setup 2. **Start with Recommended**: Let the CLI suggest components based on your project 3. **Install Incrementally**: Don't install everything at once—add components as you need them ### Team Onboarding 1. **Generate Command**: One person runs interactive mode 2. **Copy Non-Interactive Command**: Share the equivalent CLI command with team 3. **Document in README**: Add the command to project documentation ```markdown theme={null} ## Setup Claude Code Run this command to install required components: \`\`\`bash npx claude-code-templates@latest \ --agent backend-developer \ --command docker-setup \ --yes \`\`\` ``` ### Exploring Components Use interactive mode to discover components, then: 1. Note which components you selected 2. Visit [aitmpl.com](https://aitmpl.com) to read full documentation 3. Create a saved workflow for future projects ## Next Steps Install multiple components at once Save your selection as a reusable workflow Create agents accessible from anywhere Browse all available components # Workflows Source: https://davila7-claude-code-templates-86.mintlify.app/guides/workflows Create, share, and execute reusable component installation workflows using hashes and YAML configurations # Workflows Workflows allow you to save and share component installation configurations. Instead of typing long commands with many flags, you can create a workflow once and share it as a short hash or YAML file. ## What are Workflows? A workflow is a saved configuration that includes: * **Components** - Agents, commands, MCPs, settings, hooks * **Properties** - Name, description, tags * **Metadata** - Author, version, installation instructions Workflows can be: * Shared via short hash URLs (`#abc123def456`) * Saved as YAML files for version control * Generated from the workflow builder UI * Created manually in any text editor ## Why Use Workflows? Share entire component setups with a single hash Ensure consistent installations across environments Version control your Claude Code configurations Browse community workflows for common setups ## Workflow Hash Installation Workflow hashes are short identifiers (12 characters) that reference saved workflows. ### Create a Workflow Visit [aitmpl.com/workflows](https://aitmpl.com/workflows) and use the visual workflow builder: 1. Drag components from the sidebar 2. Arrange them in desired order 3. Click "Generate Workflow" 4. Fill in workflow properties (name, description) 5. Get your workflow hash ### Use the Workflow Hash ```bash theme={null} npx claude-code-templates@latest --workflow:#abc123def456 ``` The CLI: 1. Fetches the workflow from localStorage (browser-cached workflows) 2. Parses the component list 3. Installs all components in order 4. Shows installation summary ### Share the Hash Share the workflow URL with teammates: ``` https://aitmpl.com/workflows#abc123def456 ``` They can view the workflow details and install it. **Hash Storage**: Workflow hashes are stored in your browser's localStorage when created on aitmpl.com. The CLI can only install workflows you've created on your machine or workflows shared via YAML. ## YAML Workflow Format YAML workflows are more flexible and can be version-controlled. ### Basic YAML Structure ```yaml workflow.yaml theme={null} name: "Full-Stack Development Setup" description: "Complete setup for full-stack web development" tags: - development - full-stack - web steps: - step: 1 type: agent name: "frontend-developer" - step: 2 type: agent name: "backend-developer" - step: 3 type: command name: "docker-setup" - step: 4 type: command name: "setup-testing" - step: 5 type: mcp name: "filesystem" - step: 6 type: mcp name: "web-fetch" - step: 7 type: setting name: "enable-telemetry" - step: 8 type: hook name: "git/pre-commit-lint" ``` ### YAML Field Reference | Field | Required | Description | | -------------- | -------- | --------------------------------------------------------------------- | | `name` | Yes | Workflow display name | | `description` | No | Detailed workflow description | | `tags` | No | Array of searchable tags | | `steps` | Yes | Array of installation steps | | `steps[].step` | Yes | Step number (for ordering) | | `steps[].type` | Yes | Component type: `agent`, `command`, `mcp`, `setting`, `hook`, `skill` | | `steps[].name` | Yes | Component name (kebab-case) | ## Installing from YAML ### Method 1: File Path Save your workflow as a YAML file and reference it: ```bash theme={null} npx claude-code-templates@latest --workflow workflow.yaml ``` **Current Directory**: The CLI looks for the YAML file relative to your current directory. Use absolute paths if needed: ```bash theme={null} npx claude-code-templates@latest --workflow /path/to/workflow.yaml ``` ### Method 2: Base64 Encoded For remote installations or CI/CD: ```bash theme={null} # Encode workflow YAML_CONTENT=$(cat workflow.yaml | base64) # Install from base64 npx claude-code-templates@latest --workflow "$YAML_CONTENT" ``` ### Method 3: Inline YAML For short workflows: ```bash theme={null} npx claude-code-templates@latest --workflow 'name: Quick Setup steps: - step: 1 type: agent name: security-auditor - step: 2 type: command name: security-scan' ``` ## Workflow Examples ### Security-Focused Workflow ```yaml security-workflow.yaml theme={null} name: "Security-First Development" description: "Comprehensive security setup for sensitive projects" tags: - security - compliance - audit steps: - step: 1 type: agent name: "security-auditor" - step: 2 type: agent name: "penetration-tester" - step: 3 type: command name: "security-scan" - step: 4 type: command name: "vulnerability-check" - step: 5 type: setting name: "read-only-mode" - step: 6 type: hook name: "security/secrets-detection" - step: 7 type: hook name: "git/prevent-force-push" ``` ```bash Installation theme={null} npx claude-code-templates@latest --workflow security-workflow.yaml --yes ``` ### Data Science Workflow ```yaml data-science-workflow.yaml theme={null} name: "Data Science Toolkit" description: "ML, data analysis, and visualization setup" tags: - data-science - machine-learning - python steps: - step: 1 type: agent name: "data-scientist" - step: 2 type: agent name: "ml-engineer" - step: 3 type: agent name: "data-analyst" - step: 4 type: command name: "notebook-setup" - step: 5 type: mcp name: "database" - step: 6 type: setting name: "retention-90-days" ``` ### DevOps Workflow ```yaml devops-workflow.yaml theme={null} name: "DevOps Automation Suite" description: "CI/CD, infrastructure, and monitoring setup" tags: - devops - automation - infrastructure steps: - step: 1 type: agent name: "devops-engineer" - step: 2 type: agent name: "cloud-architect" - step: 3 type: command name: "docker-setup" - step: 4 type: command name: "ci-pipeline" - step: 5 type: command name: "deploy-vercel" - step: 6 type: mcp name: "github-integration" - step: 7 type: hook name: "automation/build-on-change" ``` ## Creating Workflows ### Visual Workflow Builder The easiest way to create workflows: ### Open the Builder Visit [aitmpl.com/workflows](https://aitmpl.com/workflows) ### Browse Components The left sidebar shows: * **Agents** (grouped by category) * **Commands** (grouped by category) * **MCPs** (alphabetical) Use the search bar to filter components. ### Add Components Two methods: 1. **Drag and Drop**: Drag components from sidebar to canvas 2. **Click to Add**: Click the ➕ button next to component name Components appear in the center canvas as workflow steps. ### Reorder Steps Drag steps to reorder them. The step numbers update automatically. ### Set Properties Click "Generate Workflow" and fill in: * **Name** - Workflow display name * **Description** - What the workflow does * **Tags** - Comma-separated tags for discovery ### Generate Hash and YAML The builder shows: ```bash theme={null} # Workflow Hash (for quick sharing) npx claude-code-templates@latest --workflow:#abc123def456 # YAML (for version control) name: "My Workflow" steps: - step: 1 type: agent name: "security-auditor" ... ``` Copy either format. ### Manual YAML Creation Create workflows directly in your editor: ```bash theme={null} # Create workflow file touch .claude/workflows/my-workflow.yaml # Edit with your favorite editor code .claude/workflows/my-workflow.yaml ``` Add your workflow structure following the YAML format above. ## Workflow Best Practices ### 1. Name Workflows Descriptively ✅ Good: ```yaml theme={null} name: "React Frontend with TypeScript and Testing" ``` ❌ Bad: ```yaml theme={null} name: "My Setup" ``` ### 2. Add Comprehensive Descriptions ```yaml theme={null} name: "E-commerce Backend API" description: | Complete backend setup for e-commerce API including: - Database integration (PostgreSQL) - Authentication and security - Payment processing setup - API documentation generation - Automated testing suite ``` ### 3. Use Meaningful Tags ```yaml theme={null} tags: - ecommerce - backend - api - postgresql - stripe - authentication ``` Tags help others discover your workflow. ### 4. Order Components Logically ```yaml theme={null} steps: # 1. Install agents first - step: 1 type: agent name: "backend-developer" # 2. Then commands - step: 2 type: command name: "docker-setup" # 3. Then MCPs - step: 3 type: mcp name: "database" # 4. Finally settings and hooks - step: 4 type: setting name: "enable-telemetry" ``` ### 5. Version Control Workflows Store workflows in your repo: ```bash theme={null} .claude/ ├── workflows/ │ ├── development.yaml │ ├── production.yaml │ └── testing.yaml └── README.md ``` Document in README: ```markdown theme={null} ## Development Setup \`\`\`bash npx claude-code-templates@latest --workflow .claude/workflows/development.yaml \`\`\` ``` ## Combining Workflows with Other Flags Workflows can be combined with additional flags: ### Add Extra Components ```bash theme={null} npx claude-code-templates@latest \ --workflow development.yaml \ --agent extra-agent \ --command extra-command ``` The workflow installs first, then additional components. ### Set Installation Directory ```bash theme={null} npx claude-code-templates@latest \ --workflow development.yaml \ --directory ./my-project ``` ### Auto-Confirm ```bash theme={null} npx claude-code-templates@latest \ --workflow development.yaml \ --yes ``` Skips all confirmation prompts. ## Sharing Workflows ### Share Hash URLs After creating a workflow on aitmpl.com: ``` https://aitmpl.com/workflows#abc123def456 ``` Share this URL. Others can: 1. View workflow details 2. Copy the installation command 3. Install with one command ### Share YAML Files #### Via GitHub Gist ```bash theme={null} # Create a gist gh gist create workflow.yaml --public # Share the gist URL # Others can: curl https://gist.githubusercontent.com/.../workflow.yaml | \ npx claude-code-templates@latest --workflow - ``` #### Via Git Repository ```bash theme={null} # In your repo git add .claude/workflows/setup.yaml git commit -m "Add Claude Code workflow" git push # Others can: git clone npx claude-code-templates@latest --workflow .claude/workflows/setup.yaml ``` #### Via Package Registry Publish workflows as npm packages: ```json package.json theme={null} { "name": "@yourorg/claude-workflows", "version": "1.0.0", "files": ["workflows/"] } ``` ```bash theme={null} npm publish # Others can: npx @yourorg/claude-workflows/workflows/setup.yaml ``` ## Workflow Collections Create multiple related workflows: ``` .claude/workflows/ ├── base.yaml # Core components for all projects ├── frontend.yaml # Frontend-specific additions ├── backend.yaml # Backend-specific additions └── full-stack.yaml # Combined frontend + backend ``` Install progressively: ```bash theme={null} # Start with base npx claude-code-templates@latest --workflow .claude/workflows/base.yaml --yes # Add frontend npx claude-code-templates@latest --workflow .claude/workflows/frontend.yaml --yes ``` ## Troubleshooting Workflows ### Workflow Hash Not Found ```bash theme={null} ❌ Workflow hash "abc123def456" not found in localStorage ``` **Solution**: Workflow hashes are browser-specific. Use YAML format for sharing: ```bash theme={null} # Convert to YAML # 1. Open aitmpl.com/workflows#abc123def456 # 2. Copy the YAML output # 3. Save to file and share ``` ### Invalid YAML Syntax ```bash theme={null} ❌ Error parsing workflow YAML: Unexpected token ``` **Solution**: Validate YAML syntax: ```bash theme={null} # Use a YAML validator npx js-yaml workflow.yaml # Or online: https://www.yamllint.com/ ``` Common issues: * Incorrect indentation (use 2 spaces) * Missing quotes around names with special characters * Trailing whitespace ### Component Not Found ```bash theme={null} ✅ Agent "security-auditor" installed ❌ Command "non-existent-cmd" not found ✅ MCP "filesystem" installed ``` **Solution**: Check component names: 1. Visit [aitmpl.com](https://aitmpl.com) 2. Search for the component 3. Use exact name from search results 4. Update workflow YAML ### Step Order Matters Some components depend on others: ```yaml theme={null} # ❌ Bad: Settings before agents steps: - step: 1 type: setting name: "enable-telemetry" - step: 2 type: agent name: "security-auditor" # ✅ Good: Logical order steps: - step: 1 type: agent name: "security-auditor" - step: 2 type: setting name: "enable-telemetry" ``` ## Next Steps Create globally accessible agents Install multiple components at once Visual workflow creation tool Browse all available components # Installation Guide Source: https://davila7-claude-code-templates-86.mintlify.app/installation Comprehensive guide to installing and configuring Claude Code Templates components # Installation Guide This guide covers everything you need to know about installing Claude Code Templates, from basic usage to advanced configuration and batch installation. ## Prerequisites * **Node.js 14+**: Required to run the CLI tool * **Claude Code**: Anthropic's Claude Code IDE ([download](https://code.claude.com)) * **Git** (optional): For version control integration Claude Code Templates works with any project type. The CLI automatically detects your project structure and recommends appropriate components. ## Basic Installation ### Install via npx (Recommended) No installation required - run directly with npx: ```bash theme={null} npx claude-code-templates@latest ``` The `@latest` tag ensures you always get the newest components: ```bash Package Information theme={null} Package: claude-code-templates Version: 1.28.16 NPM: https://www.npmjs.com/package/claude-code-templates Short alias: cct ``` ### Install Globally For frequent use, install globally: ```bash theme={null} npm install -g claude-code-templates # Then run anywhere: claude-code-templates # or cct ``` Global installation may use an older version unless you update regularly: ```bash theme={null} npm update -g claude-code-templates ``` ## Component Types Claude Code Templates provides six types of components: ### 🤖 Agents (400+) **What they are**: AI specialists with domain-specific knowledge and context. **Location**: `.claude/agents/` **Installation**: ```bash theme={null} npx claude-code-templates@latest --agent development-team/frontend-developer ``` **Usage**: Reference in Claude Code with `@agent-name` **Examples**: * `development-team/frontend-developer` - Expert in React, Vue, Angular * `security/security-auditor` - Security analysis and vulnerability detection * `devops-infrastructure/kubernetes-expert` - Container orchestration specialist * `data-ai/machine-learning-engineer` - ML model development and training **Categories**: * Development Team (Frontend, Backend, Fullstack) * Development Tools (Code Review, Refactoring) * Security (Auditing, Penetration Testing) * DevOps & Infrastructure (Docker, Kubernetes, AWS) * Data & AI (ML, Data Science, Analytics) * Documentation (Technical Writing, API Docs) * Testing & QA (Unit Testing, E2E Testing) * Database (PostgreSQL, MongoDB, Redis) * API & GraphQL (REST, GraphQL, API Design) * And 20+ more categories... ### ⚡ Commands (225+) **What they are**: Custom slash commands for automated workflows. **Location**: `.claude/commands/` **Installation**: ```bash theme={null} npx claude-code-templates@latest --command testing/generate-tests ``` **Usage**: Type `/command-name` in Claude Code **Examples**: * `/generate-tests` - Generate unit tests for selected code * `/optimize-bundle` - Analyze and optimize bundle size * `/check-security` - Run security audit on dependencies * `/setup-ci` - Configure CI/CD pipeline * `/refactor-code` - Suggest refactoring improvements **Categories**: * Testing (Unit Tests, E2E Tests, Coverage) * Performance (Bundle Optimization, Profiling) * Security (Vulnerability Scanning, SAST) * Documentation (README, API Docs, Changelog) * Code Quality (Linting, Formatting, Review) * Deployment (CI/CD, Docker, Cloud) ### 🔌 MCPs (65+) **What they are**: Model Context Protocol integrations for external services. **Location**: `.claude/mcps/` **Installation**: ```bash theme={null} npx claude-code-templates@latest --mcp development/github-integration ``` **Usage**: Claude Code connects automatically on startup **Examples**: * `development/github-integration` - GitHub API access * `database/postgresql-integration` - PostgreSQL queries * `cloud/aws-integration` - AWS service management * `payment/stripe-integration` - Stripe API integration * `ai/openai-integration` - OpenAI API access **Categories**: * Development (GitHub, GitLab, Bitbucket) * Database (PostgreSQL, MySQL, MongoDB, Redis) * Cloud (AWS, Azure, GCP, Vercel) * Payment (Stripe, PayPal) * AI & ML (OpenAI, Anthropic, Hugging Face) * Communication (Slack, Discord, Telegram) MCPs often require API credentials. Check component documentation for required environment variables. ### ⚙️ Settings (60+) **What they are**: Claude Code configuration presets. **Location**: `.claude/settings/` **Installation**: ```bash theme={null} npx claude-code-templates@latest --setting performance/mcp-timeouts ``` **Examples**: * `performance/mcp-timeouts` - Optimize MCP connection timeouts * `memory/large-projects` - Memory settings for large codebases * `output/verbose-logging` - Enable detailed logging * `read-only-mode` - Prevent file modifications ### 🪝 Hooks (45+) **What they are**: Automation triggers for development workflows. **Location**: `.claude/hooks/` **Installation**: ```bash theme={null} npx claude-code-templates@latest --hook git/pre-commit-validation ``` **Examples**: * `git/pre-commit-validation` - Validate code before commits * `automation/simple-notifications` - Send notifications on events * `deployment/post-deploy-check` - Verify deployments ### 🎨 Skills (300+) **What they are**: Reusable capabilities with progressive disclosure. **Location**: `.claude/skills/` **Installation**: ```bash theme={null} npx claude-code-templates@latest --skill pdf-processing ``` **Examples**: * `pdf-processing` - Generate and manipulate PDFs * `excel-automation` - Automate Excel operations * `scientific-computing` - Scientific computation tools ## Installation Methods ### Interactive Mode Launch the interactive CLI to browse and select components: ```bash theme={null} npx claude-code-templates@latest ``` **Workflow**: 1. Main menu appears 2. Select "Project Setup" 3. Choose component type (Agent, Command, MCP, etc.) 4. Browse categories 5. Select specific components 6. Confirm installation Interactive mode is great for discovering new components and learning what's available. ### Direct Installation Install specific components directly: ```bash Single Component theme={null} # Install one agent npx claude-code-templates@latest --agent development-team/frontend-developer # Install one command npx claude-code-templates@latest --command testing/generate-tests # Install one MCP npx claude-code-templates@latest --mcp development/github-integration ``` ### Batch Installation Install multiple components in one command: ```bash Multiple Components theme={null} npx claude-code-templates@latest \ --agent development-team/frontend-developer \ --agent development-team/react-expert \ --command testing/generate-tests \ --command performance/optimize-bundle \ --mcp development/github-integration \ --hook git/pre-commit-validation \ --setting performance/mcp-timeouts \ --yes ``` You can install multiple of the same type by repeating the flag: ```bash theme={null} --agent security-auditor --agent code-reviewer --agent react-expert ``` ### Skip Prompts Use `--yes` to skip all confirmation prompts: ```bash theme={null} npx claude-code-templates@latest \ --agent development-team/frontend-developer \ --yes ``` Perfect for: * Automated scripts * CI/CD pipelines * Team onboarding scripts * Docker containers ## Advanced Installation ### Install to Specific Directory By default, components install to the current directory's `.claude/` folder. Change the target: ```bash theme={null} npx claude-code-templates@latest \ --directory /path/to/project \ --agent frontend-developer ``` ### Dry Run See what would be installed without actually installing: ```bash theme={null} npx claude-code-templates@latest \ --agent frontend-developer \ --dry-run ``` Output shows: * Files that would be created * Directories that would be modified * Configuration changes ### Comma-Separated Values Install multiple components of the same type with commas: ```bash theme={null} npx claude-code-templates@latest \ --agent "development-team/frontend-developer,security/security-auditor,devops-infrastructure/kubernetes-expert" \ --yes ``` ### Workflow Installation Install complete workflows from templates: ```bash theme={null} npx claude-code-templates@latest --workflow "#react-testing-workflow" ``` Workflows are pre-configured sets of components that work together. ## Project Templates For new projects, use complete project templates: ```bash JavaScript/TypeScript theme={null} npx claude-code-templates@latest --template javascript-typescript --yes ``` ```bash Python theme={null} npx claude-code-templates@latest --template python --yes ``` ```bash Ruby theme={null} npx claude-code-templates@latest --template ruby --yes ``` ```bash Common (Language Agnostic) theme={null} npx claude-code-templates@latest --template common --yes ``` Templates include: * Language-specific agents * Common commands * Recommended MCPs * Standard hooks * Configuration presets ## Configuration ### Component Configuration After installation, components are configured in `.claude/`: ```bash Directory Structure theme={null} .claude/ ├── agents/ │ ├── frontend-developer.md │ └── react-expert.md ├── commands/ │ ├── generate-tests.json │ └── optimize-bundle.json ├── hooks/ │ └── pre-commit-validation.json ├── mcps/ │ └── github-integration.json ├── settings/ │ └── mcp-timeouts.json └── config.json ``` ### Environment Variables Some components require environment variables: ```bash .env theme={null} # GitHub MCP GITHUB_TOKEN=ghp_your_token_here # PostgreSQL MCP DATABASE_URL=postgresql://user:pass@localhost:5432/db # AWS MCP AWS_ACCESS_KEY_ID=AKIA... AWS_SECRET_ACCESS_KEY=... AWS_REGION=us-east-1 # OpenAI MCP OPENAI_API_KEY=sk-... ``` Never commit `.env` files to version control. Add to `.gitignore`: ```bash theme={null} echo ".env" >> .gitignore ``` ### Python Command Configuration On Windows, the CLI automatically detects and uses the correct Python command: * Windows: `python` or `py` * Unix/Linux/Mac: `python3` Statusline settings with Python scripts work automatically across platforms. ## CLI Reference Complete CLI options: ```bash Command Line Options theme={null} claude-code-templates [options] Options: -V, --version Output version number -h, --help Display help -t, --template