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
332 lines (329 loc) ⢠14.1 kB
JavaScript
// Performance Profiling Handler - AI Debug MCP Integration
// Enterprise-grade performance analysis with revolutionary debugging capabilities
// Target: <300 lines with comprehensive profiling tools
import { PerformanceProfiler } from '../performance-profiler.js';
import { BaseToolHandler } from './base-handler.js';
export class PerformanceProfilingHandler extends BaseToolHandler {
profiler;
constructor() {
super();
this.profiler = new PerformanceProfiler();
}
tools = [
{
name: 'performance_baseline',
description: 'Establish comprehensive performance baseline measurements',
inputSchema: {
type: 'object',
properties: {
includeMemory: { type: 'boolean', default: true },
includeTools: { type: 'boolean', default: true },
includeHandlers: { type: 'boolean', default: true }
}
}
},
{
name: 'performance_profile',
description: 'Profile system performance and identify bottlenecks',
inputSchema: {
type: 'object',
properties: {
component: { type: 'string', enum: ['startup', 'memory', 'tools', 'handlers', 'tests', 'all'], default: 'all' },
depth: { type: 'string', enum: ['basic', 'detailed', 'comprehensive'], default: 'detailed' }
}
}
},
{
name: 'performance_optimize',
description: 'Generate optimization recommendations and implementation plan',
inputSchema: {
type: 'object',
properties: {
priority: { type: 'string', enum: ['immediate', 'medium', 'long-term', 'all'], default: 'all' },
includeImplementation: { type: 'boolean', default: true }
}
}
},
{
name: 'performance_validate',
description: 'Validate performance improvements against baseline',
inputSchema: {
type: 'object',
properties: {
beforeMetrics: { type: 'object' },
afterMetrics: { type: 'object' },
component: { type: 'string', default: 'overall' }
},
required: ['beforeMetrics', 'afterMetrics']
}
},
{
name: 'performance_monitor',
description: 'Start real-time performance monitoring with AI Debug MCP',
inputSchema: {
type: 'object',
properties: {
duration: { type: 'number', default: 60 },
interval: { type: 'number', default: 5 },
captureVisuals: { type: 'boolean', default: true }
}
}
},
{
name: 'performance_report',
description: 'Generate comprehensive enterprise performance report',
inputSchema: {
type: 'object',
properties: {
format: { type: 'string', enum: ['executive', 'technical', 'comprehensive'], default: 'comprehensive' },
includeTrends: { type: 'boolean', default: true },
includeRecommendations: { type: 'boolean', default: true }
}
}
}
];
async handle(name, args, sessions) {
try {
switch (name) {
case 'performance_baseline':
return await this.establishBaseline(args);
case 'performance_profile':
return await this.profilePerformance(args);
case 'performance_optimize':
return await this.generateOptimizations(args);
case 'performance_validate':
return await this.validateImprovements(args);
case 'performance_monitor':
return await this.startMonitoring(args);
case 'performance_report':
return await this.generateReport(args);
default:
throw new Error(`Unknown performance tool: ${name}`);
}
}
catch (error) {
console.error(`Performance profiling error in ${name}:`, error);
return this.createErrorResponse(error);
}
}
async establishBaseline(args) {
const baseline = {
timestamp: new Date().toISOString(),
startup: args.includeStartup !== false ? await this.profiler.measureStartupTime() : null,
memory: args.includeMemory !== false ? await this.profiler.profileMemoryUsage() : null,
tools: args.includeTools !== false ? await this.profiler.measureToolResponseTimes() : null,
handlers: args.includeHandlers !== false ? await this.profiler.profileHandlers() : null
};
const summary = this.generateBaselineSummary(baseline);
const content = `# š Performance Baseline Established
## Summary
${summary.join('\n')}
## Recommendations
š Baseline established successfully
šÆ Use performance_profile for detailed analysis
ā” Run performance_optimize for improvement recommendations
## Details
- **Timestamp**: ${baseline.timestamp}
- **Components Measured**: ${[baseline.startup, baseline.memory, baseline.tools, baseline.handlers].filter(c => c !== null).length}`;
return this.createTextResponse(content);
}
async profilePerformance(args) {
const { component = 'all', depth = 'detailed' } = args;
const profile = {
timestamp: new Date().toISOString(),
component,
depth
};
if (component === 'all' || component === 'startup') {
profile.startup = await this.profiler.measureStartupTime();
}
if (component === 'all' || component === 'memory') {
profile.memory = await this.profiler.profileMemoryUsage();
}
if (component === 'all' || component === 'tools') {
profile.tools = await this.profiler.measureToolResponseTimes();
}
if (component === 'all' || component === 'handlers') {
profile.handlers = await this.profiler.profileHandlers();
}
if (component === 'all' || component === 'tests') {
profile.tests = await this.profiler.analyzeTestPerformance();
}
const bottlenecks = await this.profiler.identifyBottlenecks();
const analysis = this.generateProfileAnalysis(profile, bottlenecks);
return {
success: true,
profile,
bottlenecks,
analysis,
nextSteps: [
'š Review identified bottlenecks',
'ā” Run performance_optimize for solutions',
'š Use performance_monitor for real-time tracking'
]
};
}
async generateOptimizations(args) {
const { priority = 'all', includeImplementation = true } = args;
const optimizationPlan = await this.profiler.generateOptimizationPlan();
const targets = await this.profiler.establishPerformanceTargets();
let filteredPlan = optimizationPlan;
if (priority !== 'all') {
// Filter based on priority
filteredPlan = {
...optimizationPlan,
immediateActions: priority === 'immediate' ? optimizationPlan.immediateActions : [],
mediumTermGoals: priority === 'medium' ? optimizationPlan.mediumTermGoals : [],
longTermTargets: priority === 'long-term' ? optimizationPlan.longTermTargets : []
};
}
const implementation = includeImplementation ? this.generateImplementationGuide(filteredPlan) : null;
return {
success: true,
targets,
optimizationPlan: filteredPlan,
implementation,
summary: {
totalActions: filteredPlan.immediateActions.length + filteredPlan.mediumTermGoals.length + filteredPlan.longTermTargets.length,
estimatedImpact: filteredPlan.estimatedImpact,
priority
}
};
}
async validateImprovements(args) {
const { beforeMetrics, afterMetrics, component = 'overall' } = args;
const improvement = await this.profiler.validateImprovement(beforeMetrics, afterMetrics);
const analysis = this.generateImprovementAnalysis(improvement, component);
return {
success: true,
improvement,
analysis,
verdict: improvement.overallScore > 20 ? 'significant' : improvement.overallScore > 10 ? 'moderate' : 'minimal',
recommendations: this.generateValidationRecommendations(improvement)
};
}
async startMonitoring(args) {
const { duration = 60, interval = 5, captureVisuals = true } = args;
const session = await this.profiler.createDebugSession();
const visuals = captureVisuals ? await this.profiler.capturePerformanceVisuals() : null;
return {
success: true,
session,
monitoring: {
duration,
interval,
startTime: new Date().toISOString(),
visualCapture: captureVisuals
},
visuals,
instructions: [
'š Performance monitoring active',
`ā±ļø Duration: ${duration} seconds with ${interval}s intervals`,
'š Use performance_report to view results'
]
};
}
async generateReport(args) {
const { format = 'comprehensive', includeTrends = true, includeRecommendations = true } = args;
const report = await this.profiler.generatePerformanceReport();
const trends = includeTrends ? await this.profiler.trackPerformanceTrends() : null;
let formattedReport;
switch (format) {
case 'executive':
formattedReport = this.formatExecutiveReport(report);
break;
case 'technical':
formattedReport = this.formatTechnicalReport(report);
break;
default:
formattedReport = report;
}
return {
success: true,
report: formattedReport,
trends,
format,
summary: {
overallScore: report.executiveSummary.overallScore,
keyFindings: report.executiveSummary.keyFindings.length,
recommendations: includeRecommendations ? report.executiveSummary.recommendations : []
}
};
}
// Helper methods for analysis and formatting
generateBaselineSummary(baseline) {
const summary = [];
if (baseline.startup) {
summary.push(`š Startup time: ${Math.round(baseline.startup.startupTime)}ms`);
}
if (baseline.memory) {
summary.push(`š¾ Memory usage: ${Math.round(baseline.memory.heapUsed / 1024 / 1024)}MB`);
}
if (baseline.tools) {
summary.push(`š ļø Average tool response: ${Math.round(baseline.tools.averageResponseTime)}ms`);
}
return summary;
}
generateProfileAnalysis(profile, bottlenecks) {
return {
performance: bottlenecks.priorityScore > 80 ? 'needs attention' : bottlenecks.priorityScore > 60 ? 'acceptable' : 'good',
criticalIssues: bottlenecks.criticalIssues.length,
optimizationPotential: bottlenecks.optimizationOpportunities.reduce((sum, op) => sum + op.potential, 0)
};
}
generateImplementationGuide(plan) {
return {
quickWins: plan.immediateActions.slice(0, 3),
stepByStep: plan.immediateActions.map((action, index) => ({
step: index + 1,
action: action.action,
effort: action.effort,
impact: `${action.impact}% improvement`,
priority: action.priority
})),
timeline: '2-4 weeks for immediate actions'
};
}
generateImprovementAnalysis(improvement, component) {
return {
component,
significantImprovements: [
improvement.startupImprovement > 20 ? 'Startup time' : null,
improvement.memoryImprovement > 15 ? 'Memory usage' : null,
improvement.responseImprovement > 25 ? 'Tool response' : null
].filter(Boolean),
overallTrend: improvement.overallScore > 20 ? 'improving' : 'stable'
};
}
generateValidationRecommendations(improvement) {
const recommendations = [];
if (improvement.overallScore > 30) {
recommendations.push('š Excellent improvements achieved!');
}
if (improvement.startupImprovement < 10) {
recommendations.push('ā” Consider additional startup optimizations');
}
if (improvement.memoryImprovement < 5) {
recommendations.push('š¾ Memory usage could be further optimized');
}
return recommendations;
}
formatExecutiveReport(report) {
return {
summary: report.executiveSummary,
scorecard: {
performance: report.executiveSummary.overallScore,
grade: report.executiveSummary.overallScore > 80 ? 'A' : report.executiveSummary.overallScore > 60 ? 'B' : 'C'
},
topPriorities: report.executiveSummary.recommendations.slice(0, 3)
};
}
formatTechnicalReport(report) {
return {
metrics: report.detailedMetrics,
bottlenecks: report.recommendations.immediateActions,
implementation: report.recommendations
};
}
}
//# sourceMappingURL=performance-profiling-handler.js.map