UNPKG

mcp-workflow-server-enhanced

Version:

Enhanced MCP Workflow Server with smart problem routing, comprehensive validation, guide compliance, and robust error handling. Intelligently routes to appropriate AI functions based on problem type.

536 lines (481 loc) 15.5 kB
import { PlannerInputSchema, FunctionOutput, WorkflowContext, } from '../shared/types.js'; import { logWorkflowProgress } from '../shared/utils.js'; /** * Planner Function * * This function creates detailed implementation plans based on cognitive analysis results. * It breaks down the project into phases, tasks, and deliverables with clear dependencies, * timelines, and resource requirements. */ export function createPlannerFunction() { return async (input: any, context: WorkflowContext): Promise<FunctionOutput> => { try { // Validate input const validatedInput = PlannerInputSchema.parse(input); const { cognitiveAnalysis, requirements, constraints } = validatedInput; logWorkflowProgress(context, 'planner', 'Starting detailed planning phase'); // Create comprehensive implementation plan const plan = await createImplementationPlan(cognitiveAnalysis, requirements, constraints); // Generate project timeline const timeline = generateProjectTimeline(plan); // Identify dependencies const dependencies = identifyDependencies(plan); // Assess resource requirements const resources = assessResourceRequirements(plan, cognitiveAnalysis); // Create risk mitigation plan const riskMitigation = createRiskMitigationPlan(cognitiveAnalysis, plan); const result = { implementationPlan: plan, timeline, dependencies, resourceRequirements: resources, riskMitigation, successCriteria: defineSuccessCriteria(requirements, cognitiveAnalysis), qualityGates: defineQualityGates(plan), deliverables: identifyDeliverables(plan), milestones: defineMilestones(plan, timeline), contingencyPlans: createContingencyPlans(plan, cognitiveAnalysis), }; logWorkflowProgress(context, 'planner', 'Planning phase completed successfully'); return { success: true, result, nextStep: 'task-generation', context, metadata: { planComplexity: plan.phases.length, totalTasks: plan.phases.reduce((sum, phase) => sum + phase.tasks.length, 0), estimatedDuration: timeline.totalDuration, processingTime: Date.now(), }, }; } catch (error) { return { success: false, result: { error: error.message, step: 'planner', }, context, }; } }; } /** * Create comprehensive implementation plan */ async function createImplementationPlan( cognitiveAnalysis: any, requirements: string[], constraints: string[] ): Promise<{ overview: string; approach: string; phases: Array<{ name: string; description: string; duration: string; tasks: Array<{ name: string; description: string; priority: 'high' | 'medium' | 'low'; effort: string; dependencies: string[]; deliverables: string[]; }>; }>; }> { const complexity = cognitiveAnalysis?.complexityAssessment?.overallComplexity || 5; const intent = cognitiveAnalysis?.promptAnalysis?.intent || 'general'; // Determine approach based on complexity and intent let approach = 'Iterative development with continuous integration'; if (complexity > 7) { approach = 'Phased approach with detailed planning and risk management'; } else if (complexity < 4) { approach = 'Agile development with rapid prototyping'; } const overview = `Implementation plan for ${intent} project with ${complexity}/10 complexity. ` + `Following ${approach.toLowerCase()} methodology.`; // Create phases based on project type and complexity const phases = createProjectPhases(intent, complexity, requirements, constraints); return { overview, approach, phases, }; } /** * Create project phases based on intent and complexity */ function createProjectPhases( intent: string, complexity: number, requirements: string[], constraints: string[] ): Array<any> { const phases = []; // Phase 1: Setup and Foundation phases.push({ name: 'Setup and Foundation', description: 'Establish project structure, dependencies, and core infrastructure', duration: complexity > 6 ? '3-5 days' : '1-2 days', tasks: [ { name: 'Project Initialization', description: 'Set up project structure, package.json, and build configuration', priority: 'high' as const, effort: '4-6 hours', dependencies: [], deliverables: ['Project structure', 'Build configuration', 'Package.json'], }, { name: 'Dependency Setup', description: 'Install and configure required dependencies and tools', priority: 'high' as const, effort: '2-3 hours', dependencies: ['Project Initialization'], deliverables: ['Configured dependencies', 'Development tools setup'], }, { name: 'Core Infrastructure', description: 'Implement basic infrastructure and shared utilities', priority: 'high' as const, effort: '6-8 hours', dependencies: ['Dependency Setup'], deliverables: ['Core utilities', 'Shared interfaces', 'Base configuration'], }, ], }); // Phase 2: Core Implementation phases.push({ name: 'Core Implementation', description: 'Implement main functionality and core features', duration: complexity > 6 ? '1-2 weeks' : '3-5 days', tasks: [ { name: 'Core Feature Development', description: 'Implement primary functionality as specified in requirements', priority: 'high' as const, effort: complexity > 6 ? '2-3 days' : '1-2 days', dependencies: ['Core Infrastructure'], deliverables: ['Core features', 'Main functionality'], }, { name: 'Integration Layer', description: 'Implement integration points and external connections', priority: 'medium' as const, effort: '1-2 days', dependencies: ['Core Feature Development'], deliverables: ['Integration interfaces', 'External connections'], }, { name: 'Error Handling', description: 'Implement comprehensive error handling and validation', priority: 'high' as const, effort: '4-6 hours', dependencies: ['Core Feature Development'], deliverables: ['Error handling system', 'Input validation'], }, ], }); // Phase 3: Testing and Quality Assurance phases.push({ name: 'Testing and Quality Assurance', description: 'Comprehensive testing and quality validation', duration: complexity > 6 ? '5-7 days' : '2-3 days', tasks: [ { name: 'Unit Testing', description: 'Implement comprehensive unit tests for all components', priority: 'high' as const, effort: '1-2 days', dependencies: ['Core Feature Development'], deliverables: ['Unit test suite', 'Test coverage report'], }, { name: 'Integration Testing', description: 'Test integration points and end-to-end workflows', priority: 'high' as const, effort: '1 day', dependencies: ['Integration Layer', 'Unit Testing'], deliverables: ['Integration tests', 'Workflow validation'], }, { name: 'Quality Validation', description: 'Code quality checks, linting, and performance validation', priority: 'medium' as const, effort: '4-6 hours', dependencies: ['Unit Testing'], deliverables: ['Quality reports', 'Performance metrics'], }, ], }); // Phase 4: Documentation and Deployment phases.push({ name: 'Documentation and Deployment', description: 'Create documentation and prepare for deployment', duration: '2-3 days', tasks: [ { name: 'Documentation', description: 'Create comprehensive documentation and usage guides', priority: 'medium' as const, effort: '1 day', dependencies: ['Quality Validation'], deliverables: ['README', 'API documentation', 'Usage examples'], }, { name: 'Deployment Preparation', description: 'Prepare for deployment and distribution', priority: 'medium' as const, effort: '4-6 hours', dependencies: ['Documentation'], deliverables: ['Build artifacts', 'Deployment configuration'], }, { name: 'Final Validation', description: 'Final testing and validation before release', priority: 'high' as const, effort: '2-4 hours', dependencies: ['Deployment Preparation'], deliverables: ['Validation report', 'Release readiness'], }, ], }); return phases; } /** * Generate project timeline */ function generateProjectTimeline(plan: any): { totalDuration: string; phases: Array<{ name: string; startDay: number; duration: string; endDay: number; }>; criticalPath: string[]; } { let currentDay = 1; const phaseTimeline = []; const criticalPath = []; for (const phase of plan.phases) { const durationDays = parseDuration(phase.duration); phaseTimeline.push({ name: phase.name, startDay: currentDay, duration: phase.duration, endDay: currentDay + durationDays - 1, }); // Add to critical path if high priority tasks exist const hasHighPriorityTasks = phase.tasks.some(task => task.priority === 'high'); if (hasHighPriorityTasks) { criticalPath.push(phase.name); } currentDay += durationDays; } const totalDays = currentDay - 1; const totalDuration = totalDays > 7 ? `${Math.ceil(totalDays / 7)} weeks` : `${totalDays} days`; return { totalDuration, phases: phaseTimeline, criticalPath, }; } /** * Parse duration string to days */ function parseDuration(duration: string): number { if (duration.includes('week')) { const weeks = parseInt(duration.match(/(\d+)/)?.[1] || '1'); return weeks * 7; } return parseInt(duration.match(/(\d+)/)?.[1] || '1'); } /** * Identify dependencies between tasks and phases */ function identifyDependencies(plan: any): { taskDependencies: Array<{ task: string; dependsOn: string[] }>; phaseDependencies: Array<{ phase: string; dependsOn: string[] }>; criticalDependencies: string[]; } { const taskDependencies = []; const phaseDependencies = []; const criticalDependencies = []; // Analyze task dependencies for (const phase of plan.phases) { for (const task of phase.tasks) { if (task.dependencies.length > 0) { taskDependencies.push({ task: task.name, dependsOn: task.dependencies, }); if (task.priority === 'high') { criticalDependencies.push(...task.dependencies); } } } } // Analyze phase dependencies for (let i = 1; i < plan.phases.length; i++) { phaseDependencies.push({ phase: plan.phases[i].name, dependsOn: [plan.phases[i - 1].name], }); } return { taskDependencies, phaseDependencies, criticalDependencies: [...new Set(criticalDependencies)], }; } /** * Assess resource requirements */ function assessResourceRequirements(plan: any, cognitiveAnalysis: any): { humanResources: string[]; technicalResources: string[]; timeEstimate: string; skillsRequired: string[]; } { const complexity = cognitiveAnalysis?.complexityAssessment?.overallComplexity || 5; const humanResources = ['1 Developer']; if (complexity > 7) { humanResources.push('1 Technical Lead', 'QA Engineer (part-time)'); } const technicalResources = [ 'Development environment', 'Version control system', 'CI/CD pipeline', 'Testing framework', ]; const totalTasks = plan.phases.reduce((sum, phase) => sum + phase.tasks.length, 0); const timeEstimate = `${Math.ceil(totalTasks * 0.5)} to ${Math.ceil(totalTasks * 0.8)} days`; const skillsRequired = [ 'TypeScript/JavaScript development', 'Testing and quality assurance', 'Version control (Git)', ]; if (cognitiveAnalysis?.promptAnalysis?.domain?.includes('software-development')) { skillsRequired.push('Software architecture', 'API design'); } return { humanResources, technicalResources, timeEstimate, skillsRequired, }; } /** * Create risk mitigation plan */ function createRiskMitigationPlan(cognitiveAnalysis: any, plan: any): Array<{ risk: string; probability: 'low' | 'medium' | 'high'; impact: 'low' | 'medium' | 'high'; mitigation: string; }> { const risks = []; const complexity = cognitiveAnalysis?.complexityAssessment?.overallComplexity || 5; if (complexity > 7) { risks.push({ risk: 'High complexity leading to scope creep', probability: 'medium' as const, impact: 'high' as const, mitigation: 'Strict scope management and regular reviews', }); } risks.push({ risk: 'Technical dependencies causing delays', probability: 'medium' as const, impact: 'medium' as const, mitigation: 'Early dependency resolution and fallback options', }); risks.push({ risk: 'Quality issues in final deliverable', probability: 'low' as const, impact: 'high' as const, mitigation: 'Comprehensive testing and quality gates', }); return risks; } /** * Define success criteria */ function defineSuccessCriteria(requirements: string[], cognitiveAnalysis: any): string[] { const criteria = [ 'All functional requirements implemented', 'Code quality standards met', 'Comprehensive test coverage achieved', 'Documentation completed', ]; if (requirements.length > 0) { criteria.push('All specified requirements satisfied'); } return criteria; } /** * Define quality gates */ function defineQualityGates(plan: any): Array<{ phase: string; criteria: string[] }> { return plan.phases.map(phase => ({ phase: phase.name, criteria: [ 'All tasks completed', 'Quality standards met', 'Deliverables validated', 'Dependencies resolved', ], })); } /** * Identify deliverables */ function identifyDeliverables(plan: any): string[] { const deliverables = new Set<string>(); for (const phase of plan.phases) { for (const task of phase.tasks) { task.deliverables.forEach(deliverable => deliverables.add(deliverable)); } } return Array.from(deliverables); } /** * Define milestones */ function defineMilestones(plan: any, timeline: any): Array<{ name: string; date: string; criteria: string[] }> { return timeline.phases.map(phase => ({ name: `${phase.name} Complete`, date: `Day ${phase.endDay}`, criteria: [ 'All phase tasks completed', 'Quality gates passed', 'Deliverables approved', ], })); } /** * Create contingency plans */ function createContingencyPlans(plan: any, cognitiveAnalysis: any): Array<{ scenario: string; response: string }> { return [ { scenario: 'Critical dependency unavailable', response: 'Implement alternative solution or temporary workaround', }, { scenario: 'Timeline delays in critical path', response: 'Reallocate resources and adjust scope if necessary', }, { scenario: 'Quality issues discovered late', response: 'Implement additional testing phase and code review', }, ]; }