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
252 lines • 11.1 kB
JavaScript
import { BaseToolHandler } from './base-handler.js';
export class AnalysisHandler extends BaseToolHandler {
cloudService;
localEngine;
apiKeyManager;
tools = [
{
name: 'analyze_with_ai',
description: 'Get revolutionary AI insights about your application.',
inputSchema: {
type: 'object',
properties: {
sessionId: {
type: 'string',
description: 'Debug session ID'
},
analysisType: {
type: 'string',
enum: ['performance', 'ux', 'accessibility', 'security', 'comprehensive'],
description: 'Type of AI analysis',
default: 'comprehensive'
}
},
required: ['sessionId']
}
},
{
name: 'get_debug_report',
description: 'Generate comprehensive debugging report with AI-enhanced insights and recommendations.',
inputSchema: {
type: 'object',
properties: {
sessionId: {
type: 'string',
description: 'Debug session ID'
},
includeAI: {
type: 'boolean',
description: 'Include AI analysis (requires API key)',
default: false
}
},
required: ['sessionId']
}
}
];
constructor(cloudService, localEngine, apiKeyManager) {
super();
this.cloudService = cloudService;
this.localEngine = localEngine;
this.apiKeyManager = apiKeyManager;
}
getTools() {
return this.tools;
}
async handle(toolName, args, sessions) {
try {
const session = this.getSession(args.sessionId, sessions);
switch (toolName) {
case 'analyze_with_ai':
return await this.analyzeWithAI(args, session);
case 'get_debug_report':
return await this.getDebugReport(args, session);
default:
return this.createErrorResponse(new Error(`Unknown tool: ${toolName}`));
}
}
catch (error) {
return this.createErrorResponse(error);
}
}
async analyzeWithAI(args, session) {
try {
// Freemium restrictions removed - all users get full AI analysis
const analysisType = args.analysisType || 'comprehensive';
// Capture page state and DOM snapshot
const pageState = await this.localEngine.extractPageState(session.page);
const domSnapshot = await this.localEngine.captureDOMSnapshot();
// Prepare analysis request
const analysisRequest = {
sessionId: session.id,
url: await session.page.url(),
title: await session.page.title(),
analysisType,
pageState,
domSnapshot,
events: session.events || [],
timestamp: Date.now()
};
// Perform AI analysis
const result = await this.cloudService.comprehensiveAnalysis(session.events || [], pageState, analysisType);
// Format the response
let report = `# 🤖 AI Analysis Results\n\n`;
report += `**Analysis Type**: ${this.formatAnalysisType(analysisType)}\n`;
report += `**URL**: ${await session.page.url()}\n`;
// Handle various result formats from comprehensiveAnalysis
const score = result.score || result.confidence || 75;
report += `**Performance Score**: ${score}/100\n\n`;
// Process insights from various possible fields
const insights = result.insights || result.issues || [];
if (insights.length > 0) {
report += `## 💡 Insights\n\n`;
insights.forEach((insight) => {
if (typeof insight === 'string') {
report += `- ${insight}\n`;
}
else {
const emoji = this.getSeverityEmoji(insight.severity || 'medium');
const type = insight.type || 'general';
const message = insight.message || insight.description || insight.issue || '';
report += `${emoji} **${this.formatInsightType(type)}**: ${message}\n`;
}
});
report += '\n';
}
// Process recommendations
const recommendations = result.recommendations || result.suggestions || [];
if (recommendations.length > 0) {
report += `## 📋 Recommendations\n\n`;
recommendations.forEach((rec, index) => {
const recText = typeof rec === 'string' ? rec : (rec.text || rec.recommendation || rec.suggestion || '');
report += `${index + 1}. ${recText}\n`;
});
report += '\n';
}
report += `_Generated with AI-powered analysis. Results may vary based on page state._`;
return this.createTextResponse(report);
}
catch (error) {
throw new Error(`Failed to analyze with AI: ${error instanceof Error ? error.message : error}`);
}
}
async getDebugReport(args, session) {
try {
const includeAI = true; // Always include AI analysis - freemium restrictions removed
let report = `# 🐛 Debug Report\n\n`;
report += `## Session Information\n`;
report += `- **Session ID**: ${session.id}\n`;
report += `- **URL**: ${await session.page.url()}\n`;
report += `- **Title**: ${await session.page.title()}\n`;
const startTime = session.startTime || session.timestamp;
report += `- **Started**: ${this.formatTimestamp(startTime)}\n`;
report += `- **Duration**: ${Date.now() - startTime.getTime()}ms\n\n`;
// Events summary
const events = session.events || [];
report += `## Events Summary\n`;
report += `- **Events Captured**: ${events.length}\n`;
if (events.length > 0) {
const eventTypes = events.reduce((acc, event) => {
acc[event.type] = (acc[event.type] || 0) + 1;
return acc;
}, {});
Object.entries(eventTypes).forEach(([type, count]) => {
report += ` - ${type}: ${count}\n`;
});
}
report += '\n';
// Console logs summary
const consoleMessages = this.localEngine.getConsoleMessages();
report += `## Console Logs\n`;
report += `- **Total Logs**: ${consoleMessages.length}\n`;
if (consoleMessages.length > 0) {
const logTypes = consoleMessages.reduce((acc, msg) => {
acc[msg.type] = (acc[msg.type] || 0) + 1;
return acc;
}, {});
Object.entries(logTypes).forEach(([type, count]) => {
report += ` - ${type}: ${count}\n`;
});
// Show recent errors
const errors = consoleMessages.filter((msg) => msg.type === 'error').slice(-3);
if (errors.length > 0) {
report += `\n### Recent Errors\n`;
errors.forEach((error) => {
report += `- ${error.text}\n`;
});
}
}
report += '\n';
// Include AI analysis if requested and available
if (includeAI) {
report += `## 🤖 AI Analysis\n\n`;
try {
const pageState = await this.localEngine.extractPageState(session.page);
const aiResult = await this.cloudService.comprehensiveAnalysis(events, pageState, 'comprehensive');
const score = aiResult.score || aiResult.confidence || 75;
report += `**Score**: ${score}/100\n\n`;
const insights = aiResult.insights || aiResult.issues || [];
if (insights.length > 0) {
report += `### Key Insights\n`;
insights.slice(0, 3).forEach((insight) => {
const message = typeof insight === 'string' ? insight :
(insight.message || insight.description || insight.issue || '');
report += `- ${message}\n`;
});
report += '\n';
}
const recommendations = aiResult.recommendations || aiResult.suggestions || [];
if (recommendations.length > 0) {
report += `### Top Recommendations\n`;
recommendations.slice(0, 3).forEach((rec) => {
const recText = typeof rec === 'string' ? rec :
(rec.text || rec.recommendation || rec.suggestion || '');
report += `- ${recText}\n`;
});
}
}
catch (aiError) {
report += `_AI analysis failed: ${aiError instanceof Error ? aiError.message : 'Unknown error'}_\n`;
}
}
report += `\n---\n_Report generated at ${new Date().toISOString()}_`;
return this.createTextResponse(report);
}
catch (error) {
throw new Error(`Failed to generate debug report: ${error instanceof Error ? error.message : error}`);
}
}
formatAnalysisType(type) {
const types = {
performance: 'Performance Analysis',
ux: 'User Experience Analysis',
accessibility: 'Accessibility Analysis',
security: 'Security Analysis',
comprehensive: 'Comprehensive Analysis'
};
return types[type] || type;
}
formatInsightType(type) {
const types = {
performance: 'Performance',
ux: 'UX',
accessibility: 'Accessibility',
security: 'Security',
general: 'General'
};
return types[type] || type;
}
getSeverityEmoji(severity) {
const emojis = {
critical: '🔴',
high: '🟠',
medium: '🟡',
low: '🟢'
};
return emojis[severity] || '⚪';
}
formatTimestamp(date) {
return date.toISOString().replace('T', ' ').slice(0, 19);
}
}
//# sourceMappingURL=analysis-handler.js.map