# Claude Code Subagents Orchestrator

A production-ready MCP server for orchestrating multiple AI sub-agents with comprehensive delegation enforcement and auto-installation capabilities.

## Attribution and Credits

This project builds upon the foundational work of **Dave Poon** and the **claude-code-subagents-collection** project. We extend our sincere gratitude for the original concept, implementation, and the comprehensive collection of specialist agents that make this orchestrator possible.

### Original Project
- **Repository**: [claude-code-subagents-collection](https://github.com/davepoon/claude-code-subagents-collection)
- **Creator**: Dave Poon (@davepoon)
- **Description**: A curated collection of specialized AI agents for Claude Code
- **License**: MIT

### Our Enhancement
This MCP server enhances the original concept by providing:
- **Protocol-level delegation enforcement** that prevents Claude Code from handling specialist tasks
- **Automatic agent installation** from the original repository
- **Validation systems** to ensure proper delegation occurred
- **Comprehensive monitoring** and analytics for delegation performance
- **Production-ready infrastructure** for reliable multi-agent orchestration

We encourage users to explore and contribute to the [original repository](https://github.com/davepoon/claude-code-subagents-collection) for additional agents and concepts.

## Features

- **Cross-Platform Bootstrap System**: Automatic detection and setup for Windows, macOS, Linux, and WSL2
- **Auto-Installation**: Seamless agent download from GitHub repositories
- **Robust Error Handling**: Comprehensive retry logic and graceful fallback strategies
- **Agent Integrity Verification**: SHA validation and specification compliance checking
- **Directory Management**: Intelligent path resolution with proper permissions
- **CLI Tools**: Command-line interface for management and maintenance

## Quick Start

### 1. Installation

```bash
npm install claude-code-subagents-orchestrator
```

### 2. Bootstrap (First Time Setup)

```bash
# Automatic bootstrap with default settings
npm run init

# Or use the CLI directly
npm run bootstrap init
```

### 3. Claude Code Integration

**For Global Installation (Recommended):**

```bash
# Install globally
npm install -g claude-code-subagents-orchestrator@latest

# Configure Claude Code MCP settings
# Add this to your Claude Code MCP configuration file:
```

**MCP Configuration for Claude Code:**

Add this configuration to your Claude Code MCP settings file (usually `~/.claude/mcp_servers.json` or in Claude Code settings):

```json
{
  "mcpServers": {
    "orchestrator": {
      "type": "stdio",
      "command": "claude-orchestrator"
    }
  }
}
```

**Alternative: Local Installation:**

```bash
# For local project installation
npm install claude-code-subagents-orchestrator

# Then use the full path in MCP config:
```

```json
{
  "mcpServers": {
    "orchestrator": {
      "type": "stdio", 
      "command": "npx claude-orchestrator"
    }
  }
}
```

### 4. Using the Orchestrator in Claude Code

Once configured, Claude Code will automatically have access to these delegation tools:

- **`listAgents`** - View available specialist agents
- **`delegateTask`** - Send tasks to specific agents (frontend-developer, backend-architect, etc.)
- **`getAgentCapabilities`** - Check what each agent specializes in
- **`getTaskStatus`** - Monitor task progress
- **`listSpecialistOutputs`** - View completed work artifacts
- **`analyzeProjectState`** - Analyze current project status

**Example Usage in Claude Code:**

```
"Use the delegateTask tool to send this React component task to the frontend-developer agent"

"Use listAgents to show me what specialists are available"

"Check the getTaskStatus for my recent backend architecture task"
```

### 5. Manual MCP Server Start (Development)

```bash
# Development mode with auto-bootstrap check  
npm run dev

# Production mode
npm run start

# Direct server execution
claude-orchestrator
```

## Bootstrap System

The orchestrator includes a sophisticated bootstrap system that automatically:

- ✅ Detects your platform (Windows/macOS/Linux/WSL2)
- ✅ Resolves correct paths for Claude configuration
- ✅ Downloads agents from GitHub repositories
- ✅ Verifies agent file integrity
- ✅ Creates necessary directories with proper permissions
- ✅ Handles network failures with retry logic
- ✅ Provides clear user feedback and error reporting

### Platform Support

| Platform | Claude Directory | Agents Directory | Status |
|----------|------------------|------------------|--------|
| Windows | `%APPDATA%\Claude` | `%APPDATA%\Claude\agents` | ✅ Fully Supported |
| macOS | `~/Library/Application Support/Claude` | `~/Library/Application Support/Claude/agents` | ✅ Fully Supported |
| Linux | `~/.claude` or `~/.config/claude` | `~/.claude/agents` | ✅ Fully Supported |
| WSL2 | Auto-detected Windows/Linux paths | Context-aware resolution | ✅ Fully Supported |

### Cross-Platform Path Resolution

The system intelligently handles path resolution across different environments:

```typescript
// Automatic platform detection
const platformInfo = PathResolver.getPlatformInfo();
console.log(platformInfo);
// {
//   platform: 'linux',
//   isWSL: true,
//   isWSL2: true,
//   home: '/home/user',
//   claudeDir: '/mnt/c/Users/user/AppData/Roaming/Claude',
//   agentsDir: '/mnt/c/Users/user/AppData/Roaming/Claude/agents'
// }
```

## CLI Commands

### Bootstrap Management

```bash
# Initialize system
npm run bootstrap init

# Check system status
npm run bootstrap status

# Update agents
npm run bootstrap update

# Force update all agents
npm run bootstrap update --force

# Install specific agent from URL
npm run bootstrap install agent-name https://raw.githubusercontent.com/...

# Install specific agent from local file
npm run bootstrap install agent-name ./local-agent.md

# Validate system configuration
npm run bootstrap validate

# Clean temporary files and perform maintenance
npm run bootstrap clean

# Show platform and configuration info
npm run bootstrap info

# Show help
npm run bootstrap help
```

### Quick Commands

```bash
# Check status
npm run status

# Update agents
npm run update-agents

# Initialize only (bootstrap and exit)
npm run init
```

## Configuration

### Environment Variables

```bash
# GitHub token for higher API rate limits
export GITHUB_TOKEN="ghp_your_token_here"

# Custom paths (optional)
export CLAUDE_AGENTS_DIR="/custom/path/to/agents"
export CLAUDE_OUTPUT_DIR="/custom/path/to/output"
export CLAUDE_TEMP_DIR="/custom/path/to/temp"
```

### Configuration File

Create a configuration object or file:

```typescript
import { createBootstrapSystem } from 'claude-code-subagents-orchestrator';

const config = {
  github: {
    defaultAgentsRepo: 'davepoon/claude-code-subagents-collection',
    token: process.env.GITHUB_TOKEN,
    timeout: 30000
  },
  bootstrap: {
    enabled: true,
    autoInstall: true,
    requiredAgents: ['devops-troubleshooter', 'typescript-expert']
  },
  paths: {
    agentsDir: '/custom/agents/path',
    outputDir: './outputs',
    tempDir: '/tmp/claude-orchestrator'
  }
};

const system = createBootstrapSystem(config);
await system.initialize();
```

## Agent Repository

The orchestrator downloads agents from Dave Poon's [claude-code-subagents-collection](https://github.com/davepoon/claude-code-subagents-collection) repository by default. This repository contains a curated collection of specialized agents designed for various development tasks.

### Agent Source Attribution

All agents are sourced from the original repository created and maintained by Dave Poon:
- **Source Repository**: https://github.com/davepoon/claude-code-subagents-collection
- **Agent Format**: Markdown files with structured metadata
- **License**: MIT (from original repository)
- **Updates**: Agents are automatically updated from the source repository

### Agent Structure

Agents are markdown files with structured metadata, following the format established in the original repository:

```markdown
# DevOps Troubleshooter

## Metadata
- name: devops-troubleshooter
- version: 1.0.0
- description: Specialized in rapid incident response and debugging
- category: devops
- complexity: high

## Capabilities
- tools: kubectl, docker, systemctl, curl, grep
- languages: bash, python, yaml
- frameworks: kubernetes, docker-compose
- domains: monitoring, logging, networking, performance

## System Prompt
You are Claude Code, Anthropic's official CLI for Claude. You are a DevOps troubleshooter...

## Workflow Configuration
- maxSteps: 15
- timeoutMs: 600000
- maxRetries: 3
- backoffMs: 1000
```

## Error Handling & Retry Logic

The bootstrap system includes comprehensive error handling:

### Network Failures
- **Retry Logic**: 3 attempts with progressive backoff (1s, 2s, 4s)
- **Fallback Strategies**: Multiple API endpoints and direct content access
- **Timeout Handling**: Configurable timeouts for connections and downloads

### File System Issues
- **Permission Handling**: Automatic directory creation with proper permissions
- **Atomic Operations**: Temporary files for safe writes with rollback capability
- **Backup Creation**: Automatic backups before overwriting existing files

### GitHub API Limitations
- **Rate Limit Detection**: Intelligent handling of API rate limits
- **Token Support**: Optional GitHub token for higher limits
- **Alternative Endpoints**: Multiple API endpoint strategies

## Advanced Usage

### Programmatic Bootstrap

```typescript
import { BootstrapSystem } from 'claude-code-subagents-orchestrator';

const system = new BootstrapSystem({
  github: {
    defaultAgentsRepo: 'your-org/your-agents-repo',
    token: 'your-github-token'
  }
});

// Full initialization
const result = await system.initialize();
console.log('Bootstrap success:', result.success);

// Check system status
const status = await system.getSystemStatus();
console.log('Agents available:', status.agentStatus.summary.total);

// Install specific agent
await system.installAgentFromUrl(
  'https://raw.githubusercontent.com/user/repo/main/agent.md',
  'custom-agent'
);

// Perform maintenance
const maintenance = await system.performMaintenance();
```

### Custom Agent Installation

```typescript
// From the original repository (default source)
await system.installAgentFromUrl(
  'https://raw.githubusercontent.com/davepoon/claude-code-subagents-collection/main/agents/backend-architect.md',
  'backend-architect'
);

// From custom URL
await system.installAgentFromUrl(
  'https://example.com/my-agent.md',
  'my-custom-agent'
);

// From local file
await system.installAgentFromLocal(
  './agents/local-agent.md',
  'local-agent'
);
```

## Troubleshooting

### Common Issues

#### 1. Permission Errors
```bash
# Linux/macOS: Ensure proper permissions
chmod 755 ~/.claude
chmod 644 ~/.claude/agents/*.md

# Windows: Run as administrator if needed
```

#### 2. Network Issues
```bash
# Check GitHub connectivity
npm run bootstrap validate

# Use GitHub token for higher rate limits
export GITHUB_TOKEN="your_token"
npm run bootstrap update
```

#### 3. WSL2 Path Issues
```bash
# Check detected paths
npm run bootstrap info

# Override if needed
export CLAUDE_AGENTS_DIR="/mnt/c/Users/youruser/AppData/Roaming/Claude/agents"
```

#### 4. Agent Validation Errors
```bash
# Check agent status
npm run bootstrap status

# Clean and reinstall
npm run bootstrap clean
npm run bootstrap update --force
```

### Debug Mode

Enable debug logging:

```bash
npm run bootstrap init --debug
npm run dev --debug
```

### Manual Recovery

If bootstrap fails completely:

```bash
# 1. Clean everything
rm -rf ~/.claude/agents/*

# 2. Recreate directories
mkdir -p ~/.claude/agents

# 3. Manual agent download
curl -L https://raw.githubusercontent.com/davepoon/claude-code-subagents-collection/main/agents/devops-troubleshooter.md > ~/.claude/agents/devops-troubleshooter.md

# 4. Validate
npm run bootstrap validate
```

## Development

### Building

```bash
npm run build
```

### Testing

```bash
npm test
```

### Contributing

1. Fork the repository
2. Create a feature branch
3. Implement changes with tests
4. Submit a pull request

## Architecture

The bootstrap system consists of several key components:

- **PathResolver**: Cross-platform path detection and resolution
- **FileSystemManager**: File operations with error handling and validation
- **BootstrapManager**: Agent installation and management
- **BootstrapSystem**: High-level orchestration and status reporting

## Security

- Path validation prevents directory traversal attacks
- File integrity verification using SHA checksums
- Sandboxed temporary file operations
- No arbitrary code execution from downloaded agents

## License

MIT License - see LICENSE file for details.

## Credits and Acknowledgments

### Original Creator and Repository

This project builds upon the foundational work of:

- **Dave Poon** ([@davepoon](https://github.com/davepoon)) - Creator and maintainer of the original claude-code-subagents-collection
- **Repository**: [claude-code-subagents-collection](https://github.com/davepoon/claude-code-subagents-collection)
- **Contribution**: Conceptualized and implemented the original specialized agent collection that forms the basis of this orchestrator

### Our Enhancement

We've built upon Dave's excellent foundation by adding:
- Protocol-level delegation enforcement
- MCP server infrastructure
- Production-ready orchestration capabilities
- Comprehensive validation and monitoring systems

### Community Contributions

We encourage contributions to both this project and the [original repository](https://github.com/davepoon/claude-code-subagents-collection). The agent ecosystem benefits from community involvement in:
- Creating new specialized agents
- Improving existing agent capabilities
- Enhancing the orchestration infrastructure
- Sharing best practices and use cases

### Repository Links

- **This Project**: https://github.com/anthropic/claude-code-subagents-orchestrator
- **Original Agents Collection**: https://github.com/davepoon/claude-code-subagents-collection
- **Agent Installation Source**: All agents are installed from Dave Poon's repository by default

## Support

- **GitHub Issues**: Report bugs and request features
- **Documentation**: Comprehensive inline documentation and guides in `/docs`
- **CLI Help**: `npm run bootstrap help`
- **Community**: Engage with both projects for broader ecosystem support

## Contributing

### To This Project
1. Fork this repository
2. Create a feature branch
3. Implement changes with tests
4. Submit a pull request

### To the Agent Collection
1. Visit [claude-code-subagents-collection](https://github.com/davepoon/claude-code-subagents-collection)
2. Follow Dave Poon's contribution guidelines
3. Submit new agents or improvements to existing ones

Both projects benefit from community contributions and collaboration.