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
408 lines (396 loc) ⢠20.6 kB
JavaScript
/**
* Enhanced Error Context Handler
*
* P2 Priority: Improve error messages with actionable context
* - Transform generic error messages into actionable guidance
* - Provide specific troubleshooting steps for common issues
* - Include recovery suggestions and next steps
* - Context-aware error categorization
*/
export class EnhancedErrorContext {
/**
* Transform a generic error into an enhanced error with actionable context
*/
static enhanceError(error, toolName, sessionId) {
const errorMessage = error instanceof Error ? error.message : error;
const category = this.categorizeError(errorMessage, toolName);
const context = this.buildErrorContext(errorMessage, category, toolName);
const troubleshooting = this.generateTroubleshooting(errorMessage, category, toolName);
const userGuidance = this.generateUserGuidance(errorMessage, category, toolName);
return {
originalError: errorMessage,
enhancedMessage: this.createEnhancedMessage(errorMessage, context),
context,
troubleshooting,
userGuidance
};
}
/**
* Create a user-friendly error response with actionable context
*/
static createActionableErrorResponse(error, toolName, sessionId) {
const enhanced = this.enhanceError(error, toolName, sessionId);
return {
content: [{
type: 'text',
text: `ā **${toolName} Error**
${enhanced.userGuidance.whatHappened}
**Why this happened:**
${enhanced.userGuidance.whyItHappened}
**How to fix it:**
${enhanced.userGuidance.howToFix}
**Quick fixes to try:**
${enhanced.troubleshooting.quickFixes.map(fix => `⢠${fix}`).join('\n')}
**Next steps:**
${enhanced.userGuidance.nextSteps.map((step, i) => `${i + 1}. ${step}`).join('\n')}
${enhanced.context.recoverable ? 'ā
**This issue is recoverable** - try the steps above' : 'ā ļø **This may require manual intervention** - see diagnostic steps below'}
${enhanced.troubleshooting.diagnosticSteps.length > 0 ? `
**Diagnostic steps:**
${enhanced.troubleshooting.diagnosticSteps.map(step => `š ${step}`).join('\n')}
` : ''}
${enhanced.troubleshooting.preventionTips.length > 0 ? `
**Prevention tips:**
${enhanced.troubleshooting.preventionTips.map(tip => `š” ${tip}`).join('\n')}
` : ''}
${enhanced.context.estimatedFixTime ? `\nā±ļø **Estimated fix time:** ${enhanced.context.estimatedFixTime}` : ''}
${enhanced.context.relatedTools?.length ? `\nš§ **Related tools:** ${enhanced.context.relatedTools.join(', ')}` : ''}
`
}]
};
}
static categorizeError(errorMessage, toolName) {
const lowerError = errorMessage.toLowerCase();
if (lowerError.includes('session') && (lowerError.includes('not found') || lowerError.includes('expired'))) {
return 'session';
}
if (lowerError.includes('browser') || lowerError.includes('playwright') || lowerError.includes('page')) {
return 'browser';
}
if (lowerError.includes('network') || lowerError.includes('fetch') || lowerError.includes('request') || lowerError.includes('timeout')) {
return 'network';
}
if (lowerError.includes('permission') || lowerError.includes('access denied') || lowerError.includes('eperm')) {
return 'permission';
}
if (lowerError.includes('next.js') || lowerError.includes('react') || lowerError.includes('flutter') || lowerError.includes('phoenix') || lowerError.includes('liveview')) {
return 'framework';
}
if (lowerError.includes('config') || lowerError.includes('setup') || lowerError.includes('initialization')) {
return 'configuration';
}
if (lowerError.includes('required') || lowerError.includes('invalid') || lowerError.includes('missing')) {
return 'user_input';
}
return 'system';
}
static buildErrorContext(errorMessage, category, toolName) {
const lowerError = errorMessage.toLowerCase();
let severity = 'medium';
let recoverable = true;
let actionableSteps = [];
let relatedTools = [];
let estimatedFixTime = '2-5 minutes';
switch (category) {
case 'session':
severity = 'high';
recoverable = true;
estimatedFixTime = '1-2 minutes';
actionableSteps = [
'Start a new debugging session',
'Check if your application is still running',
'Verify the URL is accessible',
'Clear browser cache if issues persist'
];
relatedTools = ['inject_debugging', 'monitor_realtime'];
break;
case 'browser':
severity = 'high';
recoverable = true;
estimatedFixTime = '2-5 minutes';
actionableSteps = [
'Close other browser instances to free resources',
'Restart the debugging session',
'Check available system memory',
'Update your browser if needed'
];
relatedTools = ['inject_debugging', 'close_session'];
break;
case 'network':
severity = 'medium';
recoverable = true;
estimatedFixTime = '1-3 minutes';
actionableSteps = [
'Check your internet connection',
'Verify the target URL is accessible',
'Try again after a brief wait',
'Check for proxy or firewall issues'
];
break;
case 'permission':
severity = 'high';
recoverable = true;
estimatedFixTime = '5-10 minutes';
actionableSteps = [
'Run the command with appropriate permissions',
'Check file and directory access rights',
'Verify system accessibility settings',
'Consider running as administrator if needed'
];
break;
case 'framework':
severity = 'medium';
recoverable = true;
estimatedFixTime = '3-10 minutes';
actionableSteps = [
'Verify your framework setup is correct',
'Check that your application is running',
'Ensure you\'re using the right debugging tools for your framework',
'Review framework-specific requirements'
];
if (toolName?.includes('nextjs')) {
relatedTools = ['nextjs_page_info', 'nextjs_config'];
}
else if (toolName?.includes('flutter')) {
relatedTools = ['flutter_widget_tree', 'flutter_quantum_interact'];
}
else if (toolName?.includes('phoenix')) {
relatedTools = ['phoenix_liveview_state_inspector', 'phoenix_liveview_compatibility_check'];
}
break;
case 'configuration':
severity = 'medium';
recoverable = true;
estimatedFixTime = '5-15 minutes';
actionableSteps = [
'Review your configuration settings',
'Check for missing required parameters',
'Validate configuration file syntax',
'Restart the service after configuration changes'
];
break;
case 'user_input':
severity = 'low';
recoverable = true;
estimatedFixTime = '1-2 minutes';
actionableSteps = [
'Check that all required parameters are provided',
'Validate parameter formats and types',
'Review the tool documentation for correct usage',
'Try with simpler or default values first'
];
break;
case 'system':
severity = lowerError.includes('critical') ? 'critical' : 'medium';
recoverable = !lowerError.includes('fatal') && !lowerError.includes('critical');
estimatedFixTime = recoverable ? '5-10 minutes' : '15-30 minutes';
actionableSteps = recoverable ? [
'Check system resources (memory, CPU, disk)',
'Restart the service if safe to do so',
'Review system logs for additional context',
'Clear temporary files and cache'
] : [
'Review system logs for root cause',
'Check for system-level issues',
'Consider restarting affected services',
'Contact system administrator if needed'
];
break;
}
return {
category,
severity,
recoverable,
actionableSteps,
relatedTools,
estimatedFixTime
};
}
static generateTroubleshooting(errorMessage, category, toolName) {
const lowerError = errorMessage.toLowerCase();
const quickFixes = [];
const diagnosticSteps = [];
const preventionTips = [];
// Category-specific quick fixes
switch (category) {
case 'session':
quickFixes.push('Run `inject_debugging` to start a fresh session', 'Check if your application is running on the expected port', 'Verify the URL is accessible in your browser manually');
diagnosticSteps.push('List active sessions to see what\'s available', 'Check browser developer console for errors', 'Verify network connectivity to your application');
preventionTips.push('Keep your application running during debugging sessions', 'Use session persistence features when available', 'Monitor session health proactively');
break;
case 'browser':
quickFixes.push('Close unnecessary browser tabs and windows', 'Clear browser cache and cookies', 'Try a different browser or incognito mode');
diagnosticSteps.push('Check available system memory', 'Look for browser process conflicts', 'Verify browser version compatibility');
preventionTips.push('Keep browsers updated to latest versions', 'Monitor system resources during debugging', 'Use browser automation best practices');
break;
case 'network':
quickFixes.push('Wait 30 seconds and try again', 'Check your internet connection', 'Try accessing the URL directly in a browser');
diagnosticSteps.push('Use network diagnostic tools (ping, traceroute)', 'Check proxy and firewall settings', 'Monitor network traffic patterns');
preventionTips.push('Use stable network connections for debugging', 'Configure appropriate timeouts for your network', 'Consider network resilience patterns');
break;
case 'framework':
if (toolName?.includes('nextjs')) {
quickFixes.push('Verify Next.js is running with `npm run dev`', 'Check that you\'re using the correct port (usually 3000)', 'Try `nextjs_config` to verify setup');
}
else if (toolName?.includes('flutter')) {
quickFixes.push('Ensure Flutter web app is running and accessible', 'Verify Flutter debugging is enabled', 'Try `flutter_widget_tree` for basic connectivity');
}
else if (toolName?.includes('phoenix')) {
quickFixes.push('Verify Phoenix server is running with `mix phx.server`', 'Check LiveView is properly configured', 'Try `phoenix_liveview_compatibility_check` first');
}
else {
quickFixes.push('Verify your framework application is running', 'Check framework-specific configuration', 'Review framework debug settings');
}
break;
}
// Error-specific quick fixes
if (lowerError.includes('not found')) {
quickFixes.unshift('Double-check spelling and parameter values');
}
if (lowerError.includes('timeout')) {
quickFixes.unshift('Try increasing timeout values or waiting longer');
}
if (lowerError.includes('permission')) {
quickFixes.unshift('Check file/system permissions and run with appropriate access');
}
return {
quickFixes: quickFixes.length > 0 ? quickFixes : ['Retry the operation after checking system status'],
diagnosticSteps: diagnosticSteps.length > 0 ? diagnosticSteps : ['Review error details and system logs'],
preventionTips: preventionTips.length > 0 ? preventionTips : ['Follow best practices for system stability']
};
}
static generateUserGuidance(errorMessage, category, toolName) {
const lowerError = errorMessage.toLowerCase();
let whatHappened = 'An error occurred while processing your request.';
let whyItHappened = 'The system encountered an unexpected condition.';
let howToFix = 'Try the suggested quick fixes above.';
let nextSteps = ['Review the error details', 'Try the suggested solutions', 'Contact support if issue persists'];
// Category-specific guidance
switch (category) {
case 'session':
whatHappened = 'Your debugging session is no longer active or cannot be found.';
whyItHappened = 'This typically happens when a session expires, the browser closes, or the application stops running.';
howToFix = 'Start a new debugging session and ensure your application remains running.';
nextSteps = [
'Use `inject_debugging` to start a fresh session',
'Verify your application is running and accessible',
'Check that the URL and port are correct'
];
break;
case 'browser':
whatHappened = 'The browser automation system encountered an issue.';
whyItHappened = 'This can occur due to browser crashes, memory issues, or automation conflicts.';
howToFix = 'Reset the browser automation environment and try again.';
nextSteps = [
'Close any unnecessary browser windows',
'Start a new debugging session',
'Check available system memory'
];
break;
case 'network':
whatHappened = 'A network communication problem prevented the operation from completing.';
whyItHappened = 'This could be due to connectivity issues, server problems, or timeout conditions.';
howToFix = 'Check your network connection and ensure the target service is accessible.';
nextSteps = [
'Verify your internet connection',
'Check if the target URL is accessible',
'Wait a moment and try again'
];
break;
case 'framework':
whatHappened = `The ${toolName?.includes('nextjs') ? 'Next.js' : toolName?.includes('flutter') ? 'Flutter' : toolName?.includes('phoenix') ? 'Phoenix' : 'framework'} debugging tool encountered an issue.`;
whyItHappened = 'This often happens when the application is not running, not configured correctly, or not compatible with the debugging tool.';
howToFix = 'Verify your application setup and ensure it\'s running properly.';
nextSteps = [
'Check that your application is running',
'Verify framework-specific configuration',
'Use basic framework tools to test connectivity'
];
break;
case 'permission':
whatHappened = 'The system lacks the necessary permissions to perform this operation.';
whyItHappened = 'This occurs when file system, network, or system permissions are insufficient.';
howToFix = 'Grant the necessary permissions and try again.';
nextSteps = [
'Check file and directory permissions',
'Verify system accessibility settings',
'Run with appropriate user privileges'
];
break;
case 'user_input':
whatHappened = 'The provided input parameters are invalid or incomplete.';
whyItHappened = 'This happens when required parameters are missing, have wrong types, or invalid values.';
howToFix = 'Review and correct the input parameters based on the tool documentation.';
nextSteps = [
'Check that all required parameters are provided',
'Validate parameter formats and values',
'Refer to tool documentation for examples'
];
break;
case 'configuration':
whatHappened = 'A configuration problem prevented the operation from completing.';
whyItHappened = 'This typically occurs due to missing settings, invalid configuration values, or setup issues.';
howToFix = 'Review and correct your configuration settings.';
nextSteps = [
'Check configuration file syntax and values',
'Ensure all required settings are present',
'Restart services after configuration changes'
];
break;
}
// Error-specific refinements
if (lowerError.includes('not found')) {
whatHappened = whatHappened.replace('encountered an issue', 'could not find the requested resource');
whyItHappened = 'The specified item (session, file, or endpoint) does not exist or is not accessible.';
}
if (lowerError.includes('timeout')) {
whatHappened = whatHappened.replace('encountered an issue', 'timed out waiting for a response');
whyItHappened = 'The operation took longer than expected, possibly due to network issues or system load.';
}
return {
whatHappened,
whyItHappened,
howToFix,
nextSteps
};
}
static createEnhancedMessage(originalError, context) {
const severityEmoji = {
'low': 'š”',
'medium': 'ā ļø',
'high': 'ā',
'critical': 'šØ'
}[context.severity];
const categoryDescription = {
'session': 'Session Management',
'browser': 'Browser Automation',
'network': 'Network Communication',
'framework': 'Framework Integration',
'permission': 'System Permissions',
'user_input': 'Input Validation',
'configuration': 'Configuration',
'system': 'System Error'
}[context.category];
return `${severityEmoji} ${categoryDescription} Error: ${originalError}`;
}
/**
* Enhanced error response for common tool patterns
*/
static createToolErrorResponse(toolName, error, sessionId) {
return this.createActionableErrorResponse(error, toolName, sessionId);
}
/**
* Enhanced session error response
*/
static createSessionErrorResponse(sessionId, error) {
const defaultError = `Debug session ${sessionId} not found or unavailable`;
return this.createActionableErrorResponse(error || defaultError, 'Session Management', sessionId);
}
/**
* Enhanced framework error response
*/
static createFrameworkErrorResponse(framework, error, toolName) {
const frameworkError = `${framework} integration error: ${error instanceof Error ? error.message : error}`;
return this.createActionableErrorResponse(frameworkError, toolName);
}
}
//# sourceMappingURL=enhanced-error-context.js.map