# API Documentation

## Claude Code Subagents Orchestrator MCP Server

This document provides comprehensive documentation for all 6 core MCP tools and additional delegation enforcement tools provided by the Claude Code Subagents Orchestrator.

## Overview

The orchestrator provides two categories of tools:

1. **Core MCP Tools** - Standard agent management and orchestration tools
2. **Delegation Enforcement Tools** - Advanced tools for ensuring proper sub-agent delegation

## Core MCP Tools

### 1. `listAgents`

Lists available agents with optional filtering capabilities.

#### Parameters

```typescript
interface ListAgentsParams {
  category?: 'backend' | 'frontend' | 'fullstack' | 'devops' | 'testing' | 'security' | 'data';
  tags?: string[];
  includeMetadata?: boolean; // default: false
}
```

#### Response

```typescript
interface ListAgentsResponse {
  agents: Array<{
    name: string;
    category: string;
    description: string;
    version: string;
    tags: string[];
    capabilities?: {
      tools: string[];
      languages: string[];
      frameworks: string[];
      domains: string[];
    };
    metadata?: {
      installed: boolean;
      lastUpdated?: Date;
      dependencies: string[];
    };
  }>;
  totalCount: number;
  categories: Record<string, number>;
}
```

#### Example Usage

```javascript
// List all agents
const allAgents = await mcp.call('listAgents', {});

// List only backend agents
const backendAgents = await mcp.call('listAgents', {
  category: 'backend'
});

// List agents with specific tags and metadata
const taggedAgents = await mcp.call('listAgents', {
  tags: ['typescript', 'react'],
  includeMetadata: true
});
```

#### Error Codes

- `WORKFLOW_EXECUTION_FAILED` - Failed to read or parse agent specifications
- `FILESYSTEM_ERROR` - Cannot access agent directory

---

### 2. `installAgents`

Installs agents from various sources including GitHub repositories, local files, or direct URLs.

#### Parameters

```typescript
interface InstallAgentsParams {
  agents: string[];
  source?: 'github' | 'local' | 'url'; // default: 'github'
  repository?: string;
  force?: boolean; // default: false
}
```

#### Response

```typescript
interface InstallAgentsResponse {
  installed: Array<{
    name: string;
    version: string;
    source: string;
    success: boolean;
    error?: string;
  }>;
  failed: Array<{
    name: string;
    error: string;
    recoverable: boolean;
  }>;
  summary: {
    total: number;
    successful: number;
    failed: number;
  };
}
```

#### Example Usage

```javascript
// Install agents from default GitHub repository
const installation = await mcp.call('installAgents', {
  agents: ['backend-architect', 'frontend-developer', 'devops-engineer']
});

// Install from specific repository
const customInstall = await mcp.call('installAgents', {
  agents: ['custom-agent'],
  source: 'github',
  repository: 'myorg/my-agents-collection'
});

// Force reinstall existing agents
const forceInstall = await mcp.call('installAgents', {
  agents: ['typescript-expert'],
  force: true
});
```

#### Error Codes

- `AGENT_INSTALLATION_FAILED` - Failed to download or install agent
- `NETWORK_ERROR` - Cannot access remote repository
- `VALIDATION_ERROR` - Agent specification format invalid

---

### 3. `generateAgentPrompt`

Generates specialized prompts for specific agents and tasks with context-aware enhancement.

#### Parameters

```typescript
interface GenerateAgentPromptParams {
  agentName: string;
  task: string;
  context?: Record<string, any>;
  additionalConstraints?: string[];
}
```

#### Response

```typescript
interface GenerateAgentPromptResponse {
  prompt: string;
  agent: {
    name: string;
    version: string;
    capabilities: string[];
  };
  context: {
    task: string;
    constraints: string[];
    estimatedComplexity: 'low' | 'medium' | 'high';
    estimatedDuration: number; // milliseconds
  };
  recommendations?: string[];
}
```

#### Example Usage

```javascript
// Generate basic agent prompt
const prompt = await mcp.call('generateAgentPrompt', {
  agentName: 'backend-architect',
  task: 'Design a scalable API for a social media platform'
});

// Generate prompt with context and constraints
const contextualPrompt = await mcp.call('generateAgentPrompt', {
  agentName: 'frontend-developer',
  task: 'Build a responsive dashboard component',
  context: {
    framework: 'React',
    designSystem: 'Material-UI',
    browserSupport: ['Chrome', 'Firefox', 'Safari']
  },
  additionalConstraints: [
    'Must be accessible (WCAG 2.1 AA)',
    'Support mobile devices',
    'Load time under 2 seconds'
  ]
});
```

