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.

308 lines (264 loc) 9.73 kB
import { ImprovePromptInputSchema, FunctionOutput, WorkflowContext, } from '../shared/types.js'; import { extractKeyInfo, logWorkflowProgress } from '../shared/utils.js'; /** * Improve Prompt Function * * This function analyzes and enhances user prompts for better clarity, * specificity, and actionability. It identifies key requirements, * suggests improvements, and prepares the prompt for the research phase. */ export function createImprovePromptFunction() { return async (input: any, context: WorkflowContext): Promise<FunctionOutput> => { try { // Validate input const validatedInput = ImprovePromptInputSchema.parse(input); const { userPrompt } = validatedInput; logWorkflowProgress(context, 'improve-prompt', 'Starting prompt analysis and improvement'); // Analyze the original prompt const analysis = analyzePrompt(userPrompt); // Generate improved prompt const improvedPrompt = generateImprovedPrompt(userPrompt, analysis); // Extract research topics const researchTopics = extractResearchTopics(userPrompt, analysis); // Identify requirements and constraints const keyInfo = extractKeyInfo(userPrompt); const result = { originalPrompt: userPrompt, improvedPrompt, analysis, researchTopics, requirements: keyInfo.requirements, constraints: keyInfo.constraints, goals: keyInfo.goals, improvementSuggestions: generateImprovementSuggestions(analysis), clarity: analysis.clarityScore, specificity: analysis.specificityScore, actionability: analysis.actionabilityScore, }; logWorkflowProgress(context, 'improve-prompt', 'Prompt improvement completed successfully'); return { success: true, result, nextStep: 'research', context, metadata: { improvementScore: calculateImprovementScore(analysis), processingTime: Date.now(), }, }; } catch (error) { return { success: false, result: { error: error.message, step: 'improve-prompt', }, context, }; } }; } /** * Analyze the prompt for various quality metrics */ function analyzePrompt(prompt: string): { clarityScore: number; specificityScore: number; actionabilityScore: number; wordCount: number; hasContext: boolean; hasConstraints: boolean; hasGoals: boolean; complexity: 'low' | 'medium' | 'high'; issues: string[]; strengths: string[]; } { const wordCount = prompt.split(/\s+/).length; const issues: string[] = []; const strengths: string[] = []; // Clarity analysis let clarityScore = 5; // Base score if (prompt.includes('?')) clarityScore += 1; if (prompt.length < 20) { clarityScore -= 2; issues.push('Prompt is too short and may lack detail'); } if (prompt.length > 500) { clarityScore -= 1; issues.push('Prompt is very long and may be unclear'); } if (wordCount > 10) strengths.push('Adequate length for context'); // Specificity analysis let specificityScore = 5; // Base score const specificWords = ['specific', 'exactly', 'precisely', 'detailed', 'particular']; const hasSpecificWords = specificWords.some(word => prompt.toLowerCase().includes(word) ); if (hasSpecificWords) { specificityScore += 2; strengths.push('Contains specific language'); } const vagueWords = ['something', 'anything', 'maybe', 'perhaps', 'kind of']; const hasVagueWords = vagueWords.some(word => prompt.toLowerCase().includes(word) ); if (hasVagueWords) { specificityScore -= 2; issues.push('Contains vague language'); } // Actionability analysis let actionabilityScore = 5; // Base score const actionWords = ['create', 'build', 'implement', 'develop', 'design', 'write', 'generate']; const hasActionWords = actionWords.some(word => prompt.toLowerCase().includes(word) ); if (hasActionWords) { actionabilityScore += 2; strengths.push('Contains clear action words'); } // Context analysis const hasContext = prompt.toLowerCase().includes('context') || prompt.toLowerCase().includes('background') || prompt.includes('for') || prompt.includes('because'); if (hasContext) strengths.push('Provides context'); // Constraints analysis const hasConstraints = prompt.toLowerCase().includes('must') || prompt.toLowerCase().includes('should') || prompt.toLowerCase().includes('cannot') || prompt.toLowerCase().includes('requirement'); if (hasConstraints) strengths.push('Includes constraints or requirements'); // Goals analysis const hasGoals = prompt.toLowerCase().includes('goal') || prompt.toLowerCase().includes('objective') || prompt.toLowerCase().includes('want') || prompt.toLowerCase().includes('need'); if (hasGoals) strengths.push('Expresses clear goals'); // Complexity assessment let complexity: 'low' | 'medium' | 'high' = 'medium'; if (wordCount < 15) complexity = 'low'; if (wordCount > 50) complexity = 'high'; // Normalize scores clarityScore = Math.max(1, Math.min(10, clarityScore)); specificityScore = Math.max(1, Math.min(10, specificityScore)); actionabilityScore = Math.max(1, Math.min(10, actionabilityScore)); return { clarityScore, specificityScore, actionabilityScore, wordCount, hasContext, hasConstraints, hasGoals, complexity, issues, strengths, }; } /** * Generate an improved version of the prompt */ function generateImprovedPrompt(originalPrompt: string, analysis: any): string { let improved = originalPrompt; // Add context if missing if (!analysis.hasContext && analysis.clarityScore < 7) { improved = `Context: Please help me with the following request.\n\n${improved}`; } // Add specificity if missing if (analysis.specificityScore < 6) { improved += '\n\nPlease provide specific, detailed guidance with concrete examples where applicable.'; } // Add actionability if missing if (analysis.actionabilityScore < 6) { improved += '\n\nPlease include clear, actionable steps that I can follow to achieve this goal.'; } // Add structure for complex prompts if (analysis.complexity === 'high' && analysis.clarityScore < 7) { const sections = improved.split('\n\n'); if (sections.length === 1) { improved = `Objective: ${improved}\n\nRequirements: Please ensure the solution meets all specified requirements.\n\nDeliverables: Please provide clear deliverables and next steps.`; } } return improved; } /** * Extract research topics from the prompt */ function extractResearchTopics(prompt: string, analysis: any): string[] { const topics: string[] = []; const words = prompt.toLowerCase().split(/\s+/); // Technology-related keywords const techKeywords = [ 'typescript', 'javascript', 'python', 'react', 'node', 'api', 'database', 'mcp', 'server', 'client', 'framework', 'library', 'package', 'npm', 'testing', 'deployment', 'docker', 'kubernetes', 'aws', 'cloud' ]; // Domain-specific keywords const domainKeywords = [ 'ai', 'machine learning', 'data', 'analytics', 'web development', 'mobile', 'backend', 'frontend', 'devops', 'security', 'performance' ]; // Extract technology topics for (const keyword of techKeywords) { if (words.includes(keyword)) { topics.push(`${keyword} best practices`); topics.push(`${keyword} documentation`); } } // Extract domain topics for (const keyword of domainKeywords) { if (words.includes(keyword)) { topics.push(`${keyword} current trends`); } } // Add general research topics based on prompt content if (prompt.toLowerCase().includes('build') || prompt.toLowerCase().includes('create')) { topics.push('development methodologies'); topics.push('project structure best practices'); } if (prompt.toLowerCase().includes('test')) { topics.push('testing frameworks'); topics.push('test automation'); } // Ensure we have at least some research topics if (topics.length === 0) { topics.push('general best practices'); topics.push('current industry standards'); } return [...new Set(topics)]; // Remove duplicates } /** * Generate improvement suggestions */ function generateImprovementSuggestions(analysis: any): string[] { const suggestions: string[] = []; if (analysis.clarityScore < 7) { suggestions.push('Consider adding more context about your specific use case'); suggestions.push('Break down complex requests into smaller, clearer parts'); } if (analysis.specificityScore < 6) { suggestions.push('Be more specific about your requirements and constraints'); suggestions.push('Include examples of what you want to achieve'); } if (analysis.actionabilityScore < 6) { suggestions.push('Specify what type of deliverable you expect'); suggestions.push('Mention any preferred technologies or approaches'); } if (analysis.wordCount < 10) { suggestions.push('Provide more detail about your goals and requirements'); } if (!analysis.hasConstraints) { suggestions.push('Consider mentioning any constraints or limitations'); } return suggestions; } /** * Calculate overall improvement score */ function calculateImprovementScore(analysis: any): number { const avgScore = (analysis.clarityScore + analysis.specificityScore + analysis.actionabilityScore) / 3; return Math.round(avgScore * 10) / 10; }