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.

451 lines (406 loc) 13.7 kB
import { Collection, ObjectId, Filter, UpdateFilter } from 'mongodb'; import { UniversalContextPattern, UniversalContextPatternSchema, COLLECTIONS } from '../models/contextPattern.js'; import { MongoConnectionManager } from './connection.js'; import { debugConfig } from '../../config/environment.js'; /** * Context Pattern Operations - Core CRUD functionality * Implements production-ready MongoDB operations for Universal Context Patterns */ export class ContextPatternOperations { private connectionManager: MongoConnectionManager; private collection: Collection<UniversalContextPattern> | null = null; constructor(connectionManager: MongoConnectionManager) { this.connectionManager = connectionManager; } /** * Get the context patterns collection */ private async getCollection(): Promise<Collection<UniversalContextPattern>> { if (!this.collection) { await this.connectionManager.ensureConnected(); const db = this.connectionManager.getDatabase(); this.collection = db.collection<UniversalContextPattern>(COLLECTIONS.CONTEXT_PATTERNS); } return this.collection; } /** * Create a new context pattern */ async createPattern(pattern: Omit<UniversalContextPattern, '_id'>): Promise<{ success: boolean; patternId?: string; error?: string; }> { try { // Validate the pattern data const validatedPattern = UniversalContextPatternSchema.omit({ _id: true }).parse(pattern); const collection = await this.getCollection(); const result = await collection.insertOne({ ...validatedPattern, metadata: { ...validatedPattern.metadata, created_at: new Date(), updated_at: new Date() } } as UniversalContextPattern); if (debugConfig.mongodbOperations) { console.log('✅ Pattern created:', result.insertedId); } return { success: true, patternId: result.insertedId.toString() }; } catch (error) { console.error('❌ Failed to create pattern:', error); return { success: false, error: error instanceof Error ? error.message : 'Unknown error' }; } } /** * Get a pattern by ID */ async getPatternById(patternId: string): Promise<{ success: boolean; pattern?: UniversalContextPattern; error?: string; }> { try { const collection = await this.getCollection(); const pattern = await collection.findOne({ _id: new ObjectId(patternId) }); if (!pattern) { return { success: false, error: 'Pattern not found' }; } return { success: true, pattern }; } catch (error) { console.error('❌ Failed to get pattern:', error); return { success: false, error: error instanceof Error ? error.message : 'Unknown error' }; } } /** * Search patterns with filters and pagination */ async searchPatterns(options: { query?: string; filters?: { pattern_type?: string; complexity?: 'low' | 'medium' | 'high'; tech_stacks?: string[]; tags?: string[]; min_effectiveness?: number; agent_type?: 'cursor' | 'windsurf' | 'claude_code' | 'generic'; }; sort?: { field: string; direction: 1 | -1 }; limit?: number; skip?: number; } = {}): Promise<{ success: boolean; patterns?: UniversalContextPattern[]; total?: number; error?: string; }> { try { const collection = await this.getCollection(); const filter: Filter<UniversalContextPattern> = {}; // Text search if (options.query) { filter.$text = { $search: options.query }; } // Apply filters if (options.filters) { const { filters } = options; if (filters.pattern_type) { filter['metadata.pattern_type'] = filters.pattern_type; } if (filters.complexity) { filter['metadata.complexity'] = filters.complexity; } if (filters.tech_stacks && filters.tech_stacks.length > 0) { filter['metadata.tech_stacks'] = { $in: filters.tech_stacks }; } if (filters.tags && filters.tags.length > 0) { filter['metadata.tags'] = { $in: filters.tags }; } if (filters.min_effectiveness) { filter['effectiveness_metrics.overall_success_rate'] = { $gte: filters.min_effectiveness }; } if (filters.agent_type) { filter[`agent_optimizations.${filters.agent_type}.effectiveness_score`] = { $gte: 5 }; } } // Count total results const total = await collection.countDocuments(filter); // Apply sorting const sortOptions: { [key: string]: 1 | -1 } = {}; if (options.sort) { sortOptions[options.sort.field] = options.sort.direction; } else { // Default sort by effectiveness and recency sortOptions['effectiveness_metrics.overall_success_rate'] = -1; sortOptions['metadata.updated_at'] = -1; } // Execute search with pagination const patterns = await collection .find(filter) .sort(sortOptions) .skip(options.skip || 0) .limit(options.limit || 10) .toArray(); if (debugConfig.mongodbOperations) { console.log(`🔍 Search found ${patterns.length} patterns (${total} total)`); } return { success: true, patterns, total }; } catch (error) { console.error('❌ Failed to search patterns:', error); return { success: false, error: error instanceof Error ? error.message : 'Unknown error' }; } } /** * Update pattern effectiveness metrics */ async updatePatternEffectiveness( patternId: string, effectivenessUpdate: { success: boolean; quality_score: number; iterations_required: number; user_satisfaction?: number; agent_type: 'cursor' | 'windsurf' | 'claude_code' | 'generic'; feedback?: { what_worked: string[]; what_failed: string[]; missing_information: string[]; suggestions: string[]; }; } ): Promise<{ success: boolean; error?: string; }> { try { const collection = await this.getCollection(); // Calculate new effectiveness metrics const currentPattern = await collection.findOne({ _id: new ObjectId(patternId) }); if (!currentPattern) { return { success: false, error: 'Pattern not found' }; } const currentMetrics = currentPattern.effectiveness_metrics; const newUsageCount = currentMetrics.usage_count + 1; const newSuccessCount = currentMetrics.implementation_success_count + (effectivenessUpdate.success ? 1 : 0); const newSuccessRate = newSuccessCount / newUsageCount; // Update agent-specific effectiveness const agentKey = effectivenessUpdate.agent_type; const currentAgentScore = currentPattern.agent_optimizations[agentKey].effectiveness_score; const newAgentScore = (currentAgentScore + effectivenessUpdate.quality_score) / 2; // Simple moving average const update: UpdateFilter<UniversalContextPattern> = { $set: { 'effectiveness_metrics.overall_success_rate': newSuccessRate, 'effectiveness_metrics.implementation_success_count': newSuccessCount, 'effectiveness_metrics.usage_count': newUsageCount, 'effectiveness_metrics.last_used': new Date(), [`agent_optimizations.${agentKey}.effectiveness_score`]: Math.min(newAgentScore, 10), 'metadata.updated_at': new Date() }, $push: { 'effectiveness_metrics.feedback_history': { score: effectivenessUpdate.quality_score, feedback: effectivenessUpdate.feedback ? JSON.stringify(effectivenessUpdate.feedback) : '', agent_type: effectivenessUpdate.agent_type, timestamp: new Date(), implementation_success: effectivenessUpdate.success } } }; // Add improvement suggestions if provided if (effectivenessUpdate.feedback?.suggestions) { update.$addToSet = { 'effectiveness_metrics.improvement_suggestions': { $each: effectivenessUpdate.feedback.suggestions } }; } const result = await collection.updateOne( { _id: new ObjectId(patternId) }, update ); if (debugConfig.mongodbOperations) { console.log(`📈 Updated effectiveness for pattern ${patternId}:`, { newSuccessRate: newSuccessRate.toFixed(3), newAgentScore: newAgentScore.toFixed(1), usageCount: newUsageCount }); } return { success: result.modifiedCount > 0 }; } catch (error) { console.error('❌ Failed to update pattern effectiveness:', error); return { success: false, error: error instanceof Error ? error.message : 'Unknown error' }; } } /** * Get patterns similar to a query using text search * This is a simplified version - vector search will be implemented later */ async findSimilarPatterns( query: string, options: { limit?: number; filters?: { tech_stacks?: string[]; complexity?: 'low' | 'medium' | 'high'; min_effectiveness?: number; }; } = {} ): Promise<{ success: boolean; patterns?: Array<UniversalContextPattern & { similarity_score: number }>; error?: string; }> { try { const searchResult = await this.searchPatterns({ query, filters: options.filters, limit: options.limit || 10, sort: { field: 'score', direction: -1 } // MongoDB text search score }); if (!searchResult.success || !searchResult.patterns) { return searchResult as any; } // Add similarity scores (simplified - will be replaced with vector similarity) const patternsWithScores = searchResult.patterns.map(pattern => ({ ...pattern, similarity_score: Math.random() * 0.3 + 0.7 // Placeholder - will use actual vector similarity })); return { success: true, patterns: patternsWithScores as any }; } catch (error) { console.error('❌ Failed to find similar patterns:', error); return { success: false, error: error instanceof Error ? error.message : 'Unknown error' }; } } /** * Get patterns for a specific project */ async getProjectPatterns(projectId: string): Promise<{ success: boolean; patterns?: UniversalContextPattern[]; error?: string; }> { try { const searchResult = await this.searchPatterns({ filters: { // Project-specific search would be implemented with project context }, sort: { field: 'metadata.updated_at', direction: -1 }, limit: 50 }); return searchResult; } catch (error) { console.error('❌ Failed to get project patterns:', error); return { success: false, error: error instanceof Error ? error.message : 'Unknown error' }; } } /** * Delete a pattern (admin operation) */ async deletePattern(patternId: string): Promise<{ success: boolean; error?: string; }> { try { const collection = await this.getCollection(); const result = await collection.deleteOne({ _id: new ObjectId(patternId) }); return { success: result.deletedCount > 0 }; } catch (error) { console.error('❌ Failed to delete pattern:', error); return { success: false, error: error instanceof Error ? error.message : 'Unknown error' }; } } /** * Get effectiveness analytics */ async getEffectivenessAnalytics(): Promise<{ success: boolean; analytics?: { total_patterns: number; average_success_rate: number; most_effective_agent: string; most_common_pattern_type: string; recent_activity: number; }; error?: string; }> { try { const collection = await this.getCollection(); // Aggregate effectiveness data const pipeline = [ { $group: { _id: null, total_patterns: { $sum: 1 }, average_success_rate: { $avg: '$effectiveness_metrics.overall_success_rate' }, recent_patterns: { $sum: { $cond: [ { $gte: ['$metadata.updated_at', new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)] }, 1, 0 ] } } } } ]; const result = await collection.aggregate(pipeline).toArray(); const stats = result[0] || { total_patterns: 0, average_success_rate: 0, recent_patterns: 0 }; return { success: true, analytics: { total_patterns: stats.total_patterns, average_success_rate: stats.average_success_rate, most_effective_agent: 'claude_code', // Placeholder - would calculate from data most_common_pattern_type: 'general_feature', // Placeholder - would calculate from data recent_activity: stats.recent_patterns } }; } catch (error) { console.error('❌ Failed to get analytics:', error); return { success: false, error: error instanceof Error ? error.message : 'Unknown error' }; } } }