#### Error Codes

- `AGENT_NOT_FOUND` - Specified agent does not exist
- `PROMPT_GENERATION_FAILED` - Failed to generate prompt
- `VALIDATION_ERROR` - Invalid parameters

---

### 4. `generateMultiAgentWorkflow`

Generates comprehensive multi-agent workflows with dependency management and execution planning.

#### Parameters

```typescript
interface GenerateMultiAgentWorkflowParams {
  task: string;
  complexity?: 'low' | 'medium' | 'high'; // default: 'medium'
  preferredAgents?: string[];
  constraints?: {
    maxSteps?: number;
    timeoutMs?: number;
    parallel?: boolean; // default: false
  };
  context?: Record<string, any>;
}
```

#### Response

```typescript
interface GenerateMultiAgentWorkflowResponse {
  workflow: Workflow; // Complete workflow specification
  analysis: {
    complexity: 'low' | 'medium' | 'high';
    estimatedDuration: number;
    requiredAgents: string[];
    dependencies: string[];
    riskFactors: string[];
  };
  execution: {
    canExecuteImmediately: boolean;
    missingDependencies: string[];
    warnings: string[];
  };
}
```

#### Example Usage

```javascript
// Generate simple workflow
const workflow = await mcp.call('generateMultiAgentWorkflow', {
  task: 'Build a complete e-commerce application'
});

// Generate complex workflow with constraints
const complexWorkflow = await mcp.call('generateMultiAgentWorkflow', {
  task: 'Migrate legacy monolith to microservices architecture',
  complexity: 'high',
  preferredAgents: ['backend-architect', 'devops-engineer', 'database-expert'],
  constraints: {
    maxSteps: 10,
    timeoutMs: 3600000, // 1 hour
    parallel: true
  },
  context: {
    currentArchitecture: 'monolith',
    targetArchitecture: 'microservices',
    database: 'PostgreSQL',
    containerization: 'Docker'
  }
});
```

#### Error Codes

- `WORKFLOW_GENERATION_FAILED` - Failed to generate workflow
- `AGENT_NOT_AVAILABLE` - Required agent not available
- `COMPLEXITY_TOO_HIGH` - Task exceeds system capabilities

---

### 5. `generateRecoveryPrompt`

Generates recovery strategies and prompts for failed execution contexts with intelligent fallback options.

#### Parameters

```typescript
interface GenerateRecoveryPromptParams {
  executionContext: ExecutionContext;
  failedStep: string;
  errorDetails: {
    message: string;
    code: string;
    details?: any;
  };
  recoveryOptions?: Array<'retry' | 'skip' | 'alternative' | 'rollback'>;
}
```

#### Response

```typescript
interface GenerateRecoveryPromptResponse {
  recoveryStrategy: 'retry' | 'skip' | 'alternative' | 'rollback';
  prompt: string;
  modifications: {
    updatedStep?: any;
    alternativeSteps?: any[];
    rollbackPoint?: string;
  };
  analysis: {
    errorCategory: string;
    likelihood: 'low' | 'medium' | 'high';
    impact: 'low' | 'medium' | 'high';
    recommendations: string[];
  };
}
```

#### Example Usage

```javascript
// Generate recovery for failed step
const recovery = await mcp.call('generateRecoveryPrompt', {
  executionContext: previousWorkflow.context,
  failedStep: 'database_migration',
  errorDetails: {
    message: 'Connection timeout to database',
    code: 'DB_CONNECTION_TIMEOUT',
    details: { host: 'localhost', port: 5432 }
  },
  recoveryOptions: ['retry', 'alternative']
});

// Generate recovery with rollback option
const rollbackRecovery = await mcp.call('generateRecoveryPrompt', {
  executionContext: currentContext,
  failedStep: 'deployment',
  errorDetails: {
    message: 'Deployment failed due to insufficient resources',
    code: 'RESOURCE_EXHAUSTED'
  },
  recoveryOptions: ['rollback', 'alternative']
});
```

#### Error Codes

- `RECOVERY_GENERATION_FAILED` - Failed to generate recovery strategy
- `INVALID_EXECUTION_CONTEXT` - Provided context is invalid
- `NO_RECOVERY_OPTIONS` - No viable recovery options available

---

### 6. `analyzeProjectState`

