# Worksona Delegator MCP

A sophisticated Model Context Protocol (MCP) server that enables Claude and other MCP clients to perform complex task delegation using specialized AI agents and multiple coordination patterns.

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Node.js Version](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen)](https://nodejs.org/)
[![MCP Compatible](https://img.shields.io/badge/MCP-Compatible-blue)](https://modelcontextprotocol.io/)

## 🚀 Overview

The Worksona Delegator MCP transforms complex problem-solving by orchestrating multiple specialized AI agents through sophisticated delegation patterns. Instead of relying on a single AI response, tasks are intelligently decomposed and distributed across teams of specialized agents, each with distinct expertise and roles.

### ✨ Key Features

- **🏗️ 10+ Delegation Patterns**: Hierarchical, Peer-to-Peer, Iterative, Competitive, Federation, Adaptive, and more
- **🤖 Dynamic Agent Creation**: Intelligent agent selection based on task analysis and requirements
- **⚡ Real-time Monitoring**: Live task status, progress tracking, and agent coordination
- **🔧 Anthropic Integration**: Optimized for Claude models with seamless Claude Desktop integration
- **⏱️ Timeout Management**: Configurable timeout handling for reliable operation
- **🔌 MCP Protocol**: Full compliance with Model Context Protocol for seamless Claude integration
- **📊 Comprehensive Reporting**: Detailed execution analytics and result synthesis
- **🎛️ Extensible Architecture**: Plugin system for custom patterns, agents, and providers

## 🎯 Use Cases

- **📊 Business Analysis**: Market research, competitive analysis, strategic planning
- **💻 Software Development**: Code review, architecture analysis, documentation generation
- **📝 Content Creation**: Multi-perspective writing, editing workflows, content strategy
- **🔬 Research Projects**: Literature reviews, data analysis, comprehensive reporting
- **🎨 Creative Tasks**: Brainstorming, design thinking, creative problem-solving
- **🏢 Enterprise Workflows**: Complex business process automation and optimization

## 🏛️ Architecture

```mermaid
graph TB
    subgraph "MCP Client"
        C[Claude/Client]
        MCP[MCP Protocol]
    end
    
    subgraph "Delegator MCP Server"
        DS[Core Server]
        PM[Pattern Manager]
        AM[Agent Manager]
        TM[Task Manager]
    end
    
    subgraph "Delegation Engine"
        DP[Delegation Patterns]
        AF[Agent Framework]
        WS[Worksona.js]
    end
    
    subgraph "LLM Providers"
        OAI[OpenAI]
        ANT[Anthropic]
        GOO[Google]
    end
    
    C --> MCP
    MCP --> DS
    DS --> PM
    DS --> AM
    DS --> TM
    PM --> DP
    AM --> AF
    TM --> WS
    WS --> OAI
    WS --> ANT
    WS --> GOO
```

## 📋 Requirements

- Node.js 18.0.0 or higher
- npm or yarn package manager
- Anthropic API key (or use with Claude Desktop for seamless integration)
- MCP-compatible client (Claude Desktop, etc.)

## ⚡ Quick Start

### 1. Installation

```bash
# Clone the repository
git clone https://github.com/your-org/delegator-mcp.git
cd delegator-mcp

# Install dependencies
npm install

# Copy environment template
cp .env.example .env
```

### 2. Configuration

Edit `.env` with your API keys and preferences:

```env
# Anthropic API Key (required unless using Claude Desktop integration)
ANTHROPIC_API_KEY=your-anthropic-api-key

# Default Provider Configuration
WORKSONA_DEFAULT_PROVIDER=anthropic
WORKSONA_DEFAULT_MODEL=claude-3-5-sonnet-20241022

# Timeout Configuration
API_CALL_TIMEOUT=60000
DELEGATION_TIMEOUT=300000
PATTERN_TIMEOUT=600000

# Debug Settings
WORKSONA_DEBUG=false
```

### 3. Start the Server

```bash
# Development mode
npm run dev

# Production mode
npm start

# Using PM2 (recommended for production)
npm install -g pm2
pm2 start ecosystem.config.js
```

### 4. Configure MCP Client

Add to your Claude Desktop configuration:

```json
{
  "mcpServers": {
    "delegator": {
      "command": "node",
      "args": ["/path/to/delegator-mcp/src/index.js"],
      "env": {
        "ANTHROPIC_API_KEY": "your-anthropic-api-key"
      }
    }
  }
}
```

## 🎮 Usage Examples

### Basic Task Delegation

```javascript
// Create a delegation task
const task = await use_mcp_tool('delegator', 'create_delegation_task', {
  query: "Analyze the competitive landscape for renewable energy storage",
  pattern: "hierarchical",
  config: {
    maxAgents: 6,
    timeLimit: 600,
    temperature: 0.4
  }
});

// Execute the delegation
const execution = await use_mcp_tool('delegator', 'execute_delegation_pattern', {
  taskId: task.taskId
});

// Get results
const results = await use_mcp_tool('delegator', 'get_delegation_results', {
  taskId: task.taskId
});
```

### Pattern-Specific Examples

#### Hierarchical Delegation
Perfect for structured analysis and research tasks:

```javascript
const task = await use_mcp_tool('delegator', 'create_delegation_task', {
  query: "Create a comprehensive business plan for a sustainable tech startup",
  pattern: "hierarchical",
  config: {
    maxAgents: 8,
    roles: ["researcher", "analyst", "strategist", "writer", "critic", "synthesizer"]
  }
});
```

#### Competitive Evaluation
Ideal for comparing multiple solutions or approaches:

```javascript
const task = await use_mcp_tool('delegator', 'create_delegation_task', {
  query: "Design three different user interface approaches for a mobile banking app",
  pattern: "competitive",
  config: {
    competitorCount: 3,
    evaluationCriteria: ["usability", "security", "accessibility", "innovation"]
  }
});
```

#### Iterative Refinement
Best for improving and polishing content through multiple iterations:

```javascript
const task = await use_mcp_tool('delegator', 'create_delegation_task', {
  query: "Write and refine a technical article about quantum computing",
  pattern: "iterative",
  config: {
    maxIterations: 4,
    refinementAspects: ["clarity", "accuracy", "engagement", "structure"]
  }
});
```

### Structured Queries with Configuration

For programmatic control, you can use structured queries with precise configuration:

```javascript
// Example: 10-minute timeout with specific configuration
const result = await handleStructuredQuery({
  query: "how to identify and memorize prime numbers",
  config: {
    maxAgents: 4,
    timeLimit: 600, // 10 minutes in seconds
    focusAreas: [
      "identification methods",
      "memorization techniques", 
      "mathematical patterns",
      "practical applications"
    ],
    temperature: 0.6
  },
  pattern: "hierarchical"
});
```

#### Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `timeLimit` | number | `600` | Timeout in seconds (10 minutes) |
| `timeout` | number | `600000` | Timeout in milliseconds (alternative to timeLimit) |
| `maxAgents` | number | `5` | Maximum number of agents to create |
| `temperature` | number | `0.7` | AI model temperature for creativity control |
| `focusAreas` | array | `[]` | Specific areas to focus the analysis on |
| `pattern` | string | `"hierarchical"` | Delegation pattern to use |
| `delegationTimeout` | number | `600000` | Delegation timeout in milliseconds |

#### Dynamic Timeout Handling

The system dynamically handles timeout configuration with the following priority:
1. `timeLimit` (in seconds) - converted to milliseconds
2. `timeout` (in milliseconds) - used directly
3. `delegationTimeout` (in milliseconds) - used directly
4. Default: 600,000ms (10 minutes)

```javascript
// All equivalent - 10 minute timeout
const configs = [
  { timeLimit: 600 },
  { timeout: 600000 },
  { delegationTimeout: 600000 }
];
```

## 🔧 Configuration

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `ANTHROPIC_API_KEY` | - | Anthropic API key |
| `WORKSONA_DEFAULT_PROVIDER` | `anthropic` | Default LLM provider |
| `WORKSONA_DEFAULT_MODEL` | `claude-3-5-sonnet-20241022` | Default model |
| `API_CALL_TIMEOUT` | `60000` | API call timeout (ms) |
| `DELEGATION_TIMEOUT` | `600000` | Delegation timeout (ms) |
| `PATTERN_TIMEOUT` | `600000` | Pattern execution timeout (ms) |
| `MAX_CONCURRENT_TASKS` | `10` | Maximum concurrent tasks |
| `WORKSONA_DEBUG` | `false` | Enable debug logging |

### Pattern Configuration

Configure delegation patterns in `config/patterns.json`:

```json
{
  "patterns": {
    "hierarchical": {
      "enabled": true,
      "defaultConfig": {
        "maxAgents": 5,
        "timeLimit": 300,
        "temperature": 0.4
      },
      "constraints": {
        "minAgents": 2,
        "maxAgents": 10
      }
    },
    "competitive": {
      "enabled": true,
      "defaultConfig": {
        "competitorCount": 3,
        "evaluationRounds": 2
      }
    }
  }
}
```

## 🎭 Delegation Patterns

### 1. Hierarchical Pattern 🏢
**Best for**: Structured analysis, research projects, content creation
- Central coordinator delegates to specialized workers
- Clear chain of command and responsibility
- Sequential or parallel execution options

### 2. Peer-to-Peer Pattern 🤝
**Best for**: Collaborative tasks, brainstorming, consensus building
- Agents work together as equals
- Collaborative discussion and iteration
- Consensus-based decision making

### 3. Iterative Pattern 🔄
**Best for**: Content refinement, progressive enhancement, quality improvement
- Sequential refinement through multiple stages
- Each iteration builds on previous work
- Convergence towards optimal solution

### 4. Competitive Pattern 🏆
**Best for**: Optimization problems, creative tasks, solution comparison
- Multiple agents provide different solutions
- Comparative evaluation and selection
- Best solution wins or hybrid approach

### 5. Federation Pattern 🌐
**Best for**: Large-scale projects, multi-domain problems
- Multi-level hierarchy with domain coordinators
- Specialized coordination for different domains
- Integration of domain-specific results

### 6. Adaptive Pattern 🧠
**Best for**: Unknown complexity, experimental tasks, learning scenarios
- Dynamic pattern selection based on task analysis
- Self-adjusting approach based on intermediate results
- Learning from execution patterns

## 🤖 Agent Framework

### Available Agent Templates

#### Core Templates
- **base-delegator**: Task coordination and breakdown
- **base-researcher**: Information gathering and analysis
- **base-analyst**: Data processing and insight generation
- **base-writer**: Content creation and communication
- **base-critic**: Evaluation and quality assessment
- **base-synthesizer**: Result integration and summary

#### Specialized Templates
- **technical-agent**: Code and architecture analysis
- **business-agent**: Market and strategy analysis
- **creative-agent**: Design and creative content
- **domain-expert**: Subject-specific expertise

### Custom Agent Templates

Create custom agent templates in `agents/templates/`:

```json
{
  "id": "custom-agent",
  "name": "Custom Specialist",
  "description": "Specialized agent for custom tasks",
  "traits": {
    "personality": ["analytical", "thorough", "precise"],
    "knowledge": ["domain expertise", "analytical thinking"],
    "tone": "professional and detailed",
    "background": "Expert in specialized domain"
  },
  "config": {
    "provider": "anthropic",
    "model": "claude-3-5-sonnet-20241022",
    "temperature": 0.4,
    "maxTokens": 8000,
    "systemPrompt": "You are a specialized agent...",
    "examples": [
      {
        "user": "Example input",
        "assistant": "Example response"
      }
    ]
  }
}
```

## 🛠️ Development

### Project Structure

```
delegator-mcp/
├── src/
│   ├── core/              # Core delegation logic
│   ├── api/               # API endpoints and handlers
│   ├── delegation/        # Delegation patterns and strategies
│   ├── state/             # State management
│   ├── ui/                # User interface components
│   └── utils/             # Utilities and helpers
├── agents/
│   ├── templates/         # Agent template definitions
│   └── patterns/          # Pattern-specific configurations
├── config/                # Configuration files
├── docs/                  # Documentation
├── tests/                 # Test suites
└── scripts/               # Build and deployment scripts
```

### Running Tests

```bash
# Run all tests
npm test

# Run specific test suite
npm run test:patterns
npm run test:agents
npm run test:integration

# Run with coverage
npm run test:coverage
```

### Development Commands

```bash
# Start development server with hot reload
npm run dev

# Build for production
npm run build

# Lint and format code
npm run lint
npm run format

# Type checking
npm run type-check

# Generate documentation
npm run docs
```

## 🐳 Docker Deployment

### Quick Start with Docker

```bash
# Build image
docker build -t delegator-mcp .

# Run container
docker run -p 3000:3000 \
  -e OPENAI_API_KEY=your-key \
  -e ANTHROPIC_API_KEY=your-key \
  delegator-mcp
```

### Docker Compose

```yaml
version: '3.8'
services:
  delegator-mcp:
    build: .
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production
      - OPENAI_API_KEY=${OPENAI_API_KEY}
      - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
    volumes:
      - ./config:/app/config
      - ./logs:/app/logs
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
```

## 📊 Monitoring and Observability

### Health Checks

The server provides comprehensive health check endpoints:

```bash
# Basic health check
curl http://localhost:3000/health

# Detailed system status
curl http://localhost:3000/status

# Provider status
curl http://localhost:3000/providers/status
```

### Metrics and Logging

```bash
# Enable debug logging
DEBUG=delegator:* npm start

# View performance metrics
curl http://localhost:3000/metrics

# Monitor active tasks
curl http://localhost:3000/tasks/active
```

### Performance Optimization

- **Connection Pooling**: HTTP keep-alive for LLM APIs
- **Result Caching**: LRU cache for agent responses
- **Batch Processing**: Parallel execution where possible
- **Resource Limits**: Configurable concurrency and memory limits

## 🔐 Security

### API Key Management

- Environment variable configuration
- Secure storage and rotation
- Provider-specific key validation
- Automatic failover on authentication errors

### Rate Limiting

```javascript
// Configure rate limits
{
  "rateLimits": {
    "perMinute": 60,
    "perHour": 1000,
    "perDay": 10000
  }
}
```

### Input Validation

- Query sanitization and validation
- Configuration parameter validation
- Agent template validation
- Pattern input validation

## 🚨 Troubleshooting

### Common Issues

#### Timeout Errors
```bash
# Increase timeout values
export API_CALL_TIMEOUT=120000
export DELEGATION_TIMEOUT=600000

# Check network connectivity
curl -I https://api.openai.com/v1/models
```

#### Agent Creation Failures
```bash
# Verify API keys
npm run test:providers

# Check agent templates
npm run validate:templates

# Review logs
tail -f logs/delegator.log
```

#### Performance Issues
```bash
# Monitor resource usage
npm run monitor

# Check active tasks
curl http://localhost:3000/tasks/active

# Review configuration
npm run config:validate
```

### Debug Mode

Enable comprehensive debugging:

```bash
# Environment variable
export DEBUG=delegator:*

# Or in .env file
DEBUG=delegator:*
WORKSONA_DEBUG=true
```

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guidelines](CONTRIBUTING.md) for details.

### Development Setup

```bash
# Fork and clone the repository
git clone https://github.com/your-username/delegator-mcp.git
cd delegator-mcp

# Install dependencies
npm install

# Create feature branch
git checkout -b feature/your-feature-name

# Make changes and test
npm test

# Submit pull request
```

### Code Style

- ESLint configuration for code quality
- Prettier for code formatting
- TypeScript for type safety
- Conventional commits for changelog generation

### Testing

- Unit tests for core functionality
- Integration tests for delegation patterns
- End-to-end tests for MCP protocol
- Performance tests for load validation

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🙏 Acknowledgments

- [Model Context Protocol](https://modelcontextprotocol.io/) for the MCP specification
- [Worksona.js](https://github.com/worksona/worksona.js) for LLM provider abstraction
- [OpenAI](https://openai.com/), [Anthropic](https://anthropic.com/), and [Google AI](https://ai.google/) for LLM services
- The open-source community for inspiration and contributions

## 📞 Support

- **Documentation**: [Technical Documentation](MCP_TECHNICAL_DOCUMENTATION.md)
- **Issues**: [GitHub Issues](https://github.com/your-org/delegator-mcp/issues)
- **Discussions**: [GitHub Discussions](https://github.com/your-org/delegator-mcp/discussions)
- **Email**: support@delegator-mcp.com

## 🗺️ Roadmap

### Version 2.0
- [ ] Advanced pattern composition
- [ ] Multi-modal agent support
- [ ] Real-time streaming responses
- [ ] Enhanced error recovery

### Version 2.1
- [ ] Plugin marketplace
- [ ] Custom provider integration
- [ ] Advanced analytics dashboard
- [ ] Enterprise security features

### Version 3.0
- [ ] Distributed execution
- [ ] Machine learning optimization
- [ ] Advanced workflow automation
- [ ] Integration ecosystem

---

**Built with ❤️ by the Worksona team**

*Empowering intelligent task delegation through sophisticated multi-agent orchestration.* 