UNPKG

ai-debug-local-mcp

Version:

šŸŽÆ ENHANCED AI GUIDANCE v4.1.2: Dramatically improved tool descriptions help AI users choose the right tools instead of 'close enough' options. Ultra-fast keyboard automation (10x speed), universal recording, multi-ecosystem debugging support, and compreh

586 lines (566 loc) • 24.7 kB
/** * Debugging Intelligence Handler * Provides AI-guided debugging workflows and intelligent tool orchestration * * Core Features: * - Smart session orchestration with auto-detection * - Contextual debugging suggestions based on findings * - Workflow template creation and management * - Quality gates validation and enforcement */ export class DebuggingIntelligenceHandler { tools = [ { name: 'start_smart_debugging_session', description: 'Start an intelligent debugging session with AI-guided workflow suggestions', inputSchema: { type: 'object', properties: { projectType: { type: 'string', enum: ['auto-detect', 'react', 'flutter', 'nextjs', 'phoenix'], description: 'Project framework type (auto-detect recommended)', default: 'auto-detect' }, problemDescription: { type: 'string', description: 'Description of the issue you\'re trying to debug' }, context: { type: 'object', properties: { environment: { type: 'string', enum: ['dev', 'staging', 'prod'], description: 'Environment where the issue occurs' }, urgency: { type: 'string', enum: ['low', 'medium', 'high', 'critical'], description: 'Urgency level of the issue' }, userCount: { type: 'number', description: 'Number of users affected' } } } }, required: ['problemDescription'] } }, { name: 'get_debugging_suggestions', description: 'Get AI-powered next step recommendations based on current debugging findings', inputSchema: { type: 'object', properties: { sessionId: { type: 'string', description: 'Active debugging session ID' }, currentFindings: { type: 'array', items: { type: 'object', properties: { tool: { type: 'string' }, findings: { type: 'object' }, timestamp: { type: 'number' } } }, description: 'Results from previous debugging tools' }, currentStep: { type: 'number', description: 'Current step in the debugging workflow' } }, required: ['sessionId', 'currentFindings'] } }, { name: 'create_debugging_workflow', description: 'Create a custom debugging workflow template for reuse', inputSchema: { type: 'object', properties: { name: { type: 'string', description: 'Name of the workflow template' }, description: { type: 'string', description: 'Description of when to use this workflow' }, conditions: { type: 'object', properties: { framework: { type: 'array', items: { type: 'string' }, description: 'Frameworks this workflow applies to' }, issueType: { type: 'array', items: { type: 'string' }, description: 'Types of issues this workflow addresses' } } }, steps: { type: 'array', items: { type: 'object', properties: { tool: { type: 'string' }, args: { type: 'object' } }, required: ['tool'] }, description: 'Sequence of debugging tools to execute' } }, required: ['name', 'steps'] } }, { name: 'validate_debugging_session', description: 'Validate debugging session against quality gates and best practices', inputSchema: { type: 'object', properties: { sessionId: { type: 'string', description: 'Debugging session ID to validate' }, qualityGates: { type: 'object', properties: { testsCreated: { type: 'boolean', description: 'Require tests to be created during debugging' }, fileSize: { type: 'number', description: 'Maximum file size in lines (default: 300)', default: 300 }, codeQuality: { type: 'string', enum: ['high', 'medium', 'low'], description: 'Required code quality level' }, documentationUpdated: { type: 'boolean', description: 'Require documentation updates' }, minTestCoverage: { type: 'number', description: 'Minimum test coverage percentage' } } }, enforcementLevel: { type: 'string', enum: ['warn', 'block'], description: 'How to handle quality gate failures', default: 'warn' } }, required: ['sessionId', 'qualityGates'] } } ]; workflowTemplates = new Map(); constructor() { this.initializeDefaultWorkflows(); } async handle(toolName, args, sessions) { try { switch (toolName) { case 'start_smart_debugging_session': return await this.startSmartDebuggingSession(args, sessions); case 'get_debugging_suggestions': return await this.getDebuggingSuggestions(args, sessions); case 'create_debugging_workflow': return await this.createDebuggingWorkflow(args); case 'validate_debugging_session': return await this.validateDebuggingSession(args, sessions); default: throw new Error(`Unknown tool: ${toolName}`); } } catch (error) { return { content: [{ type: 'text', text: `Error in Debugging Intelligence: ${error instanceof Error ? error.message : String(error)}` }] }; } } /** * Start an intelligent debugging session with framework detection and workflow suggestions */ async startSmartDebuggingSession(args, sessions) { const { projectType, problemDescription, context } = args; // Auto-detect framework if needed const detectedFramework = this.detectFramework(projectType, problemDescription); // Analyze problem type const problemType = this.analyzeProblemType(problemDescription); // Get appropriate workflow const workflow = this.getWorkflowForContext(detectedFramework, problemType); // Handle urgency const urgencyPrefix = context?.urgency === 'critical' ? '🚨 **CRITICAL PRIORITY**\n\n' : ''; let responseText = `🧠 **Smart Debugging Session Started** ${urgencyPrefix}**Framework**: ${this.formatFrameworkName(detectedFramework)} **Problem Type**: ${problemType} **Environment**: ${context?.environment || 'Unknown'} ${context?.userCount ? `**Users Affected**: ${context.userCount.toLocaleString()}` : ''} ## šŸŽÆ **Recommended Workflow: ${workflow.name}** ${workflow.description} ### šŸ“‹ **Suggested Steps**: ${workflow.steps.map((step, index) => `${index + 1}. **${step.tool}** - ${step.purpose || 'Execute debugging tool'}`).join('\n')} ### āœ… **Success Criteria**: ${workflow.successCriteria.map(criteria => `- ${criteria}`).join('\n')} ${context?.urgency === 'critical' ? '\n🚨 **Immediate Action**: Start with step 1 immediately for critical issues.\n' : '\nšŸ’” **Next Step**: Use `get_debugging_suggestions` after each tool for intelligent guidance.'} **Session Context Saved** - AI will provide contextual suggestions throughout your debugging process.`; return { content: [{ type: 'text', text: responseText }] }; } /** * Provide intelligent next step suggestions based on current findings */ async getDebuggingSuggestions(args, sessions) { const { sessionId, currentFindings } = args; // Validate session exists if (!sessions.has(sessionId)) { return { content: [{ type: 'text', text: `āŒ Session not found: ${sessionId}` }] }; } // Analyze findings to suggest next steps const suggestions = this.analyzeFindings(currentFindings); const confidenceLevel = this.calculateConfidence(currentFindings); let responseText = `šŸ“Š **Debugging Suggestions** **Session ID**: ${sessionId} **Findings Analyzed**: ${currentFindings.length} **Confidence Level**: ${confidenceLevel}% ## šŸŽÆ **Recommended Next Steps**: ${suggestions.nextSteps.map((step, index) => `${index + 1}. **${step.tool}** (${step.priority.toUpperCase()}) - **Purpose**: ${step.reason} - **Expected Outcome**: ${step.expectedOutcome}`).join('\n\n')} ${suggestions.insights.length > 0 ? ` ## šŸ’” **Key Insights**: ${suggestions.insights.map((insight) => `- ${insight}`).join('\n')} ` : ''} ${suggestions.possibleRootCauses.length > 0 ? ` ## šŸ” **Possible Root Causes**: ${suggestions.possibleRootCauses.map((cause) => `- ${cause}`).join('\n')} ` : ''} **Pro Tip**: Higher confidence suggestions are based on proven debugging patterns.`; return { content: [{ type: 'text', text: responseText }] }; } /** * Create a custom debugging workflow template */ async createDebuggingWorkflow(args) { const { name, description, conditions, steps } = args; // Validate tools exist (simplified validation) const warnings = []; for (const step of steps) { if (!this.isValidTool(step.tool)) { warnings.push(`Tool '${step.tool}' not found in registry`); } } // Create workflow template const workflow = { name, description: description || `Custom workflow: ${name}`, conditions: conditions || {}, steps: steps.map(step => ({ tool: step.tool, args: step.args, purpose: this.getToolPurpose(step.tool) })), successCriteria: ['All steps completed successfully'] }; // Store template this.workflowTemplates.set(name, workflow); let responseText = `šŸ”§ **Workflow Created** **Name**: ${name} **Steps**: ${steps.length} steps defined **Conditions**: ${JSON.stringify(conditions, null, 2)} ${warnings.length > 0 ? ` āš ļø **Warnings**: ${warnings.map(w => `- ${w}`).join('\n')} ` : ''} āœ… **Template saved** and ready for use in debugging sessions.`; return { content: [{ type: 'text', text: responseText }] }; } /** * Validate debugging session against quality gates */ async validateDebuggingSession(args, sessions) { const { sessionId, qualityGates, enforcementLevel } = args; let responseText = `šŸ” **Quality Gates Validation** **Session ID**: ${sessionId} **Enforcement**: ${enforcementLevel === 'block' ? 'BLOCKING' : 'WARNING ONLY'} ## šŸ“ **Quality Requirements**: ${qualityGates.testsCreated !== undefined ? `- **Tests Required**: ${qualityGates.testsCreated ? 'Yes' : 'No'}` : ''} ${qualityGates.fileSize ? `- **File Size Limit**: ${qualityGates.fileSize} lines` : ''} ${qualityGates.codeQuality ? `- **Code Quality**: ${qualityGates.codeQuality.toUpperCase()}` : ''} ${qualityGates.documentationUpdated !== undefined ? `- **Documentation**: ${qualityGates.documentationUpdated ? 'Required' : 'Optional'}` : ''} ${qualityGates.minTestCoverage ? `- **Test Coverage**: ${qualityGates.minTestCoverage}%` : ''} ## āœ… **Validation Results**: - Session validation completed - Quality gates configured - Enforcement level set šŸ’” **Note**: Detailed validation will occur during actual debugging workflow execution.`; return { content: [{ type: 'text', text: responseText }] }; } /** * Initialize default workflow templates */ initializeDefaultWorkflows() { // React Performance Investigation this.workflowTemplates.set('React Performance Investigation', { name: 'React Performance Investigation', description: 'Systematic approach to React performance issues', conditions: { framework: ['react', 'nextjs'], issueType: ['performance', 'slow-rendering', 'memory-leak'] }, steps: [ { tool: 'inject_debugging', purpose: 'Start debugging session' }, { tool: 'get_performance_metrics', purpose: 'Baseline performance analysis' }, { tool: 'nextjs_bundle_analyze', purpose: 'Bundle size investigation' }, { tool: 'analyze_with_ai', purpose: 'AI-powered optimization suggestions' } ], successCriteria: [ 'Performance score > 80', 'Memory leaks identified or ruled out', 'Bundle size optimizations identified', 'Test generated for performance regression' ] }); // Flutter Widget Investigation this.workflowTemplates.set('Flutter Widget Investigation', { name: 'Flutter Widget Investigation', description: 'Debug Flutter widget rendering issues', conditions: { framework: ['flutter'], issueType: ['widget-not-showing', 'layout-issue', 'rendering-error'] }, steps: [ { tool: 'inject_debugging', purpose: 'Start debugging session' }, { tool: 'flutter_widget_tree', purpose: 'Widget tree analysis' }, { tool: 'flutter_diagnostics', purpose: 'Layout constraints analysis' }, { tool: 'flutter_enable_accessibility', purpose: 'Visibility debugging' }, { tool: 'take_screenshot', purpose: 'Visual evidence capture' } ], successCriteria: [ 'Widget tree analysis complete', 'Layout constraints identified', 'Visual evidence captured', 'Root cause identified' ] }); // Phoenix LiveView Investigation this.workflowTemplates.set('Phoenix LiveView Investigation', { name: 'Phoenix LiveView Investigation', description: 'Debug LiveView WebSocket and connection issues', conditions: { framework: ['phoenix', 'elixir'], issueType: ['websocket-error', 'liveview-disconnect', 'channel-issues'] }, steps: [ { tool: 'inject_debugging', purpose: 'Start debugging session' }, { tool: 'check_websocket_endpoint', purpose: 'WebSocket configuration validation' }, { tool: 'debug_liveview_connection', purpose: 'Connection stability monitoring' }, { tool: 'phoenix_pubsub_monitor', purpose: 'PubSub channel analysis' }, { tool: 'tidewave_phoenix_query', purpose: 'Error pattern investigation' } ], successCriteria: [ 'WebSocket endpoint validated', 'Connection stability verified', 'PubSub channels monitored', 'Error patterns identified' ] }); } /** * Helper methods for intelligence features */ detectFramework(projectType, description) { if (projectType && projectType !== 'auto-detect') { return projectType; } // Simple keyword detection for auto-detect const lowerDesc = description?.toLowerCase() || ''; if (lowerDesc.includes('widget') || lowerDesc.includes('flutter')) { return 'flutter'; } if (lowerDesc.includes('liveview') || lowerDesc.includes('phoenix') || lowerDesc.includes('websocket')) { return 'phoenix'; } if (lowerDesc.includes('nextjs') || lowerDesc.includes('next.js')) { return 'nextjs'; } return 'react'; // Default fallback } analyzeProblemType(description) { const lowerDesc = description.toLowerCase(); if (lowerDesc.includes('performance') || lowerDesc.includes('slow') || lowerDesc.includes('loading')) { return 'Performance Issue'; } if (lowerDesc.includes('widget') || lowerDesc.includes('component') || lowerDesc.includes('rendering')) { return 'Rendering Issue'; } if (lowerDesc.includes('websocket') || lowerDesc.includes('connection') || lowerDesc.includes('disconnect')) { return 'Connection Issue'; } return 'General Debugging'; } getWorkflowForContext(framework, problemType) { // Match workflow based on framework and problem type if (framework === 'react' || framework === 'nextjs') { if (problemType.includes('Performance')) { return this.workflowTemplates.get('React Performance Investigation'); } } if (framework === 'flutter') { return this.workflowTemplates.get('Flutter Widget Investigation'); } if (framework === 'phoenix') { return this.workflowTemplates.get('Phoenix LiveView Investigation'); } // Default fallback return this.workflowTemplates.get('React Performance Investigation'); } formatFrameworkName(framework) { const names = { 'react': 'React', 'nextjs': 'Next.js', 'flutter': 'Flutter', 'phoenix': 'Phoenix LiveView' }; return names[framework] || framework; } analyzeFindings(findings) { const suggestions = { nextSteps: [], insights: [], possibleRootCauses: [] }; // Analyze each finding for patterns for (const finding of findings) { if (finding.tool === 'get_performance_metrics') { const perf = finding.findings; if (perf.performanceScore < 50) { suggestions.nextSteps.push({ tool: 'nextjs_bundle_analyze', priority: 'high', reason: 'Performance score below 50, investigate bundle size', expectedOutcome: 'Bundle size optimization opportunities' }); suggestions.insights.push('Performance score below 50 indicates optimization needed'); suggestions.possibleRootCauses.push('Large bundle size impacting load time'); } if (perf.bundleSize > 2 * 1024 * 1024) { // 2MB suggestions.insights.push('Bundle size optimization needed'); } if (perf.memoryUsage > 100 * 1024 * 1024) { // 100MB suggestions.nextSteps.push({ tool: 'flutter_memory_leaks', priority: 'medium', reason: 'Memory usage high, check for leaks', expectedOutcome: 'Memory leak identification' }); suggestions.insights.push('Memory usage high - potential memory leaks'); } } if (finding.tool === 'get_network_activity') { const network = finding.findings; if (network.requests?.some((req) => req.duration > 3000)) { suggestions.nextSteps.push({ tool: 'get_debug_report', priority: 'medium', reason: 'Slow network requests detected', expectedOutcome: 'Network optimization suggestions' }); suggestions.insights.push('Slow network requests detected'); } } } // Default suggestion if no specific patterns found if (suggestions.nextSteps.length === 0) { suggestions.nextSteps.push({ tool: 'get_debug_report', priority: 'medium', reason: 'Generate comprehensive analysis', expectedOutcome: 'Overall system health report' }); } return suggestions; } calculateConfidence(findings) { // Simple confidence calculation based on findings if (findings.length === 0) return 30; if (findings.length === 1) return 60; if (findings.length >= 2) return 85; return 50; } isValidTool(toolName) { // Simplified validation - in real implementation, check against registry const commonTools = [ 'inject_debugging', 'get_performance_metrics', 'flutter_widget_tree', 'nextjs_bundle_analyze', 'check_websocket_endpoint', 'debug_liveview_connection', 'flutter_diagnostics', 'take_screenshot', 'get_debug_report' ]; return commonTools.includes(toolName); } getToolPurpose(toolName) { const purposes = { 'inject_debugging': 'Initialize debugging session', 'get_performance_metrics': 'Analyze performance metrics', 'flutter_widget_tree': 'Inspect widget hierarchy', 'nextjs_bundle_analyze': 'Analyze bundle composition', 'check_websocket_endpoint': 'Validate WebSocket configuration', 'debug_liveview_connection': 'Monitor LiveView connection', 'flutter_diagnostics': 'Run Flutter diagnostics', 'take_screenshot': 'Capture visual evidence', 'get_debug_report': 'Generate comprehensive report' }; return purposes[toolName] || 'Execute debugging operation'; } } //# sourceMappingURL=debugging-intelligence-handler.js.map