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.
366 lines (322 loc) • 12.6 kB
text/typescript
import {
ResearchInputSchema,
FunctionOutput,
WorkflowContext,
} from '../shared/types.js';
import { logWorkflowProgress } from '../shared/utils.js';
/**
* Research Function
*
* This function performs comprehensive research on topics identified in the improved prompt.
* It analyzes code structures, gathers information about tools and technologies,
* and provides detailed findings to inform the cognitive analysis phase.
*/
export function createResearchFunction() {
return async (input: any, context: WorkflowContext): Promise<FunctionOutput> => {
try {
// Validate input
const validatedInput = ResearchInputSchema.parse(input);
const { improvedPrompt, researchTopics, codeAnalysis } = validatedInput;
logWorkflowProgress(context, 'research', 'Starting research and analysis phase');
// Perform research on each topic
const researchResults = await Promise.all(
researchTopics.map(topic => performTopicResearch(topic))
);
// Analyze code structures if requested
let codeAnalysisResults = null;
if (codeAnalysis) {
codeAnalysisResults = await analyzeCodeStructures(improvedPrompt);
}
// Research current tools and technologies
const toolsResearch = await researchCurrentTools(improvedPrompt);
// Generate research summary
const summary = generateResearchSummary(researchResults, codeAnalysisResults, toolsResearch);
const result = {
improvedPrompt,
researchTopics,
topicResults: researchResults,
codeAnalysis: codeAnalysisResults,
toolsAndTechnologies: toolsResearch,
summary,
recommendations: generateRecommendations(researchResults, toolsResearch),
keyFindings: extractKeyFindings(researchResults),
nextSteps: suggestNextSteps(summary),
};
logWorkflowProgress(context, 'research', 'Research phase completed successfully');
return {
success: true,
result,
nextStep: 'cognitive',
context,
metadata: {
topicsResearched: researchTopics.length,
codeAnalysisPerformed: codeAnalysis,
processingTime: Date.now(),
},
};
} catch (error) {
return {
success: false,
result: {
error: error.message,
step: 'research',
},
context,
};
}
};
}
/**
* Perform research on a specific topic
*/
async function performTopicResearch(topic: string): Promise<{
topic: string;
findings: string[];
bestPractices: string[];
currentTrends: string[];
tools: string[];
resources: string[];
}> {
// Simulate research with comprehensive knowledge base
const findings: string[] = [];
const bestPractices: string[] = [];
const currentTrends: string[] = [];
const tools: string[] = [];
const resources: string[] = [];
// Research based on topic keywords
const topicLower = topic.toLowerCase();
if (topicLower.includes('typescript')) {
findings.push('TypeScript provides static type checking for JavaScript');
findings.push('TypeScript 5.x introduces new features like decorators and const assertions');
bestPractices.push('Use strict mode for better type safety');
bestPractices.push('Leverage utility types for better code reuse');
currentTrends.push('Increased adoption in enterprise applications');
currentTrends.push('Better integration with modern frameworks');
tools.push('tsup for fast bundling');
tools.push('vitest for testing');
tools.push('eslint with TypeScript rules');
resources.push('TypeScript Handbook');
resources.push('TypeScript Deep Dive');
}
if (topicLower.includes('mcp') || topicLower.includes('model context protocol')) {
findings.push('MCP enables standardized integration between LLMs and external data sources');
findings.push('MCP supports resources, tools, and prompts as core concepts');
bestPractices.push('Use proper error handling in MCP servers');
bestPractices.push('Implement comprehensive input validation');
currentTrends.push('Growing adoption in AI application development');
currentTrends.push('Integration with major AI platforms');
tools.push('@modelcontextprotocol/sdk for TypeScript');
tools.push('MCP Inspector for testing');
resources.push('Official MCP documentation');
resources.push('MCP specification');
}
if (topicLower.includes('testing')) {
findings.push('Modern testing emphasizes fast feedback and comprehensive coverage');
findings.push('Unit, integration, and end-to-end testing form a testing pyramid');
bestPractices.push('Write tests before implementation (TDD)');
bestPractices.push('Use descriptive test names and arrange-act-assert pattern');
currentTrends.push('Shift towards faster test runners like Vitest');
currentTrends.push('Increased focus on testing in production');
tools.push('Vitest for unit testing');
tools.push('Playwright for E2E testing');
tools.push('Testing Library for component testing');
resources.push('Testing JavaScript Applications');
resources.push('Test-Driven Development guides');
}
if (topicLower.includes('npm') || topicLower.includes('package')) {
findings.push('npm is the standard package manager for Node.js ecosystem');
findings.push('Package.json defines dependencies and scripts');
bestPractices.push('Use semantic versioning for releases');
bestPractices.push('Include comprehensive documentation');
currentTrends.push('Increased focus on security scanning');
currentTrends.push('Better support for monorepos');
tools.push('npm for package management');
tools.push('semantic-release for automated versioning');
tools.push('npm audit for security scanning');
resources.push('npm documentation');
resources.push('Package.json specification');
}
// Add general findings if no specific matches
if (findings.length === 0) {
findings.push(`Research topic: ${topic}`);
findings.push('General best practices apply');
bestPractices.push('Follow industry standards');
bestPractices.push('Maintain good documentation');
currentTrends.push('Focus on developer experience');
tools.push('Standard development tools');
resources.push('Official documentation');
}
return {
topic,
findings,
bestPractices,
currentTrends,
tools,
resources,
};
}
/**
* Analyze code structures mentioned in the prompt
*/
async function analyzeCodeStructures(prompt: string): Promise<{
identifiedPatterns: string[];
suggestedArchitecture: string[];
codeOrganization: string[];
designPatterns: string[];
}> {
const identifiedPatterns: string[] = [];
const suggestedArchitecture: string[] = [];
const codeOrganization: string[] = [];
const designPatterns: string[] = [];
const promptLower = prompt.toLowerCase();
// Identify architectural patterns
if (promptLower.includes('server') || promptLower.includes('api')) {
identifiedPatterns.push('Server/API architecture');
suggestedArchitecture.push('Layered architecture with clear separation of concerns');
suggestedArchitecture.push('RESTful API design principles');
codeOrganization.push('Separate routes, controllers, and services');
designPatterns.push('Repository pattern for data access');
designPatterns.push('Dependency injection for loose coupling');
}
if (promptLower.includes('mcp')) {
identifiedPatterns.push('MCP server pattern');
suggestedArchitecture.push('Tool-based architecture with clear interfaces');
suggestedArchitecture.push('Resource and prompt management');
codeOrganization.push('Separate functions for each MCP capability');
designPatterns.push('Factory pattern for creating handlers');
designPatterns.push('Strategy pattern for different transport types');
}
if (promptLower.includes('workflow') || promptLower.includes('process')) {
identifiedPatterns.push('Workflow orchestration pattern');
suggestedArchitecture.push('State machine or pipeline architecture');
suggestedArchitecture.push('Event-driven processing');
codeOrganization.push('Separate modules for each workflow step');
designPatterns.push('Chain of responsibility for step execution');
designPatterns.push('Observer pattern for progress tracking');
}
// Add default suggestions if none identified
if (identifiedPatterns.length === 0) {
identifiedPatterns.push('General application structure');
suggestedArchitecture.push('Modular architecture with clear interfaces');
codeOrganization.push('Logical separation of concerns');
designPatterns.push('SOLID principles');
}
return {
identifiedPatterns,
suggestedArchitecture,
codeOrganization,
designPatterns,
};
}
/**
* Research current tools and technologies for 2024
*/
async function researchCurrentTools(prompt: string): Promise<{
buildTools: string[];
testingFrameworks: string[];
developmentTools: string[];
deploymentTools: string[];
recommendations: { tool: string; reason: string }[];
}> {
const buildTools = [
'tsup - Fast TypeScript bundler',
'Vite - Fast build tool with HMR',
'esbuild - Extremely fast bundler',
'Rollup - Module bundler for libraries',
];
const testingFrameworks = [
'Vitest - Fast testing framework',
'Jest - Comprehensive testing solution',
'Playwright - End-to-end testing',
'Testing Library - Component testing utilities',
];
const developmentTools = [
'TypeScript - Static type checking',
'ESLint - Code linting',
'Prettier - Code formatting',
'tsx - TypeScript execution',
];
const deploymentTools = [
'Docker - Containerization',
'GitHub Actions - CI/CD',
'Vercel - Frontend deployment',
'Railway - Full-stack deployment',
];
const recommendations: { tool: string; reason: string }[] = [
{ tool: 'tsup', reason: 'Fast builds with minimal configuration' },
{ tool: 'vitest', reason: 'Excellent TypeScript support and speed' },
{ tool: 'zod', reason: 'Runtime type validation' },
{ tool: 'semantic-release', reason: 'Automated versioning and publishing' },
];
return {
buildTools,
testingFrameworks,
developmentTools,
deploymentTools,
recommendations,
};
}
/**
* Generate a comprehensive research summary
*/
function generateResearchSummary(
researchResults: any[],
codeAnalysis: any,
toolsResearch: any
): string {
let summary = 'Research Summary:\n\n';
summary += `Analyzed ${researchResults.length} research topics:\n`;
researchResults.forEach(result => {
summary += `- ${result.topic}: ${result.findings.length} findings, ${result.tools.length} tools identified\n`;
});
if (codeAnalysis) {
summary += `\nCode Architecture Analysis:\n`;
summary += `- Identified ${codeAnalysis.identifiedPatterns.length} architectural patterns\n`;
summary += `- Suggested ${codeAnalysis.suggestedArchitecture.length} architectural approaches\n`;
}
summary += `\nTool Recommendations:\n`;
toolsResearch.recommendations.forEach(rec => {
summary += `- ${rec.tool}: ${rec.reason}\n`;
});
return summary;
}
/**
* Generate recommendations based on research
*/
function generateRecommendations(researchResults: any[], toolsResearch: any): string[] {
const recommendations: string[] = [];
// Add tool recommendations
toolsResearch.recommendations.forEach(rec => {
recommendations.push(`Use ${rec.tool} for ${rec.reason.toLowerCase()}`);
});
// Add best practice recommendations
researchResults.forEach(result => {
result.bestPractices.forEach(practice => {
recommendations.push(practice);
});
});
return [...new Set(recommendations)]; // Remove duplicates
}
/**
* Extract key findings from research
*/
function extractKeyFindings(researchResults: any[]): string[] {
const keyFindings: string[] = [];
researchResults.forEach(result => {
// Add the most important findings
keyFindings.push(...result.findings.slice(0, 2));
keyFindings.push(...result.currentTrends.slice(0, 1));
});
return [...new Set(keyFindings)]; // Remove duplicates
}
/**
* Suggest next steps based on research
*/
function suggestNextSteps(summary: string): string[] {
return [
'Proceed to cognitive analysis phase',
'Analyze research findings for patterns and insights',
'Identify key requirements and constraints',
'Prepare for detailed planning phase',
];
}