Analyzes project state including file structure, dependencies, and git status with intelligent recommendations.

#### Parameters

```typescript
interface AnalyzeProjectStateParams {
  projectPath?: string;
  includeFileStructure?: boolean; // default: true
  includeDependencies?: boolean; // default: true
  includeGitStatus?: boolean; // default: true
  depth?: number; // default: 3
}
```

#### Response

```typescript
interface AnalyzeProjectStateResponse {
  project: {
    path: string;
    name: string;
    type: string;
    language?: string;
    framework?: string;
  };
  structure?: {
    files: Array<{
      path: string;
      type: 'file' | 'directory';
      size?: number;
      lastModified?: Date;
    }>;
    depth: number;
    totalFiles: number;
    totalDirectories: number;
  };
  dependencies?: {
    package?: Record<string, string>;
    runtime?: string[];
    development?: string[];
  };
  git?: {
    branch: string;
    status: 'clean' | 'dirty' | 'detached';
    commits: number;
    lastCommit?: {
      hash: string;
      message: string;
      date: Date;
    };
  };
  recommendations: Array<{
    type: 'agent' | 'workflow' | 'tool';
    name: string;
    reason: string;
    priority: 'low' | 'medium' | 'high';
  }>;
}
```

#### Example Usage

```javascript
// Analyze current project
const analysis = await mcp.call('analyzeProjectState', {});

// Analyze specific project with limited depth
const targetAnalysis = await mcp.call('analyzeProjectState', {
  projectPath: '/path/to/project',
  depth: 2,
  includeGitStatus: false
});

// Quick analysis without file structure
const quickAnalysis = await mcp.call('analyzeProjectState', {
  includeFileStructure: false,
  includeDependencies: true,
  includeGitStatus: true
});
```

#### Error Codes

- `PROJECT_ANALYSIS_FAILED` - Failed to analyze project
- `PATH_NOT_FOUND` - Specified path does not exist
- `PERMISSION_DENIED` - Insufficient permissions to access project

## Delegation Enforcement Tools

These advanced tools ensure proper sub-agent delegation and prevent Claude Code from handling specialist tasks.

### 1. `forceDelegation`

**CRITICAL TOOL**: Forces delegation to specialist agents and prevents Claude Code from handling specialist tasks.

#### Parameters

```typescript
interface ForceDelegationParams {
  task: string;
  targetAgent?: string;
  context?: Record<string, any>;
  enforcementLevel?: 'strict' | 'moderate' | 'advisory'; // default: 'strict'
  bypassProtection?: boolean; // default: true
}
```

#### Response

```typescript
interface ForceDelegationResponse {
  delegationEnforced: boolean;
  agentUsed: string;
  executionTime: number;
  output: any;
  classification: TaskClassification;
  sessionId: string;
  bypassPrevented: boolean;
}
```

#### Example Usage

```javascript
// Force strict delegation to backend architect
const delegation = await mcp.call('forceDelegation', {
  task: 'Design a microservices architecture for an e-commerce platform',
  targetAgent: 'backend-architect',
  enforcementLevel: 'strict'
});

// Force delegation with context
const contextualDelegation = await mcp.call('forceDelegation', {
  task: 'Optimize database queries for better performance',
  context: {
    database: 'PostgreSQL',
    currentPerformance: 'slow',
    expectedImprovement: '50%'
  }
});
```

#### Enforcement Levels

- **strict**: Completely blocks Claude Code execution, forces agent spawning
- **moderate**: Injects delegation markers, modifies requests
- **advisory**: Adds delegation suggestions while allowing execution

---

### 2. `validateDelegation`

**CRITICAL TOOL**: Validates that delegation occurred and Claude Code was bypassed successfully.

#### Parameters

```typescript
interface ValidateDelegationParams {
  originalRequest: any;
  response: any;
  expectedAgent: string;
}
```

#### Response

```typescript
interface DelegationValidation {
  delegationOccurred: boolean;
  agentUsed: string;
  claudeCodeBypassed: boolean;
  evidence: string[];
}
```

#### Example Usage

```javascript
// Validate delegation occurred
const validation = await mcp.call('validateDelegation', {
  originalRequest: previousRequest,
  response: delegationResponse,
  expectedAgent: 'backend-architect'
});

if (!validation.delegationOccurred) {
  console.error('Delegation failed:', validation.evidence);
}
```

---

### 3. `delegationStatus`

**MONITORING TOOL**: Monitors the status of delegation sessions and agent execution.

