UNPKG

mcp-context-engineering

Version:

The intelligent context optimization system for AI coding assistants. Built with Cole's PRP methodology, Context Portal knowledge graphs, and production-ready MongoDB architecture.

368 lines (309 loc) 13.7 kB
import { z } from 'zod'; // Cole's verified research process schema export const ResearchRequestSchema = z.object({ feature_description: z.string(), project_context: z.object({ type: z.string(), tech_stack: z.array(z.string()), existing_patterns: z.array(z.string()).optional(), codebase_info: z.object({ languages: z.array(z.string()), frameworks: z.array(z.string()), architecture_patterns: z.array(z.string()) }).optional() }), research_depth: z.enum(['basic', 'comprehensive', 'exhaustive']).default('comprehensive') }); export const ResearchResultSchema = z.object({ codebase_analysis: z.array(z.string()), external_research: z.array(z.string()), documentation_urls: z.array(z.string()), existing_patterns: z.array(z.string()), potential_challenges: z.array(z.string()), best_practices: z.array(z.string()), implementation_examples: z.array(z.object({ source: z.string(), description: z.string(), code_snippet: z.string().optional(), relevance_score: z.number().min(0).max(10) })), confidence_score: z.number().min(1).max(10) }); export type ResearchRequest = z.infer<typeof ResearchRequestSchema>; export type ResearchResult = z.infer<typeof ResearchResultSchema>; /** * Research Engine implementing Cole's systematic research methodology * * From Cole's verified approach: * 1. Analyze existing codebase for patterns * 2. Conduct external research * 3. Gather documentation and examples * 4. Identify potential challenges * 5. Extract implementation patterns */ export class ResearchEngine { /** * Conduct systematic research following Cole's methodology */ async conductResearch(request: ResearchRequest): Promise<ResearchResult> { const validatedRequest = ResearchRequestSchema.parse(request); // Step 1: Analyze existing codebase patterns (Cole's first step) const codebaseAnalysis = await this.analyzeCodebasePatterns(validatedRequest); // Step 2: Conduct external research (Cole's second step) const externalResearch = await this.conductExternalResearch(validatedRequest); // Step 3: Gather documentation and examples (Cole's third step) const documentationResearch = await this.gatherDocumentationAndExamples(validatedRequest); // Step 4: Identify potential challenges (Cole's proactive approach) const challengeAnalysis = await this.identifyPotentialChallenges(validatedRequest); // Step 5: Extract best practices and patterns const bestPractices = await this.extractBestPractices(validatedRequest); // Step 6: Score confidence based on research completeness const confidenceScore = this.calculateConfidenceScore({ codebaseAnalysis, externalResearch, documentationResearch, challengeAnalysis, bestPractices }); return { codebase_analysis: codebaseAnalysis, external_research: externalResearch, documentation_urls: documentationResearch.urls, existing_patterns: documentationResearch.patterns, potential_challenges: challengeAnalysis, best_practices: bestPractices, implementation_examples: documentationResearch.examples, confidence_score: confidenceScore }; } /** * Step 1: Analyze existing codebase for patterns * Cole's emphasis on understanding existing implementations */ private async analyzeCodebasePatterns(request: ResearchRequest): Promise<string[]> { const analysis: string[] = []; // Analyze based on project context const { project_context } = request; // Technology stack analysis if (project_context.tech_stack.length > 0) { analysis.push(`Technology stack: ${project_context.tech_stack.join(', ')}`); // Framework-specific patterns for (const tech of project_context.tech_stack) { analysis.push(...this.getFrameworkPatterns(tech, request.feature_description)); } } // Existing patterns analysis if (project_context.existing_patterns) { analysis.push(`Existing patterns identified: ${project_context.existing_patterns.join(', ')}`); analysis.push(...this.analyzePatternCompatibility( project_context.existing_patterns, request.feature_description )); } // Architecture considerations if (project_context.codebase_info?.architecture_patterns) { analysis.push(...this.analyzeArchitecturalFit( project_context.codebase_info.architecture_patterns, request.feature_description )); } return analysis; } /** * Step 2: Conduct external research * Cole's emphasis on comprehensive external knowledge */ private async conductExternalResearch(request: ResearchRequest): Promise<string[]> { const research: string[] = []; // Industry best practices research research.push(`Industry best practices for ${request.feature_description}`); research.push(`Common implementation approaches for ${request.project_context.type} projects`); // Technology-specific research for (const tech of request.project_context.tech_stack) { research.push(`${tech} specific implementation patterns for ${request.feature_description}`); research.push(`${tech} community best practices and conventions`); } // Security and performance considerations research.push(`Security considerations for ${request.feature_description}`); research.push(`Performance implications and optimization strategies`); research.push(`Scalability considerations for ${request.project_context.type} applications`); // Maintenance and testing approaches research.push(`Testing strategies for ${request.feature_description} implementations`); research.push(`Maintenance and debugging approaches`); return research; } /** * Step 3: Gather documentation and examples * Cole's focus on concrete, actionable references */ private async gatherDocumentationAndExamples(request: ResearchRequest): Promise<{ urls: string[]; patterns: string[]; examples: Array<{ source: string; description: string; code_snippet?: string; relevance_score: number; }>; }> { const documentation = { urls: [] as string[], patterns: [] as string[], examples: [] as Array<{ source: string; description: string; code_snippet?: string; relevance_score: number; }> }; // Framework documentation for (const tech of request.project_context.tech_stack) { documentation.urls.push(`Official ${tech} documentation for ${request.feature_description}`); documentation.patterns.push(`${tech} recommended patterns for ${request.feature_description}`); } // Implementation examples documentation.examples.push({ source: `${request.project_context.type} implementation guide`, description: `Standard ${request.feature_description} implementation`, relevance_score: 9 }); documentation.examples.push({ source: `${request.project_context.tech_stack[0] || 'Generic'} best practices`, description: `Production-ready ${request.feature_description} example`, relevance_score: 8 }); return documentation; } /** * Step 4: Identify potential challenges * Cole's proactive error prevention approach */ private async identifyPotentialChallenges(request: ResearchRequest): Promise<string[]> { const challenges: string[] = []; // Technology stack specific challenges for (const tech of request.project_context.tech_stack) { challenges.push(...this.getTechnologyChallenges(tech, request.feature_description)); } // Project type specific challenges challenges.push(...this.getProjectTypeChallenges( request.project_context.type, request.feature_description )); // Integration challenges if (request.project_context.existing_patterns) { challenges.push(...this.getIntegrationChallenges( request.project_context.existing_patterns, request.feature_description )); } // Common implementation pitfalls challenges.push(...this.getCommonPitfalls(request.feature_description)); return challenges; } /** * Step 5: Extract best practices */ private async extractBestPractices(request: ResearchRequest): Promise<string[]> { const practices: string[] = []; // Universal best practices practices.push(`Follow ${request.project_context.type} coding standards and conventions`); practices.push(`Implement comprehensive error handling and logging`); practices.push(`Include unit and integration tests`); practices.push(`Document API interfaces and usage examples`); // Technology-specific practices for (const tech of request.project_context.tech_stack) { practices.push(...this.getTechnologyBestPractices(tech, request.feature_description)); } return practices; } /** * Calculate research confidence score (Cole's quality measurement) */ private calculateConfidenceScore(research: { codebaseAnalysis: string[]; externalResearch: string[]; documentationResearch: { urls: string[]; patterns: string[]; examples: any[] }; challengeAnalysis: string[]; bestPractices: string[]; }): number { let score = 0; // Codebase analysis completeness (0-2 points) score += Math.min(research.codebaseAnalysis.length / 3, 2); // External research depth (0-2 points) score += Math.min(research.externalResearch.length / 5, 2); // Documentation quality (0-2 points) const docScore = (research.documentationResearch.urls.length + research.documentationResearch.patterns.length + research.documentationResearch.examples.length) / 3; score += Math.min(docScore, 2); // Challenge identification (0-2 points) score += Math.min(research.challengeAnalysis.length / 4, 2); // Best practices coverage (0-2 points) score += Math.min(research.bestPractices.length / 4, 2); return Math.round(score); } // Helper methods for specific analysis private getFrameworkPatterns(tech: string, feature: string): string[] { // Technology-specific pattern analysis const patterns: Record<string, string[]> = { 'express': [`Express.js middleware patterns for ${feature}`, `Express.js routing patterns`], 'react': [`React component patterns for ${feature}`, `React hooks usage patterns`], 'nodejs': [`Node.js async/await patterns`, `Node.js error handling patterns`], 'mongodb': [`MongoDB schema design for ${feature}`, `MongoDB indexing strategies`], 'typescript': [`TypeScript type safety patterns`, `TypeScript interface design`] }; return patterns[tech.toLowerCase()] || [`${tech} implementation patterns for ${feature}`]; } private analyzePatternCompatibility(existingPatterns: string[], feature: string): string[] { return existingPatterns.map(pattern => `Compatibility analysis: ${pattern} with ${feature} implementation` ); } private analyzeArchitecturalFit(architectures: string[], feature: string): string[] { return architectures.map(arch => `Architectural integration: ${feature} within ${arch} pattern` ); } private getTechnologyChallenges(tech: string, feature: string): string[] { const challenges: Record<string, string[]> = { 'mongodb': [`MongoDB connection handling`, `Schema validation and migration`], 'express': [`Middleware ordering and conflicts`, `Route parameter validation`], 'react': [`State management complexity`, `Component lifecycle issues`], 'typescript': [`Type inference limitations`, `Interface compatibility`] }; return challenges[tech.toLowerCase()] || [`${tech} specific implementation challenges`]; } private getProjectTypeChallenges(projectType: string, feature: string): string[] { const challenges: Record<string, string[]> = { 'web app': [`Browser compatibility`, `SEO and performance optimization`], 'api': [`Rate limiting and security`, `API versioning and backwards compatibility`], 'cli': [`Cross-platform compatibility`, `Command line argument parsing`], 'mobile app': [`Platform-specific implementations`, `Performance on mobile devices`] }; return challenges[projectType.toLowerCase()] || [`${projectType} specific challenges`]; } private getIntegrationChallenges(patterns: string[], feature: string): string[] { return [ `Integration with existing ${patterns.join(', ')} patterns`, `Potential conflicts with current architecture`, `Database migration and backwards compatibility` ]; } private getCommonPitfalls(feature: string): string[] { return [ `Insufficient error handling and validation`, `Security vulnerabilities and data exposure`, `Performance bottlenecks and scalability issues`, `Inadequate testing and edge case coverage` ]; } private getTechnologyBestPractices(tech: string, feature: string): string[] { const practices: Record<string, string[]> = { 'mongodb': [`Use proper indexing strategies`, `Implement connection pooling`], 'express': [`Use helmet for security headers`, `Implement proper CORS configuration`], 'react': [`Use React.memo for performance`, `Implement proper key props`], 'typescript': [`Use strict type checking`, `Implement proper error types`] }; return practices[tech.toLowerCase()] || [`Follow ${tech} community best practices`]; } }