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.

233 lines (210 loc) 7.35 kB
import { z } from 'zod'; // Guide compliance validation schemas export const GuideComplianceSchema = z.object({ maximsApplied: z.array(z.enum([ 'PrimedCognition', 'AppropriateComplexity', 'FullyUnleashedPotential', 'ClearCommunication', 'PurposefulToolLeveraging', 'ToolAssistedDiagnosis', 'Autonomy', 'PurityAndCleanliness', 'Perceptivity', 'Impenetrability', 'Resilience', 'Consistency', 'OperationalFlexibility' ])).min(1, 'At least one maxim must be applied'), heuristicsApplied: z.array(z.enum([ 'SOLID', 'SMART', 'Responsive UI' ])).optional(), complianceScore: z.number().min(0).max(100), validationCheckpoints: z.array(z.object({ checkpoint: z.string(), passed: z.boolean(), details: z.string().optional(), })), }); export type GuideCompliance = z.infer<typeof GuideComplianceSchema>; // Enhanced validation metadata export const ValidationMetadataSchema = z.object({ inputValidated: z.boolean(), schemaVersion: z.string(), validationTimestamp: z.string(), validationErrors: z.array(z.string()).optional(), guideCompliance: GuideComplianceSchema.optional(), }); export type ValidationMetadata = z.infer<typeof ValidationMetadataSchema>; // Base workflow context that gets passed between functions export const WorkflowContextSchema = z.object({ sessionId: z.string(), originalPrompt: z.string(), currentStep: z.enum([ 'improve-prompt', 'research', 'cognitive', 'planner', 'task-generation', 'implementation', 'problem-solver' ]), stepResults: z.record(z.any()).optional(), metadata: z.record(z.any()).optional(), timestamp: z.string(), validationMetadata: ValidationMetadataSchema.optional(), guideCompliance: GuideComplianceSchema.optional(), }); export type WorkflowContext = z.infer<typeof WorkflowContextSchema>; // Enhanced input validation with guide compliance const createEnhancedInputSchema = <T extends z.ZodRawShape>(baseSchema: z.ZodObject<T>) => { return baseSchema.extend({ validationMetadata: ValidationMetadataSchema.optional(), guideCompliance: GuideComplianceSchema.optional(), }).refine((data) => { // Validate that required maxims are applied based on function type return true; // Placeholder for complex validation logic }, { message: "Guide compliance validation failed" }); }; // Individual function schemas export const ImprovePromptInputSchema = z.object({ userPrompt: z.string() .min(1, 'User prompt cannot be empty') .max(10000, 'User prompt too long') .describe('The original user prompt to improve'), context: WorkflowContextSchema.optional(), }); export const ResearchInputSchema = z.object({ improvedPrompt: z.string() .min(1, 'Improved prompt cannot be empty') .describe('The improved prompt from previous step'), researchTopics: z.array(z.string()) .min(1, 'At least one research topic required') .describe('Specific topics to research'), codeAnalysis: z.boolean().default(false).describe('Whether to analyze code structures'), context: WorkflowContextSchema.optional(), }); export const CognitiveInputSchema = z.object({ researchData: z.any() .refine((data) => data !== null && data !== undefined, 'Research data is required') .describe('Research results from previous step'), improvedPrompt: z.string() .min(1, 'Improved prompt cannot be empty') .describe('The improved prompt'), analysisDepth: z.enum(['surface', 'deep', 'comprehensive']).default('deep'), context: WorkflowContextSchema.optional(), }); export const PlannerInputSchema = z.object({ cognitiveAnalysis: z.any() .refine((data) => data !== null && data !== undefined, 'Cognitive analysis is required') .describe('Cognitive analysis results'), requirements: z.array(z.string()) .min(1, 'At least one requirement must be identified') .describe('Identified requirements'), constraints: z.array(z.string()).optional().describe('Any constraints to consider'), context: WorkflowContextSchema.optional(), }); export const TaskGenerationInputSchema = z.object({ plan: z.any() .refine((data) => data !== null && data !== undefined, 'Planning results are required') .describe('The detailed plan from planner'), granularity: z.enum(['high', 'medium', 'fine']).default('medium'), context: WorkflowContextSchema.optional(), }); export const ImplementationInputSchema = z.object({ tasks: z.array(z.any()) .min(1, 'At least one task must be provided for implementation') .describe('Generated tasks to implement'), currentTaskIndex: z.number() .min(0, 'Task index cannot be negative') .default(0) .describe('Current task being implemented'), context: WorkflowContextSchema.optional(), }); export const ProblemSolverInputSchema = z.object({ error: z.string() .min(1, 'Error description cannot be empty') .describe('The error or problem encountered'), context: z.any() .refine((data) => data !== null && data !== undefined, 'Problem context is required') .describe('Context where the problem occurred'), previousAttempts: z.array(z.string()).optional().describe('Previous solution attempts'), strictMode: z.boolean().default(true).describe('Whether to solve without skipping/removing code'), workflowContext: WorkflowContextSchema.optional(), }); // Output schemas export const FunctionOutputSchema = z.object({ success: z.boolean(), result: z.any(), nextStep: z.string().optional(), context: WorkflowContextSchema.optional(), metadata: z.record(z.any()).optional(), }); export type FunctionOutput = z.infer<typeof FunctionOutputSchema>; // Workflow orchestration types export const WorkflowConfigSchema = z.object({ enabledFunctions: z.array(z.string()).default([ 'improve-prompt', 'research', 'cognitive', 'planner', 'task-generation', 'implementation' ]), autoAdvance: z.boolean().default(true), errorHandling: z.enum(['stop', 'retry', 'skip']).default('retry'), maxRetries: z.number().default(3), }); export type WorkflowConfig = z.infer<typeof WorkflowConfigSchema>; // Enhanced error types with recovery mechanisms export class WorkflowError extends Error { constructor( message: string, public step: string, public context?: WorkflowContext, public originalError?: Error, public recoverable: boolean = true, public recoveryStrategy?: string ) { super(message); this.name = 'WorkflowError'; } } export class ValidationError extends Error { constructor( message: string, public validationErrors: z.ZodError | string[], public step?: string, public recoverable: boolean = true ) { super(message); this.name = 'ValidationError'; } } export class DomainError extends Error { constructor( message: string, public domain: string, public errorType: 'detection' | 'analysis' | 'implementation', public recoverable: boolean = true ) { super(message); this.name = 'DomainError'; } } export class GuideComplianceError extends Error { constructor( message: string, public step: string, public complianceScore: number, public failedMaxims: string[], public recoverable: boolean = true ) { super(message); this.name = 'GuideComplianceError'; } }