#### Parameters

```typescript
interface DelegationStatusParams {
  sessionId: string;
}
```

#### Response

```typescript
interface DelegationStatusResponse {
  sessionId: string;
  agentId: string;
  status: 'active' | 'completed' | 'failed' | 'timeout';
  startTime: Date;
  enforced: boolean;
  duration: number;
}
```

#### Example Usage

```javascript
// Monitor delegation status
const status = await mcp.call('delegationStatus', {
  sessionId: 'forced_delegation_1640995200000_abc123'
});

console.log(`Session ${status.sessionId} is ${status.status}`);
```

---

### 4. `delegationMetrics`

**ANALYTICS TOOL**: Provides analytics and metrics about delegation performance and bypass prevention effectiveness.

#### Parameters

None required.

#### Response

```typescript
interface DelegationMetrics {
  router: {
    successfulDelegations: number;
    failedDelegations: number;
    averageExecutionTime: number;
    activeAgents: number;
  };
  interceptor: {
    activeInterceptions: number;
    totalInterceptions: number;
    enforcementLevel: string;
  };
  health: Record<string, {
    status: string;
    lastSeen: Date;
    successRate: number;
    executionCount: number;
  }>;
  summary: {
    totalDelegations: number;
    successRate: number;
    averageExecutionTime: number;
    activeAgents: number;
    bypassPreventionRate: number;
  };
}
```

#### Example Usage

```javascript
// Get delegation metrics
const metrics = await mcp.call('delegationMetrics', {});

console.log(`Success rate: ${metrics.summary.successRate * 100}%`);
console.log(`Bypass prevention: ${metrics.summary.bypassPreventionRate * 100}%`);
```

---

### 5. `delegationConfig`

**CONFIGURATION TOOL**: Configures delegation enforcement parameters and rules.

#### Parameters

```typescript
interface DelegationConfigParams {
  enforcementLevel?: 'strict' | 'moderate' | 'advisory';
  addRule?: {
    domain: string;
    pattern: string;
    targetAgent: string;
    priority: number;
  };
  removeRule?: {
    domain: string;
    pattern: string;
  };
}
```

#### Response

```typescript
interface DelegationConfigResponse {
  enforcementLevel: string;
  activeInterceptions: number;
  message: string;
}
```

#### Example Usage

```javascript
// Set enforcement level
const config = await mcp.call('delegationConfig', {
  enforcementLevel: 'strict'
});

// Add delegation rule
const ruleConfig = await mcp.call('delegationConfig', {
  addRule: {
    domain: 'frontend',
    pattern: 'react|component|ui',
    targetAgent: 'frontend-developer',
    priority: 10
  }
});
```

## Enhanced Tool Variants

### 1. `generateAgentPromptEnhanced`

Enhanced version with delegation enforcement and validation tokens.

#### Additional Features

- Delegation enforcement markers
- Validation tokens for bypass prevention
- Enhanced context awareness
- Automatic agent capability matching

### 2. `generateRecoveryPromptEnhanced`

Enhanced recovery with escalation and alternative agent suggestions.

#### Additional Features

- Escalation strategies
- Alternative agent recommendations
- Failure pattern analysis
- Enhanced fallback options

### 3. `generateMultiAgentWorkflowEnhanced`

Enhanced workflow generation with delegation enforcement at each step.

#### Additional Features

- Per-step delegation enforcement
- Dependency-aware prompt generation
- Parallel execution optimization
- Enhanced validation mechanisms

## Error Handling

### Error Types

```typescript
enum ErrorCode {
  // Core errors
  AGENT_NOT_FOUND = 'AGENT_NOT_FOUND',
  WORKFLOW_EXECUTION_FAILED = 'WORKFLOW_EXECUTION_FAILED',
  VALIDATION_ERROR = 'VALIDATION_ERROR',
  
  // Enhanced errors
  DELEGATION_FAILED = 'DELEGATION_FAILED',
  AGENT_SPAWN_FAILED = 'AGENT_SPAWN_FAILED',
  BYPASS_DETECTED = 'BYPASS_DETECTED',
  CONFIGURATION_ERROR = 'CONFIGURATION_ERROR',
}
```

### Error Response Format

```typescript
interface ErrorResponse {
  success: false;
  error: {
    code: string;
    message: string;
    details?: any;
    retryable: boolean;
  };
  metadata: {
    timestamp: Date;
    toolName: string;
    executionTime: number;
  };
}
```

