UNPKG

claude-code-subagents-orchestrator

Version:

Claude Code Sub-agents Orchestrator - A powerful MCP server for orchestrating multiple AI sub-agents for complex task execution in Claude Code

1,083 lines (874 loc) 30.8 kB
# Delegation Best Practices and Troubleshooting Guide ## How the MCP Solves Delegation Recognition Problems The Claude Code Subagents Orchestrator MCP server fundamentally solves the delegation recognition problem that exists in manual sub-agent orchestration approaches. ### The Core Problem **Manual delegation attempts fail because Claude Code has no native sub-agent awareness:** 1. **No Protocol-Level Recognition**: Claude Code treats "frontend-developer, implement..." as regular instructions 2. **No Delegation Capability**: Claude Code naturally handles tasks itself instead of delegating 3. **No Enforcement Mechanism**: No way to prevent Claude Code from processing specialist tasks 4. **No Validation System**: No confirmation that delegation actually occurred ### The MCP Solution This MCP server **creates delegation capability that doesn't exist natively** through: #### 1. Protocol-Level Interception ```typescript // MCP requests are intercepted BEFORE Claude Code processes them export class DelegationInterceptor { async interceptRequest(request: MCPRequest): Promise<MCPResponse> { // Classify task domain const classification = await this.taskClassifier.classifyTask(request); // Check if delegation is required if (classification.delegationRequired) { // FORCE delegation - bypass Claude Code entirely return await this.agentRouter.executeWithAgent( classification.suggestedAgent, request, true // Enforced delegation ); } // Allow normal processing for non-specialist tasks return await this.normalProcessing(request); } } ``` #### 2. Physical Process Separation ```typescript // Agents run in separate processes with direct MCP communication export class AgentRouter { async executeWithAgent(agentId: string, request: MCPRequest, enforced: boolean) { // Spawn dedicated agent process const agentProcess = await this.spawnAgent(agentId); // Direct MCP communication - Claude Code never sees the request const response = await this.directMCPCall(agentProcess, request); // Validate delegation occurred return this.validateDelegation(response, agentId); } } ``` #### 3. Mandatory Routing Through MCP ```javascript // ALL specialist tasks MUST go through the MCP server // Claude Code cannot bypass this because: // 1. MCP protocol requires tool calls const delegation = await mcp.call('forceDelegation', { task: 'Design microservices architecture', targetAgent: 'backend-architect' }); // 2. Validation ensures delegation occurred const validation = await mcp.call('validateDelegation', { originalRequest: request, response: delegation, expectedAgent: 'backend-architect' }); // 3. If validation fails, the system can retry or escalate if (!validation.delegationOccurred) { // Force retry with stricter enforcement await mcp.call('forceDelegation', { task: originalTask, enforcementLevel: 'strict', bypassProtection: true }); } ``` #### 4. Validation Tokens and Bypass Prevention ```typescript // Validation tokens prevent Claude Code from faking delegation export class PromptGenerationEngine { generateDelegationPrompt(task: string, context: DelegationContext) { return { prompt: `${task} DELEGATION_ENFORCED: true AGENT_USED: ${context.selectedAgent} VALIDATION_TOKEN: ${this.generateValidationToken()} BYPASS_PROTECTED: true SESSION_ID: ${context.sessionId} You are now executing as ${context.selectedAgent}. Claude Code has been bypassed for this specialist task.`, validationTokens: this.generateValidationTokenSet(), metadata: { delegationEnforced: true, bypassPrevented: true, agentUsed: context.selectedAgent } }; } } ``` ## Delegation Enforcement Mechanisms ### Enforcement Levels #### 1. Strict Mode (Recommended) - **Completely blocks** Claude Code execution for specialist tasks - **Forces agent spawning** with process isolation - **Validates delegation** with multi-layer confirmation - **Prevents bypass** through physical separation ```javascript const strictDelegation = await mcp.call('forceDelegation', { task: 'Optimize database performance', enforcementLevel: 'strict', bypassProtection: true }); // Result: Agent process spawned, Claude Code completely bypassed console.log(strictDelegation.bypassPrevented); // true ``` #### 2. Moderate Mode - **Injects delegation markers** into requests - **Modifies prompts** to enforce delegation awareness - **Monitors execution** for delegation compliance - **Allows fallback** to Claude Code if agent fails ```javascript const moderateDelegation = await mcp.call('forceDelegation', { task: 'Create React component', enforcementLevel: 'moderate' }); // Result: Request modified, delegation strongly encouraged ``` #### 3. Advisory Mode - **Adds delegation suggestions** to prompts - **Tracks delegation attempts** for metrics - **Allows normal execution** while logging recommendations - **Useful for gradual migration** from manual patterns ```javascript const advisoryDelegation = await mcp.call('forceDelegation', { task: 'General development task', enforcementLevel: 'advisory' }); // Result: Suggestion added, normal execution allowed ``` ### Delegation Validation Pipeline #### Multi-Layer Validation ```typescript export class DelegationValidator { async validateDelegation( originalRequest: any, response: any, expectedAgent: string ): Promise<DelegationValidation> { // Layer 1: Response Metadata Validation const metadataValid = this.validateResponseMetadata(response, expectedAgent); // Layer 2: Process Execution Validation const processValid = this.validateProcessExecution(expectedAgent); // Layer 3: Content Analysis Validation const contentValid = this.validateResponseContent(response, expectedAgent); // Layer 4: Session Tracking Validation const sessionValid = this.validateSessionTracking(response.sessionId); return { delegationOccurred: metadataValid && processValid, claudeCodeBypassed: processValid && sessionValid, agentUsed: this.extractAgentUsed(response), evidence: this.compileEvidence([ metadataValid, processValid, contentValid, sessionValid ]) }; } } ``` #### Validation Evidence Collection ```javascript // Example validation evidence const validation = await mcp.call('validateDelegation', { originalRequest: request, response: delegationResponse, expectedAgent: 'backend-architect' }); console.log(validation.evidence); // [ // "Response indicates agent used: backend-architect", // "Expected agent (backend-architect) was used", // "Response marked as delegation enforced", // "Response indicates bypass was prevented", // "Found 1 active enforced sessions for backend-architect", // "Delegation interceptor shows 1 active interceptions" // ] ``` ## Best Practices for Ensuring Sub-Agent Engagement ### 1. Always Use Force Delegation for Specialist Tasks ```javascript // ❌ WRONG: Manual delegation (unreliable) const manualPrompt = "frontend-developer, create a React component for user authentication"; // ✅ CORRECT: Force delegation (guaranteed) const delegation = await mcp.call('forceDelegation', { task: 'Create a React component for user authentication', targetAgent: 'frontend-developer', enforcementLevel: 'strict' }); ``` ### 2. Always Validate Delegation Success ```javascript // ❌ WRONG: Assume delegation worked const result = await mcp.call('forceDelegation', { task, targetAgent }); // No validation - might have failed silently // ✅ CORRECT: Validate delegation occurred const delegation = await mcp.call('forceDelegation', { task, targetAgent }); const validation = await mcp.call('validateDelegation', { originalRequest: request, response: delegation, expectedAgent: targetAgent }); if (!validation.delegationOccurred) { throw new Error(`Delegation failed: ${validation.evidence.join(', ')}`); } ``` ### 3. Use Task Classification for Agent Selection ```javascript // ❌ WRONG: Hardcode agent selection const delegation = await mcp.call('forceDelegation', { task: 'Complex task involving multiple domains', targetAgent: 'backend-architect' // Might not be optimal }); // ✅ CORRECT: Use intelligent classification const prompt = await mcp.call('generateAgentPrompt', { agentName: 'any', // Let system choose task: 'Complex task involving multiple domains' }); const delegation = await mcp.call('forceDelegation', { task: 'Complex task involving multiple domains', // No targetAgent - let classifier choose optimal agent enforcementLevel: 'strict' }); ``` ### 4. Implement Proper Error Handling and Recovery ```javascript async function robustDelegation(task, preferredAgent) { try { // Attempt delegation const delegation = await mcp.call('forceDelegation', { task, targetAgent: preferredAgent, enforcementLevel: 'strict' }); // Validate success const validation = await mcp.call('validateDelegation', { originalRequest: { task, targetAgent: preferredAgent }, response: delegation, expectedAgent: preferredAgent }); if (!validation.delegationOccurred) { throw new Error('Delegation validation failed'); } return delegation; } catch (error) { // Generate recovery strategy const recovery = await mcp.call('generateRecoveryPrompt', { executionContext: { task, selectedAgent: preferredAgent }, failedStep: 'delegation', errorDetails: { message: error.message, code: 'DELEGATION_FAILED' }, recoveryOptions: ['retry', 'alternative'] }); // Implement recovery if (recovery.recoveryStrategy === 'alternative') { return await robustDelegation(task, recovery.alternativeAgent); } else if (recovery.recoveryStrategy === 'retry') { return await robustDelegation(task, preferredAgent); } throw error; } } ``` ### 5. Monitor Delegation Metrics for Performance ```javascript // Regular health monitoring async function monitorDelegationHealth() { const metrics = await mcp.call('delegationMetrics', {}); console.log(`Delegation Success Rate: ${metrics.summary.successRate * 100}%`); console.log(`Bypass Prevention Rate: ${metrics.summary.bypassPreventionRate * 100}%`); console.log(`Average Execution Time: ${metrics.summary.averageExecutionTime}ms`); // Alert if performance degrades if (metrics.summary.successRate < 0.9) { console.warn('⚠️ Delegation success rate below 90%'); // Investigate failing agents for (const [agentId, health] of Object.entries(metrics.health)) { if (health.successRate < 0.8) { console.warn(`Agent ${agentId} success rate: ${health.successRate * 100}%`); } } } if (metrics.summary.bypassPreventionRate < 0.95) { console.error('🚨 Claude Code bypass detection - delegation enforcement failing'); } } // Run monitoring periodically setInterval(monitorDelegationHealth, 300000); // Every 5 minutes ``` ## Troubleshooting Delegation Failures ### Common Delegation Issues #### 1. Agent Not Found **Symptoms:** - "Agent not found" errors - Delegation attempts fail immediately **Diagnosis:** ```javascript // Check agent availability const agents = await mcp.call('listAgents', {}); console.log('Available agents:', agents.agents.map(a => a.name)); // Verify specific agent const targetAgent = 'backend-architect'; const agent = agents.agents.find(a => a.name === targetAgent); if (!agent) { console.error(`Agent ${targetAgent} not found`); } ``` **Solutions:** ```javascript // Install missing agent const installation = await mcp.call('installAgents', { agents: ['backend-architect'], force: true }); // Verify installation if (installation.summary.successful > 0) { console.log('Agent installed successfully'); } else { console.error('Installation failed:', installation.failed); } ``` #### 2. Delegation Bypass Detected **Symptoms:** - `validation.claudeCodeBypassed === false` - Tasks executed by Claude Code instead of agents - Missing validation tokens in responses **Diagnosis:** ```javascript const validation = await mcp.call('validateDelegation', { originalRequest: request, response: response, expectedAgent: 'backend-architect' }); console.log('Delegation occurred:', validation.delegationOccurred); console.log('Claude Code bypassed:', validation.claudeCodeBypassed); console.log('Evidence:', validation.evidence); // Check active sessions const metrics = await mcp.call('delegationMetrics', {}); console.log('Active enforced sessions:', metrics.summary.activeAgents); ``` **Solutions:** ```javascript // Increase enforcement level await mcp.call('delegationConfig', { enforcementLevel: 'strict' }); // Force delegation with bypass protection const strictDelegation = await mcp.call('forceDelegation', { task: originalTask, enforcementLevel: 'strict', bypassProtection: true, targetAgent: expectedAgent }); // Add delegation rule for this type of task await mcp.call('delegationConfig', { addRule: { domain: 'backend', pattern: 'architecture|api|database', targetAgent: 'backend-architect', priority: 10 } }); ``` #### 3. Agent Process Failures **Symptoms:** - Agent spawn errors - Process timeout issues - Communication failures **Diagnosis:** ```javascript // Check agent health const metrics = await mcp.call('delegationMetrics', {}); for (const [agentId, health] of Object.entries(metrics.health)) { console.log(`${agentId}: ${health.status}, success rate: ${health.successRate}`); if (health.status !== 'healthy') { console.warn(`Agent ${agentId} is unhealthy`); } } // Monitor specific session try { const status = await mcp.call('delegationStatus', { sessionId: 'your-session-id' }); console.log('Session status:', status); } catch (error) { console.error('Session not found or failed:', error.message); } ``` **Solutions:** ```javascript // Restart unhealthy agents (implementation-specific) // This would typically be handled by the MCP server internally // Use alternative agent const recovery = await mcp.call('generateRecoveryPrompt', { executionContext: { selectedAgent: 'backend-architect' }, failedStep: 'agent_spawn', errorDetails: { message: 'Agent process failed to start', code: 'AGENT_SPAWN_FAILED' }, recoveryOptions: ['alternative'] }); // Retry with alternative agent const alternativeDelegation = await mcp.call('forceDelegation', { task: originalTask, targetAgent: recovery.alternativeAgent }); ``` #### 4. Task Classification Errors **Symptoms:** - Wrong agent selected for tasks - Low confidence scores in classification - Unexpected delegation behavior **Diagnosis:** ```javascript // Test task classification const prompt = await mcp.call('generateAgentPrompt', { agentName: 'any', task: 'Your problematic task here' }); console.log('Classification:', prompt.context); console.log('Estimated complexity:', prompt.context.estimatedComplexity); // Check if task is being classified correctly if (prompt.agent.name !== expectedAgent) { console.warn(`Expected ${expectedAgent}, got ${prompt.agent.name}`); } ``` **Solutions:** ```javascript // Add context to improve classification const betterPrompt = await mcp.call('generateAgentPrompt', { agentName: 'any', task: 'Your task here', context: { domain: 'backend', framework: 'Node.js', complexity: 'high' } }); // Override classification with specific agent const forcedDelegation = await mcp.call('forceDelegation', { task: 'Your task here', targetAgent: 'backend-architect', // Override classification enforcementLevel: 'strict' }); // Add custom classification rule await mcp.call('delegationConfig', { addRule: { domain: 'backend', pattern: 'node.js|express|mongodb', targetAgent: 'backend-architect', priority: 15 } }); ``` ### Recovery Procedures #### Automated Recovery Workflow ```javascript async function autoRecovery(originalTask, originalAgent, error) { console.log(`🔄 Starting auto-recovery for failed delegation...`); // Step 1: Generate recovery strategy const recovery = await mcp.call('generateRecoveryPrompt', { executionContext: { task: originalTask, selectedAgent: originalAgent, retryCount: 0 }, failedStep: 'delegation', errorDetails: { message: error.message, code: error.code || 'UNKNOWN_ERROR' }, recoveryOptions: ['retry', 'alternative', 'rollback'] }); console.log(`📋 Recovery strategy: ${recovery.recoveryStrategy}`); // Step 2: Implement recovery switch (recovery.recoveryStrategy) { case 'retry': console.log(`🔄 Retrying with same agent...`); await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2s return await robustDelegation(originalTask, originalAgent); case 'alternative': console.log(`🔀 Switching to alternative agent: ${recovery.alternativeAgent}`); return await robustDelegation(originalTask, recovery.alternativeAgent); case 'rollback': console.log(`⏪ Rolling back to previous state...`); // Implement rollback logic throw new Error('Task failed - rolled back to previous state'); default: console.error(`❌ No viable recovery strategy found`); throw error; } } ``` #### Manual Recovery Procedures ##### 1. Reset Delegation System ```javascript // Clear all active sessions and reset async function resetDelegationSystem() { console.log('🔄 Resetting delegation system...'); // Get current metrics const metrics = await mcp.call('delegationMetrics', {}); console.log(`Current active agents: ${metrics.summary.activeAgents}`); // Reset enforcement level await mcp.call('delegationConfig', { enforcementLevel: 'strict' }); // Clear any stuck sessions (implementation-specific) // This might require restarting the MCP server console.log('✅ Delegation system reset complete'); } ``` ##### 2. Reinstall Problematic Agents ```javascript async function reinstallAgent(agentName) { console.log(`🔄 Reinstalling agent: ${agentName}`); // Force reinstall const installation = await mcp.call('installAgents', { agents: [agentName], force: true }); if (installation.summary.successful > 0) { console.log(`✅ Agent ${agentName} reinstalled successfully`); // Test agent const testDelegation = await mcp.call('forceDelegation', { task: 'Simple test task', targetAgent: agentName, enforcementLevel: 'strict' }); console.log(`✅ Agent ${agentName} test delegation successful`); } else { console.error(`❌ Failed to reinstall ${agentName}:`, installation.failed); } } ``` ##### 3. Validate System Health ```javascript async function validateSystemHealth() { console.log('🏥 Validating delegation system health...'); // Check agent availability const agents = await mcp.call('listAgents', {}); console.log(`📋 Available agents: ${agents.totalCount}`); // Check metrics const metrics = await mcp.call('delegationMetrics', {}); console.log(`📊 Success rate: ${(metrics.summary.successRate * 100).toFixed(1)}%`); console.log(`🛡️ Bypass prevention: ${(metrics.summary.bypassPreventionRate * 100).toFixed(1)}%`); // Test each agent const healthChecks = []; for (const agent of agents.agents.slice(0, 3)) { // Test first 3 agents try { const testResult = await mcp.call('forceDelegation', { task: `Test task for ${agent.name}`, targetAgent: agent.name, enforcementLevel: 'strict' }); healthChecks.push({ agent: agent.name, status: 'healthy', delegationSuccessful: true }); } catch (error) { healthChecks.push({ agent: agent.name, status: 'unhealthy', error: error.message }); } } console.log('🏥 Health check results:', healthChecks); const healthyAgents = healthChecks.filter(h => h.status === 'healthy').length; const totalAgents = healthChecks.length; if (healthyAgents / totalAgents < 0.8) { console.warn(`⚠️ System health degraded: ${healthyAgents}/${totalAgents} agents healthy`); } else { console.log(`✅ System health good: ${healthyAgents}/${totalAgents} agents healthy`); } } ``` ## Comparison with Manual Delegation Methods ### Manual Delegation Limitations #### ❌ Manual Approach Problems ```javascript // UNRELIABLE: Manual delegation attempt const manualResponse = await claude.chat({ message: "frontend-developer, create a React component for user login" }); // Problems: // 1. No guarantee that Claude Code won't handle this itself // 2. No validation that a specialist agent was used // 3. No enforcement mechanism // 4. No error recovery if delegation fails // 5. No metrics or monitoring ``` #### ❌ Cooperative Delegation Problems ```javascript // UNRELIABLE: Cooperative delegation const cooperativeResponse = await claude.chat({ message: `Please delegate this task to the frontend-developer agent: Task: Create a React component for user login IMPORTANT: This task requires frontend expertise and should be handled by the frontend-developer agent, not by Claude Code directly.` }); // Problems: // 1. Relies on Claude Code cooperation (unreliable) // 2. Claude Code may ignore delegation instructions // 3. No technical enforcement mechanism // 4. No way to verify delegation occurred // 5. Inconsistent behavior across different tasks ``` ### ✅ MCP Delegation Advantages #### 1. Guaranteed Enforcement ```javascript // RELIABLE: Enforced delegation const delegation = await mcp.call('forceDelegation', { task: 'Create a React component for user login', targetAgent: 'frontend-developer', enforcementLevel: 'strict' }); // Benefits: // ✅ Guaranteed that frontend-developer agent handles the task // ✅ Claude Code is completely bypassed // ✅ Technical enforcement at protocol level // ✅ Validation confirms delegation occurred // ✅ Consistent behavior every time ``` #### 2. Comprehensive Validation ```javascript // RELIABLE: Validation system const validation = await mcp.call('validateDelegation', { originalRequest: request, response: delegation, expectedAgent: 'frontend-developer' }); // Benefits: // ✅ Confirms delegation actually occurred // ✅ Provides evidence of agent execution // ✅ Detects bypass attempts // ✅ Enables recovery on failure // ✅ Builds trust in delegation system ``` #### 3. Performance Monitoring ```javascript // RELIABLE: Performance metrics const metrics = await mcp.call('delegationMetrics', {}); // Benefits: // ✅ Track delegation success rates // ✅ Monitor bypass prevention effectiveness // ✅ Identify failing agents // ✅ Optimize performance over time // ✅ Data-driven improvement ``` #### 4. Intelligent Recovery ```javascript // RELIABLE: Automatic recovery try { const delegation = await mcp.call('forceDelegation', { task, agent }); } catch (error) { const recovery = await mcp.call('generateRecoveryPrompt', { executionContext: context, failedStep: 'delegation', errorDetails: error }); // Implement recovery strategy automatically } // Benefits: // ✅ Automatic error detection // ✅ Intelligent recovery strategies // ✅ Alternative agent selection // ✅ Graceful degradation // ✅ Higher overall reliability ``` ### Migration Strategy #### Phase 1: Assessment ```javascript // Identify current manual delegation patterns const manualPatterns = [ 'frontend-developer, implement...', 'backend-architect, design...', 'devops-engineer, deploy...' ]; // Map to MCP delegation calls const mcpMigrations = manualPatterns.map(pattern => { const [agent, task] = pattern.split(', '); return { original: pattern, mcp: `mcp.call('forceDelegation', { task: '${task}', targetAgent: '${agent}' })` }; }); ``` #### Phase 2: Gradual Migration ```javascript // Start with advisory mode for low-risk tasks async function migrateGradually(task, agent) { // Try MCP delegation first try { const delegation = await mcp.call('forceDelegation', { task, targetAgent: agent, enforcementLevel: 'advisory' // Start with advisory }); return delegation; } catch (error) { // Fallback to manual for now console.warn('MCP delegation failed, falling back to manual'); return await manualDelegation(task, agent); } } ``` #### Phase 3: Full Migration ```javascript // Move to strict enforcement for all specialist tasks async function fullMCPDelegation(task, agent) { const delegation = await mcp.call('forceDelegation', { task, targetAgent: agent, enforcementLevel: 'strict', bypassProtection: true }); // Always validate const validation = await mcp.call('validateDelegation', { originalRequest: { task, targetAgent: agent }, response: delegation, expectedAgent: agent }); if (!validation.delegationOccurred) { throw new Error('Delegation validation failed - manual intervention required'); } return delegation; } ``` ## Advanced Delegation Patterns ### 1. Multi-Agent Workflows with Delegation ```javascript async function executeMultiAgentWorkflow(complexTask) { // Generate workflow with delegation enforcement const workflow = await mcp.call('generateMultiAgentWorkflowEnhanced', { task: complexTask, complexity: 'high' }); const results = []; // Execute each step with delegation enforcement for (const step of workflow.workflowSteps) { console.log(`🔄 Executing step ${step.stepNumber}: ${step.task}`); const delegation = await mcp.call('forceDelegation', { task: step.task, targetAgent: step.agent, enforcementLevel: 'strict', context: { stepNumber: step.stepNumber, totalSteps: workflow.totalSteps, dependencies: step.dependencies } }); // Validate each step const validation = await mcp.call('validateDelegation', { originalRequest: { task: step.task, targetAgent: step.agent }, response: delegation, expectedAgent: step.agent }); if (!validation.delegationOccurred) { throw new Error(`Step ${step.stepNumber} delegation failed`); } results.push({ step: step.stepNumber, agent: step.agent, result: delegation, validated: true }); console.log(`✅ Step ${step.stepNumber} completed successfully`); } return { workflowCompleted: true, totalSteps: workflow.totalSteps, results }; } ``` ### 2. Conditional Delegation Based on Context ```javascript async function smartDelegation(task, context) { // Analyze task complexity and context const analysis = await mcp.call('analyzeProjectState', { includeFileStructure: true, includeDependencies: true }); // Determine if delegation is necessary let enforcementLevel = 'advisory'; if (analysis.project.type === 'enterprise' || analysis.recommendations.some(r => r.priority === 'high')) { enforcementLevel = 'strict'; } else if (context.complexity === 'high') { enforcementLevel = 'moderate'; } // Generate appropriate prompt const prompt = await mcp.call('generateAgentPromptEnhanced', { agentName: 'any', // Let system choose task, context: { ...context, projectContext: analysis.project, recommendations: analysis.recommendations } }); // Execute with determined enforcement level const delegation = await mcp.call('forceDelegation', { task, targetAgent: prompt.agentName, enforcementLevel, context: prompt.context }); return delegation; } ``` ### 3. Delegation with Fallback Chains ```javascript async function delegationWithFallback(task, primaryAgent, fallbackAgents = []) { const attemptOrder = [primaryAgent, ...fallbackAgents]; for (let i = 0; i < attemptOrder.length; i++) { const agent = attemptOrder[i]; const isLastAttempt = i === attemptOrder.length - 1; try { console.log(`🎯 Attempting delegation to ${agent} (attempt ${i + 1})`); const delegation = await mcp.call('forceDelegation', { task, targetAgent: agent, enforcementLevel: 'strict' }); const validation = await mcp.call('validateDelegation', { originalRequest: { task, targetAgent: agent }, response: delegation, expectedAgent: agent }); if (validation.delegationOccurred) { console.log(`✅ Delegation successful with ${agent}`); return delegation; } else { throw new Error('Validation failed'); } } catch (error) { console.warn(`⚠️ Delegation to ${agent} failed: ${error.message}`); if (isLastAttempt) { throw new Error(`All delegation attempts failed. Last error: ${error.message}`); } // Generate recovery for next attempt const recovery = await mcp.call('generateRecoveryPrompt', { executionContext: { task, selectedAgent: agent, retryCount: i }, failedStep: 'delegation', errorDetails: { message: error.message, code: 'DELEGATION_FAILED' }, recoveryOptions: ['alternative'] }); console.log(`🔄 Recovery strategy: ${recovery.recoveryStrategy}`); } } } ``` ## Conclusion The Claude Code Subagents Orchestrator MCP server fundamentally transforms delegation from a cooperative suggestion into an enforced system requirement. By implementing protocol-level interception, process isolation, and comprehensive validation, it ensures that specialist tasks are always handled by appropriate specialist agents rather than generic Claude Code execution. Key benefits include: 1. **Guaranteed Delegation**: Technical enforcement prevents Claude Code bypass 2. **Validation System**: Multi-layer confirmation ensures delegation occurred 3. **Performance Monitoring**: Metrics and analytics for continuous improvement 4. **Intelligent Recovery**: Automatic fallback and error handling 5. **Consistent Behavior**: Reliable delegation across all task types This approach provides a robust foundation for building complex multi-agent workflows with confidence in proper task delegation and specialist engagement.