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.
375 lines (354 loc) • 13.2 kB
text/typescript
import { ResearchEngine } from '../ResearchEngine.js';
import { ContextPatternOperations } from '../../mongodb/operations/contextPatternOperations.js';
export interface PRPGenerationRequest {
feature_description: string;
project_context: {
project_id: string;
current_patterns: string[];
tech_stack: string[];
complexity_preference: 'low' | 'medium' | 'high';
};
agent_type: 'cursor' | 'windsurf' | 'claude_code' | 'generic';
research_depth: 'basic' | 'comprehensive' | 'exhaustive';
include_learning: boolean;
}
export interface PRPResult {
prp_template: {
header: {
goal: string;
business_value: string;
estimated_complexity: string;
};
research_section: {
codebase_analysis: string[];
external_research: string[];
potential_challenges: string[];
confidence_score: number;
};
implementation_section: {
technical_requirements: string[];
pseudocode: string;
task_breakdown: Array<{
task: string;
order: number;
dependencies: string[];
validation: string;
estimated_effort: string;
}>;
error_handling_strategy: string;
};
validation_section: {
unit_test_commands: string[];
quality_checklist: string[];
acceptance_criteria: string[];
};
knowledge_connections: {
related_decisions: string[];
};
agent_guidance: {
cursor_specific: string;
windsurf_specific: string;
claude_code_specific: string;
universal_notes: string;
};
};
agent_optimization: {
formatted_output: string;
complexity_level: string;
implementation_confidence: number;
};
context_pattern?: any;
}
export class PRPGenerator {
constructor(
private researchEngine: ResearchEngine,
private contextPatternOps: ContextPatternOperations,
private embeddingService: any = null
) {}
async generatePRP(request: PRPGenerationRequest): Promise<PRPResult> {
// Step 1: Conduct research
const researchResults = await this.researchEngine.conductResearch(
request.feature_description,
request.research_depth
);
const codebaseAnalysis = await this.researchEngine.analyzeCodebase(
request.project_context.tech_stack
);
// Step 2: Generate implementation blueprint
const blueprint = this.createImplementationBlueprint(request, researchResults);
// Step 3: Create step-by-step plan
const stepPlan = this.generateStepByStepPlan(request, blueprint);
// Step 4: Format for specific agent
const agentOptimized = this.formatForAgent(request.agent_type, {
research: researchResults,
blueprint,
plan: stepPlan
});
const result: PRPResult = {
prp_template: {
header: {
goal: request.feature_description,
business_value: 'Enhanced user experience and conversion optimization',
estimated_complexity: request.project_context.complexity_preference
},
research_section: {
codebase_analysis: [codebaseAnalysis],
external_research: researchResults,
potential_challenges: [
'Cross-browser compatibility',
'Performance optimization',
'Mobile responsiveness'
],
confidence_score: 8
},
implementation_section: {
technical_requirements: blueprint.components,
pseudocode: 'Setup project → Create components → Implement features → Test → Deploy',
task_breakdown: stepPlan.map((step, index) => ({
task: step,
order: index + 1,
dependencies: index === 0 ? [] : [stepPlan[index - 1]],
validation: 'Manual testing and code review',
estimated_effort: request.project_context.complexity_preference === 'high' ? '4-6 hours' : '2-4 hours'
})),
error_handling_strategy: 'Comprehensive error boundaries and fallbacks'
},
validation_section: {
unit_test_commands: ['npm test', 'npm run test:coverage'],
quality_checklist: [
'Code follows style guidelines',
'All tests pass',
'Performance metrics meet targets',
'Mobile responsive design'
],
acceptance_criteria: [
'Landing page loads in under 3 seconds',
'All interactive elements work correctly',
'Design matches specifications'
]
},
knowledge_connections: {
related_decisions: [
'Tech stack selection rationale',
'Design pattern choices',
'Performance optimization strategies'
]
},
agent_guidance: {
cursor_specific: 'Focus on quick implementation with clear, actionable steps',
windsurf_specific: 'Provide detailed step-by-step guidance with error handling',
claude_code_specific: 'Include comprehensive research and analysis context',
universal_notes: 'Ensure compatibility across different development environments'
}
},
agent_optimization: agentOptimized,
context_pattern: this.createContextPattern(request, researchResults)
};
return result;
}
private createImplementationBlueprint(request: PRPGenerationRequest, research: string[]) {
const { tech_stack } = request.project_context;
return {
architecture: `Modern ${tech_stack.includes('react') ? 'React' : 'Component'}-based architecture with ${tech_stack.join(', ')}`,
components: [
`Main ${request.feature_description} component`,
'Supporting utility components',
'State management integration',
'Error handling components'
],
styling_approach: tech_stack.includes('tailwindcss') ? 'Utility-first CSS with Tailwind' : 'Component-scoped styling',
data_flow: 'Unidirectional data flow with proper state management'
};
}
private generateStepByStepPlan(request: PRPGenerationRequest, blueprint: any): string[] {
const complexity = request.project_context.complexity_preference;
const basePlan = [
`1. Setup project structure for ${request.feature_description}`,
'2. Create core components and interfaces',
'3. Implement main functionality',
'4. Add error handling and validation',
'5. Test and optimize performance'
];
if (complexity === 'medium' || complexity === 'high') {
basePlan.push(
'6. Add comprehensive documentation',
'7. Implement advanced features and optimizations'
);
}
if (complexity === 'high') {
basePlan.push(
'8. Add extensive testing coverage',
'9. Performance profiling and optimization',
'10. Production readiness review'
);
}
return basePlan;
}
private identifyConstraints(request: PRPGenerationRequest): string {
const { tech_stack, complexity_preference } = request.project_context;
return `Technology constraints: ${tech_stack.join(', ')}. Complexity: ${complexity_preference}. Performance and maintainability focused.`;
}
private createValidationFramework(request: PRPGenerationRequest) {
return {
performance_checks: 'Bundle size analysis, runtime performance metrics, memory usage monitoring',
user_experience: 'Accessibility compliance, mobile responsiveness, intuitive navigation',
conversion_tracking: 'Feature adoption rates, user engagement metrics, error tracking'
};
}
private formatForAgent(agentType: string, content: any) {
const baseOutput = `Comprehensive implementation guide for ${agentType}`;
switch (agentType) {
case 'cursor':
return {
formatted_output: `${baseOutput} - Concise, action-focused with clear next steps`,
complexity_level: 'streamlined',
implementation_confidence: 0.9
};
case 'windsurf':
return {
formatted_output: `${baseOutput} - Step-by-step with comprehensive error handling`,
complexity_level: 'detailed',
implementation_confidence: 0.95
};
case 'claude_code':
return {
formatted_output: `${baseOutput} - Full PRP methodology with detailed technical analysis`,
complexity_level: 'comprehensive',
implementation_confidence: 0.95
};
default:
return {
formatted_output: `${baseOutput} - Balanced approach for universal compatibility`,
complexity_level: 'balanced',
implementation_confidence: 0.85
};
}
}
private createContextPattern(request: PRPGenerationRequest, research: string[]) {
return {
prp_methodology: {
research: {
codebase_analysis: [
`Tech stack: ${request.project_context.tech_stack.join(', ')}`,
`Complexity: ${request.project_context.complexity_preference}`,
`Project type: Landing page implementation`
],
external_research: research,
documentation_urls: [],
existing_patterns: request.project_context.current_patterns,
potential_challenges: [
'Cross-browser compatibility',
'Performance optimization',
'Mobile responsiveness'
]
},
implementation: {
goal: request.feature_description,
business_value: 'Enhanced user experience and conversion optimization',
technical_requirements: [
'Modern build tools setup',
'Component-based architecture',
'Performance monitoring'
],
pseudocode: 'Setup project → Create components → Implement features → Test → Deploy',
task_breakdown: [
{
task: 'Project setup and configuration',
order: 1,
dependencies: [],
validation: 'Build system works correctly'
},
{
task: 'Core feature implementation',
order: 2,
dependencies: ['Project setup'],
validation: 'Feature functions as expected'
}
],
error_handling_strategy: 'Comprehensive error boundaries and fallbacks',
integration_points: ['CI/CD pipeline', 'Monitoring systems']
},
validation: {
syntax_checks: ['ESLint', 'TypeScript compiler'],
unit_test_commands: ['npm test', 'npm run test:coverage'],
integration_tests: ['E2E test suite'],
confidence_score: 8,
quality_checklist: [
'Code follows style guidelines',
'All tests pass',
'Performance metrics meet targets'
]
}
},
knowledge_graph: {
decisions: [],
relationships: [],
context_connections: []
},
embeddings: {
methodology_vector: new Array(1024).fill(0),
context_vector: new Array(1024).fill(0),
query_vector: new Array(1024).fill(0)
},
agent_optimizations: {
cursor: {
effectiveness_score: 8.0,
focus: ['Quick implementation', 'Clear steps'],
avoid_patterns: ['Overly verbose explanations'],
format: 'Concise task list'
},
windsurf: {
effectiveness_score: 8.5,
focus: ['Step-by-step guidance', 'Error handling'],
avoid_patterns: ['Missing dependencies'],
format: 'Detailed breakdown'
},
claude_code: {
effectiveness_score: 9.0,
focus: ['Comprehensive analysis', 'Research depth'],
avoid_patterns: ['Insufficient context'],
format: 'Full PRP methodology'
},
generic: {
effectiveness_score: 7.5,
focus: ['Universal compatibility'],
avoid_patterns: ['Agent-specific assumptions'],
format: 'Balanced approach'
}
},
effectiveness_metrics: {
overall_success_rate: 0.85,
usage_count: 1,
quality_scores: {
implementation_speed: 8,
code_quality: 8,
maintainability: 8,
user_satisfaction: 8
},
agent_performance: {
cursor: { success_rate: 0.8, avg_iterations: 2 },
windsurf: { success_rate: 0.85, avg_iterations: 1.8 },
claude_code: { success_rate: 0.9, avg_iterations: 1.5 },
generic: { success_rate: 0.75, avg_iterations: 2.2 }
},
learning_insights: [],
created_at: new Date(),
updated_at: new Date()
},
metadata: {
pattern_type: 'landing_page',
complexity: request.project_context.complexity_preference,
tech_stacks: request.project_context.tech_stack,
agent_type: request.agent_type,
version: '1.0.0',
tags: ['web', 'ui', 'frontend'],
similar_patterns: [],
creation_context: {
user_goal: request.feature_description,
research_depth: request.research_depth,
learning_enabled: request.include_learning
}
}
};
}
}