## Rate Limiting

### Limits

- **Core tools**: 100 requests per minute per client
- **Delegation tools**: 50 requests per minute per client
- **Analysis tools**: 20 requests per minute per client

### Headers

Response headers include rate limiting information:

```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995260
```

## Authentication

The MCP server uses stdio transport and inherits authentication from the Claude Code client. No additional authentication is required.

## Usage Guidelines

### Best Practices

1. **Use delegation enforcement** for specialist tasks
2. **Validate delegation success** using validation tools
3. **Monitor metrics** for performance optimization
4. **Handle errors gracefully** with proper retry logic
5. **Cache agent lists** to reduce API calls

### Common Patterns

#### Task Delegation Pattern

```javascript
// 1. Classify task
const prompt = await mcp.call('generateAgentPrompt', {
  agentName: 'backend-architect',
  task: complexTask
});

// 2. Force delegation
const delegation = await mcp.call('forceDelegation', {
  task: complexTask,
  targetAgent: 'backend-architect'
});

// 3. Validate success
const validation = await mcp.call('validateDelegation', {
  originalRequest: prompt,
  response: delegation,
  expectedAgent: 'backend-architect'
});
```

#### Multi-Agent Workflow Pattern

```javascript
// 1. Generate workflow
const workflow = await mcp.call('generateMultiAgentWorkflow', {
  task: 'Build complete application',
  complexity: 'high'
});

// 2. Execute each step with delegation
for (const step of workflow.workflow.steps) {
  const delegation = await mcp.call('forceDelegation', {
    task: step.task,
    targetAgent: step.agent
  });
  
  // Handle results...
}
```

#### Recovery Pattern

```javascript
try {
  const result = await mcp.call('forceDelegation', { task });
} catch (error) {
  const recovery = await mcp.call('generateRecoveryPrompt', {
    executionContext: context,
    failedStep: 'delegation',
    errorDetails: error
  });
  
  // Implement recovery strategy...
}
```

## Monitoring and Debugging

### Debug Mode

Enable debug mode for detailed logging:

```javascript
const result = await mcp.call('forceDelegation', {
  task: 'debug task',
  debug: true
});
```

### Health Checks

Monitor system health:

```javascript
const metrics = await mcp.call('delegationMetrics', {});
const healthScore = metrics.summary.successRate * metrics.summary.bypassPreventionRate;

if (healthScore < 0.9) {
  console.warn('Delegation system health degraded');
}
```

### Troubleshooting

Common issues and solutions:

1. **Agent not found**: Ensure agent is installed via `installAgents`
2. **Delegation failed**: Check enforcement level and agent availability
3. **Bypass detected**: Increase enforcement level or check configuration
4. **Performance issues**: Monitor metrics and optimize workflow complexity

## SDK Integration

### Node.js Example

```javascript
import { MCPClient } from '@modelcontextprotocol/sdk/client/index.js';

const client = new MCPClient({
  name: 'my-app',
  version: '1.0.0'
});

// Connect to orchestrator
await client.connect({
  command: 'node',
  args: ['path/to/orchestrator/server.js']
});

// Use tools
const agents = await client.call('listAgents', {});
const delegation = await client.call('forceDelegation', {
  task: 'implement feature',
  targetAgent: 'backend-architect'
});
```

### Python Example

```python
from mcp import Client

client = Client()
await client.connect('claude-code-subagents-orchestrator')

# List agents
agents = await client.call('listAgents', {})

# Force delegation
delegation = await client.call('forceDelegation', {
    'task': 'implement feature',
    'targetAgent': 'backend-architect'
})
```

## Migration Guide

### From Manual Delegation

If migrating from manual delegation patterns:

1. Replace manual agent mentions with `forceDelegation` calls
2. Add validation checks using `validateDelegation`
3. Monitor delegation success with `delegationMetrics`
4. Configure enforcement rules using `delegationConfig`

### Version Compatibility

- **v1.0.x**: Full API compatibility
- **v0.x**: Deprecated, upgrade recommended
- **Future versions**: Backward compatibility maintained

## Support

For API support and questions:

- **Documentation**: [GitHub Repository](https://github.com/anthropic/claude-code-subagents-orchestrator)
- **Issues**: [GitHub Issues](https://github.com/anthropic/claude-code-subagents-orchestrator/issues)
- **Community**: [GitHub Discussions](https://github.com/anthropic/claude-code-subagents-orchestrator/discussions)