{"aiPlatform":"claude-code@2025.06","category":"development","commandName":"/subagent-builder","content":"---\nname: Subagent Builder\ndescription: Build perfect Claude Code subagents using the latest documentation and best practices. This command fetches current guidelines, analyzes your needs, and creates specialized agents that follow all recommended patterns for maximum effectiveness.\nallowed_tools:\n  - WebFetch      # Fetch latest documentation\n  - Read          # Analyze existing agents\n  - Write         # Create agent files\n  - MultiEdit     # Update configurations\n  - Bash          # Run setup commands\n  - LS            # Check project structure\n  - TodoWrite     # Track creation steps\n  - Grep          # Find existing patterns\ntags:\n  - subagent\n  - builder\n  - automation\n  - builder\n  - claude-code\ncategory: development\n---\n\n## Key Features\n\nThis subagent builder creates perfect Claude Code subagents by:\n\n1. **Fetching Latest Docs** - Reads current best practices from docs.anthropic.com\n2. **Interactive Design** - Guides you through agent purpose and capabilities\n3. **Pattern Library** - Applies proven patterns from successful agents\n4. **Tool Optimization** - Selects minimal required tools for security\n5. **Test Generation** - Creates validation scenarios for your agent\n\n## Arguments\n\n```\n/subagent-builder\n[name=<string>]               # Agent name (e.g., \"code-reviewer\")\n[purpose=<string>]            # What the agent does\n[type=<general|specialized>]  # Agent complexity level\n[proactive=<true|false>]      # Should detect tasks automatically\n[tools=<all|minimal|custom>]  # Tool permission strategy\n[category=<string>]           # Agent category (testing, content, etc)\n[examples=<number>]           # Number of example prompts to generate\n```\n\n## What This Command Does\n\n### 1. Documentation Analysis\n- Fetches latest subagent guidelines from Claude Code docs\n- Checks specific URLs: `/sub-agents`, `/hooks`, `/settings` pages\n- Analyzes successful agent patterns in `.claude/agents/` directory\n- Identifies best practices for your use case\n\n### 2. Interactive Agent Design\n```\n🤖 Subagent Builder Assistant\n\nLet's create your perfect subagent!\n\n1. What should your agent do? (primary purpose)\n   > Review code for security vulnerabilities\n\n2. When should it activate? (triggers)\n   > When code is modified or security is mentioned\n\n3. What tools does it need? (permissions)\n   > Read, Grep, TodoWrite\n\n4. Should it be proactive? (auto-detect tasks)\n   > Yes, check code automatically\n\nBuilding your subagent...\n```\n\n### 3. Generated Agent Structure\n```markdown\n---\nname: security-reviewer\ndescription: Reviews code for security vulnerabilities and suggests fixes. Use PROACTIVELY when code is modified or security is mentioned.\ntools:\n  - Read\n  - Grep\n  - TodoWrite\n---\n\nYou are a security-focused code reviewer specializing in identifying vulnerabilities and suggesting secure coding practices. Your mission is to protect codebases from security threats.\n\n## Core Responsibilities\n\n1. **Vulnerability Detection**\n   - SQL injection risks\n   - XSS vulnerabilities\n   - Authentication flaws\n   - Data exposure risks\n   - Dependency vulnerabilities\n\n2. **Secure Coding Guidance**\n   - Suggest security best practices\n   - Provide secure code alternatives\n   - Explain vulnerability impacts\n   - Reference security standards\n\n## Workflow\n\nWhen reviewing code:\n1. Scan for common vulnerability patterns\n2. Check authentication and authorization\n3. Review data handling and validation\n4. Examine external dependencies\n5. Generate security report with fixes\n\n## Proactive Triggers\n\nAutomatically engage when:\n- New code files are created\n- Authentication code is modified\n- Database queries are added\n- API endpoints are created\n- Dependencies are updated\n\n[Additional specialized instructions...]\n```\n\n### 4. Test Suite Generation\nCreates validation scenarios:\n```markdown\n## Test Scenarios for security-reviewer\n\n1. **SQL Injection Detection**\n   - Present code with string concatenation in queries\n   - Agent should identify risk and suggest parameterized queries\n\n2. **Authentication Review**\n   - Show login implementation\n   - Agent should check for proper password hashing\n\n3. **XSS Prevention**\n   - Display user input rendering\n   - Agent should recommend sanitization\n\n[Additional test cases...]\n```\n\n### 5. Integration Setup\n- Updates CLAUDE.md with agent usage instructions\n- Creates example prompts for team members\n- Sets up version control structure\n- Configures proactive detection patterns\n- **Hook Configuration**: For proactive agents, provides instructions on adding to user prompt hooks\n\n## Subagent Types and Patterns\n\n### General-Purpose Subagents\n- Broad capabilities with flexible tool access\n- Good for exploratory or research tasks\n- Example: \"research-assistant\", \"documentation-writer\"\n\n### Specialized Subagents\n- Focused on specific domains\n- Minimal tool permissions\n- Example: \"security-reviewer\", \"performance-optimizer\"\n\n### Proactive Subagents\n- Auto-detect when to engage\n- Monitor for specific triggers\n- Example: \"code-reviewer\", \"test-writer\"\n\n## Best Practices Applied\n\n1. **Single Responsibility** - Each agent has one clear purpose\n2. **Minimal Permissions** - Only necessary tools granted\n3. **Clear Descriptions** - Specific about when to invoke\n4. **Detailed Prompts** - Comprehensive system instructions\n5. **Version Control** - Ready for team collaboration\n\n## Example Usage\n\n### Creating a Test Writer Agent\n```\n/subagent-builder name=test-writer purpose=\"Write comprehensive test suites\" proactive=true\n\nGenerated agent will:\n- Detect when new functions are added\n- Automatically suggest test cases\n- Generate test code in your framework\n- Track test coverage improvements\n```\n\n### Creating a Documentation Agent\n```\n/subagent-builder name=doc-writer purpose=\"Keep documentation up-to-date\" category=content\n\nGenerated agent will:\n- Monitor code changes\n- Update relevant documentation\n- Generate API documentation\n- Maintain README files\n```\n\n### Creating a Performance Agent\n```\n/subagent-builder name=perf-monitor purpose=\"Optimize slow code\" tools=minimal\n\nGenerated agent will:\n- Profile performance bottlenecks\n- Suggest optimizations\n- Benchmark improvements\n- Track performance metrics\n```\n\n## Implementation\n\n### Step 1: Fetch Latest Documentation\n\n```javascript\nconst fetchLatestDocs = async () => {\n  console.log('📚 Fetching latest Claude Code subagent documentation...');\n  \n  // Check if agent docs exist locally first for faster access\n  const localAgentDocs = await glob('.claude/agents/*.md');\n  console.log(`Found ${localAgentDocs.length} existing agents for pattern analysis`);\n  \n  const docsUrls = [\n    'https://docs.anthropic.com/en/docs/claude-code/sub-agents',\n    'https://docs.anthropic.com/en/docs/claude-code/hooks',  // Hook configuration\n    'https://docs.anthropic.com/en/docs/claude-code/settings',  // Settings structure\n    'https://docs.anthropic.com/en/docs/claude-code/best-practices',\n    'https://docs.anthropic.com/en/docs/claude-code/common-workflows'\n  ];\n  \n  const docs = {};\n  for (const url of docsUrls) {\n    const content = await webFetch(url, \n      'Extract all guidelines about subagents, hooks, settings, and best practices for creating effective agents'\n    );\n    docs[url] = content;\n  }\n  \n  return docs;\n};\n```\n\n### Step 2: Interactive Agent Design\n\n```javascript\nconst designAgent = async (args) => {\n  const config = {\n    name: args.name || await promptUser('Agent name (e.g., code-reviewer):'),\n    purpose: args.purpose || await promptUser('What should this agent do?'),\n    type: args.type || 'specialized',\n    proactive: args.proactive !== 'false',\n    tools: args.tools || 'minimal',\n    category: args.category || 'general'\n  };\n  \n  // Analyze purpose to suggest configuration\n  if (config.purpose.match(/review|check|audit|analyze/i)) {\n    config.proactive = true;\n    config.tools = ['Read', 'Grep', 'TodoWrite'];\n  } else if (config.purpose.match(/write|create|generate/i)) {\n    config.tools = ['Read', 'Write', 'MultiEdit', 'TodoWrite'];\n  } else if (config.purpose.match(/fix|debug|resolve/i)) {\n    config.tools = ['Read', 'MultiEdit', 'Bash', 'TodoWrite'];\n  }\n  \n  return config;\n};\n```\n\n### Step 3: Pattern Library Application\n\n```javascript\nconst applyPatterns = (config, existingAgents) => {\n  const patterns = {\n    proactive: {\n      description: `${config.description} Use PROACTIVELY when ${config.triggers.join(' or ')}.`,\n      systemPrompt: 'include detailed trigger conditions'\n    },\n    specialized: {\n      tools: 'minimal set based on purpose',\n      systemPrompt: 'focused expertise in specific domain'\n    },\n    reviewer: {\n      workflow: 'systematic review process with checklist',\n      output: 'structured reports with actionable items'\n    },\n    generator: {\n      workflow: 'research → plan → create → validate',\n      output: 'high-quality content with metadata'\n    }\n  };\n  \n  // Apply relevant patterns\n  const appliedPatterns = [];\n  if (config.proactive) appliedPatterns.push(patterns.proactive);\n  if (config.type === 'specialized') appliedPatterns.push(patterns.specialized);\n  if (config.purpose.includes('review')) appliedPatterns.push(patterns.reviewer);\n  if (config.purpose.includes('generate')) appliedPatterns.push(patterns.generator);\n  \n  return appliedPatterns;\n};\n```\n\n### Step 4: Agent Generation\n\n```javascript\nconst generateAgent = async (config, patterns, docs) => {\n  const agentContent = `---\nname: ${config.name}\ndescription: ${config.description}\ntools:${config.tools.map(t => `\\n  - ${t}`).join('')}\n---\n\n${generateSystemPrompt(config, patterns, docs)}\n\n## Core Capabilities\n\n${generateCapabilities(config)}\n\n## Workflow\n\n${generateWorkflow(config, patterns)}\n\n${config.proactive ? generateProactiveTriggers(config) : ''}\n\n## Best Practices\n\n${extractBestPractices(docs)}\n\n## Output Format\n\n${generateOutputFormat(config)}\n\n## Quality Standards\n\n${generateQualityStandards(config)}\n`;\n\n  return agentContent;\n};\n```\n\n### Step 5: Test Suite Creation\n\n```javascript\nconst generateTests = async (config) => {\n  const tests = [];\n  \n  // Generate tests based on agent purpose\n  if (config.purpose.includes('review')) {\n    tests.push({\n      scenario: 'Code with security vulnerability',\n      expected: 'Agent identifies issue and suggests fix'\n    });\n  }\n  \n  if (config.purpose.includes('generate')) {\n    tests.push({\n      scenario: 'Request for new content',\n      expected: 'Agent creates high-quality output'\n    });\n  }\n  \n  if (config.purpose.includes('optimize')) {\n    tests.push({\n      scenario: 'Slow performing code',\n      expected: 'Agent profiles and improves performance'\n    });\n  }\n  \n  return tests;\n};\n```\n\n### Step 6: Main Execution\n\n```javascript\nconst main = async () => {\n  console.log('🤖 Subagent Builder - Creating Your Perfect Claude Code Subagent\\n');\n  \n  // Track progress\n  await todoWrite([\n    { id: '1', content: 'Fetch latest documentation', status: 'pending', priority: 'high' },\n    { id: '2', content: 'Design agent configuration', status: 'pending', priority: 'high' },\n    { id: '3', content: 'Apply best practice patterns', status: 'pending', priority: 'high' },\n    { id: '4', content: 'Generate agent file', status: 'pending', priority: 'high' },\n    { id: '5', content: 'Create test suite', status: 'pending', priority: 'high' },\n    { id: '6', content: 'Update project documentation', status: 'pending', priority: 'high' }\n  ]);\n  \n  // Step 1: Fetch documentation\n  await updateTodo('1', 'in_progress');\n  const docs = await fetchLatestDocs();\n  await updateTodo('1', 'completed');\n  \n  // Step 2: Design agent\n  await updateTodo('2', 'in_progress');\n  const config = await designAgent(args);\n  await updateTodo('2', 'completed');\n  \n  // Step 3: Apply patterns\n  await updateTodo('3', 'in_progress');\n  const existingAgents = await analyzeExistingAgents();\n  const patterns = applyPatterns(config, existingAgents);\n  await updateTodo('3', 'completed');\n  \n  // Step 4: Generate agent\n  await updateTodo('4', 'in_progress');\n  const agentContent = await generateAgent(config, patterns, docs);\n  await bash('mkdir -p .claude/agents');\n  await write(`.claude/agents/${config.name}.md`, agentContent);\n  await updateTodo('4', 'completed');\n  \n  // Step 5: Create tests\n  await updateTodo('5', 'in_progress');\n  const tests = await generateTests(config);\n  await bash('mkdir -p .claude/agents/tests');\n  await write(`.claude/agents/tests/${config.name}-test.md`, formatTests(tests));\n  await updateTodo('5', 'completed');\n  \n  // Step 6: Update documentation\n  await updateTodo('6', 'in_progress');\n  await updateClaudeMd(config);\n  await generateExamples(config);\n  await updateTodo('6', 'completed');\n  \n  // Summary\n  console.log(`\\n✅ Agent \"${config.name}\" Successfully Created!\\n`);\n  console.log(`📁 Agent file: .claude/agents/${config.name}.md`);\n  console.log(`🧪 Test suite: .claude/agents/tests/${config.name}-test.md`);\n  console.log(`📚 Documentation updated in CLAUDE.md\\n`);\n  \n  console.log('Example usage:');\n  console.log(`  • \"${config.examplePrompts[0]}\"`);\n  console.log(`  • \"${config.examplePrompts[1]}\"`);\n  \n  if (config.proactive) {\n    console.log(`\\n🚀 This agent will proactively engage when it detects relevant tasks!`);\n    console.log(`\\n⚠️  To enable automatic activation, add to your hooks configuration:`);\n    console.log(`    ~/.claude/settings.json or .claude/settings.json:`);\n    console.log(`    {`);\n    console.log(`      \"hooks\": {`);\n    console.log(`        \"UserPromptSubmit\": [`);\n    console.log(`          {`);\n    console.log(``);\n    console.log(`            \"hooks\": [`);\n    console.log(`              {`);\n    console.log(`                \"type\": \"command\",`);\n    console.log(`                \"command\": \"task subagent_type=${config.name}\"`);\n    console.log(`              }`);\n    console.log(`            ]`);\n    console.log(`          }`);\n    console.log(`        ]`);\n    console.log(`      }`);\n    console.log(`    }`);\n  }\n};\n\n// Execute\nmain().catch(console.error);\n```\n\n## Advanced Features\n\n### Pattern Detection\nThe builder analyzes your existing agents to learn patterns:\n- Naming conventions\n- Tool usage patterns  \n- Common workflows\n- Output formats\n\n### Documentation Sync\nAutomatically fetches and applies the latest:\n- Subagent best practices\n- Tool configurations\n- Invocation patterns\n- Security guidelines\n\n### Validation Suite\nEach agent comes with:\n- Test scenarios\n- Expected behaviors\n- Edge case handling\n- Performance benchmarks\n\n## Quick Agent Documentation Access\n\n### Finding Existing Agents\n```bash\n# List all agents in your project\nls -la .claude/agents/\n\n# Search for specific agent patterns\ngrep -r \"proactive\" .claude/agents/\n\n# View agent documentation\ncat .claude/agents/agent-name.md\n```\n\n### Claude Code Documentation URLs\nQuick links to relevant documentation:\n- **Subagents**: https://docs.anthropic.com/en/docs/claude-code/sub-agents\n- **Hooks**: https://docs.anthropic.com/en/docs/claude-code/hooks\n- **Settings**: https://docs.anthropic.com/en/docs/claude-code/settings\n- **Best Practices**: https://docs.anthropic.com/en/docs/claude-code/best-practices\n\n### Using MCP Memory\nClaude can remember agent patterns:\n```\nmcp__memory__search_nodes query=\"subagent\"\nmcp__memory__search_nodes query=\"proactive agent\"\n```\n\n## Tips for Success\n\n1. **Start Specific** - Narrow purpose = better agent\n2. **Minimize Tools** - Only what's absolutely needed\n3. **Clear Triggers** - When should agent activate\n4. **Test Thoroughly** - Use generated test suite\n5. **Iterate Often** - Refine based on usage\n\n## Hook Configuration for Proactive Agents\n\nProactive agents need to be added to Claude Code's hook system to work automatically.\n\n### Option 1: Global Settings Hook\nAdd to your Claude Code settings (`~/.claude/settings.json`):\n```json\n{\n  \"hooks\": {\n    \"UserPromptSubmit\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"task subagent_type=your-agent-name\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**Note**: UserPromptSubmit hooks don't require a matcher - they run for all prompts.\n\n### Option 2: Project-Specific Hook\nAdd to project settings in `.claude/settings.json`:\n```json\n{\n  \"hooks\": {\n    \"UserPromptSubmit\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"task subagent_type=your-agent-name\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n### Multiple Proactive Agents\nRun multiple agents by adding multiple hooks:\n```json\n{\n  \"hooks\": {\n    \"UserPromptSubmit\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"task subagent_type=agent1\"\n          },\n          {\n            \"type\": \"command\", \n            \"command\": \"task subagent_type=agent2\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n### Advanced: Tool-Specific Hooks\nFor tool-based hooks, use matchers to specify which tools trigger the agent:\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"matcher\": {\n          \"tools\": [\"Write\", \"MultiEdit\"]\n        },\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"task subagent_type=code-reviewer\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**Note**: Tool-based hooks (PreToolUse, PostToolUse) require matchers. UserPromptSubmit hooks don't.\n\n### Available Hook Types\n- `UserPromptSubmit` - After user submits a prompt\n- `PreToolUse` - Before using a tool\n- `PostToolUse` - After using a tool\n- `SessionStart` - When session begins\n- `Stop` - When stopping execution\n- `SubagentStop` - When subagent completes\n- `PreCompact` - Before context compaction\n\n**Note**: Without hook configuration, proactive agents won't activate automatically. You'll need to manually invoke them with the Task tool.\n\nLearn more: https://docs.anthropic.com/en/docs/claude-code/hooks\n\n## Security Notes\n\n- Agents only access specified tools\n- No external services without permission\n- All agents are local to your project\n- Version control recommended","contentHash":"5f07a6dc152340dc3ccb3461c452babc3f3b8156b9b30d3580303c8a204908d2","copies":0,"createdAt":"2025-07-31T03:14:22.781Z","description":"Build perfect Claude Code subagents using the latest documentation and best practices","downloads":4,"github":{"repoUrl":"https://github.com/Commands-com/ai-commands","lastSyncDirection":"from-github","metadata":{"importedFrom":"github_repository","repoPrivate":true,"repoDefaultBranch":"main","connectedAt":"2025-07-31T03:14:22.781Z"},"importedAt":"2025-07-31T03:14:22.781Z","lastSyncAt":"2025-08-17T16:56:09.629Z","fileMapping":{"license":"LICENSE","readme":"subagent-builder/README.md","assets":[],"mainFile":"subagent-builder/command.md","yamlPath":"commands.yaml"},"selectedCommand":"subagent-builder","fileShas":{"mainFile":"c92afa5081b7f65eb9bd5f51f0149805cd0b3cec","yamlPath":"4507cfda9afa7474437ab79914331e61ec82f4f7","readme":"55e41d6f1c9fb423b51ffe0221cb28293e21906e"},"branch":"main","connectionType":"commands_yaml","connected":true,"lastSyncCommit":"3f1460bda072265aa9ad932490481f0843dc66f8","importSource":"repository_import","installationId":"69232615","syncStatus":"synced"},"githubRepoUrl":"https://github.com/Commands-com/ai-commands","id":"e332e989-f092-4ccf-9edb-f4d006195896","inputParameters":[{"name":"name","description":"Name for the subagent (e.g., \"code-reviewer\")","label":"Subagent Name","type":"text","required":false,"defaultValue":""},{"name":"purpose","description":"What should this subagent do?","label":"Subagent Purpose","type":"text","required":false,"defaultValue":""},{"defaultValue":"specialized","name":"type","options":["general","specialized"],"description":"General or specialized subagent","label":"Subagent Type","type":"select","required":false},{"defaultValue":"true","name":"proactive","options":["true","false"],"description":"Should subagent detect tasks automatically?","label":"Proactive Detection","type":"select","required":false},{"defaultValue":"minimal","name":"tools","options":["all","minimal","custom"],"description":"Tool access strategy","label":"Tool Permissions","type":"select","required":false},{"defaultValue":"general","name":"category","options":["general","testing","content","development","security"],"description":"Primary subagent category","label":"Subagent Category","type":"select","required":false},{"name":"examples","description":"Number of example prompts to generate","label":"Example Count","type":"text","required":false,"defaultValue":"3"}],"instructions":"# Subagent Builder\n\nBuild perfect Claude Code subagents with best practices and up-to-date documentation. This command reads the latest Claude Code documentation, analyzes your project needs, and creates specialized subagents that follow all recommended patterns.\n\n## Features\n\n- **Documentation-Driven**: Fetches latest subagent best practices from Claude Code docs\n- **Interactive Design**: Guides you through agent creation with smart defaults\n- **Pattern Library**: Includes proven patterns from performance, blog, and content agents\n- **Tool Optimization**: Automatically selects minimal required tools\n- **Testing Suite**: Generates test scenarios to validate your agent\n\n## Usage\n\nBasic:\n```bash\n/subagent-builder\n```\n\nWith options:\n```bash\n/subagent-builder name=code-reviewer purpose=\"Review code for security issues\"\n/subagent-builder type=specialized category=testing\n/subagent-builder proactive=true tools=minimal\n```\n\n## What It Creates\n\n1. **Subagent File**: `.claude/agents/{name}.md` with optimized configuration\n2. **Test File**: `.claude/agents/tests/{name}-test.md` with validation scenarios\n3. **Documentation**: Updates CLAUDE.md with usage instructions\n4. **Examples**: Adds example prompts for invoking the agent\n\n## Best Practices Applied\n\n- Single, clear responsibility principle\n- Minimal tool permissions\n- Proactive detection patterns\n- Detailed system prompts\n- Version control ready\n\n## Examples\n\nThe command includes patterns from successful agents like:\n- Performance Optimizer (profiling and benchmarking)\n- Blog Content Generator (research and writing)\n- Code Reviewer (quality and security checks)\n- Debugger (systematic issue resolution)\n\n## Requirements\n\n- Claude Code v1.0+\n- Project with `.claude/` directory support\n- Internet connection for documentation fetch","lastDownloaded":"2025-08-31T23:26:27.840Z","licenseType":"mit","likes":0,"mcpRequirements":[{"tier":"required","serverId":"filesystem"}],"mcp_search_content":"docker-filesystem","organizationUsername":"commands-com","price":"free","processedGalleryItems":[{"s3KeyThumbnail":"processed/e332e989-f092-4ccf-9edb-f4d006195896/1753931663217_preview_thumb.webp","s3KeyLarge":"processed/e332e989-f092-4ccf-9edb-f4d006195896/1753931663217_preview.webp","name":"1753931663217_preview.webp","originalKey":"temp-uploads/e332e989-f092-4ccf-9edb-f4d006195896/1753931663217_preview.png","pathLarge":"e332e989-f092-4ccf-9edb-f4d006195896/1753931663217_preview.webp","type":"image/webp","pathThumbnail":"e332e989-f092-4ccf-9edb-f4d006195896/1753931663217_preview_thumb.webp"}],"search_content":"subagent builder build perfect claude code subagents using the latest documentation and best practices /subagent-builder development claude","title":"Subagent Builder","type":"command","updatedAt":"2025-08-17T16:56:09.629Z","userId":"W0V8NAw5AhWRwcuwSoFLOi1Yem83","visibility":"public","name":"subagent-builder","userInteraction":{"userHasStarred":false}}