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
333 lines โข 15.2 kB
JavaScript
/**
* AI-Debug v2 Server - Architectural Rebuild with Advanced Stability Monitoring
*
* This is the new server architecture that addresses all the fundamental
* reliability issues through:
* - Stateless design and connection-agnostic transport
* - Advanced stability monitoring and circuit breakers
* - HTTP-first architecture with real-time health tracking
* - Automatic recovery and performance optimization
*/
import { HttpMcpTransport } from './transport/http-mcp-transport.js';
import { StatelessDebugService } from './core/stateless-debug-service.js';
import { StartupAwareMemoryManager } from './utils/startup-aware-memory-manager.js';
import { AdvancedMemoryManager } from './utils/advanced-memory-manager.js';
import { V2SessionRegistry } from './session/v2-session-registry.js';
import { V2StabilityMonitor } from './stability/v2-stability-monitor.js';
// Process supervision with comprehensive stability monitoring
class ProcessSupervisor {
httpTransport;
debugService;
sessionRegistry;
stabilityMonitor;
healthCheckInterval = null;
performanceInterval = null;
isShuttingDown = false;
startupAwareMemoryManager;
advancedMemoryManager;
startTime = Date.now();
constructor() {
this.httpTransport = new HttpMcpTransport(8081);
this.startupAwareMemoryManager = new StartupAwareMemoryManager();
this.advancedMemoryManager = AdvancedMemoryManager.getInstance();
// Initialize session registry
this.sessionRegistry = new V2SessionRegistry({
basePort: 8200,
defaultQuotas: {
maxConcurrentSessions: 10,
maxMemoryMB: 1024,
maxBrowserInstances: 5,
maxIdleTimeMinutes: 15,
maxTempDirectorySizeMB: 100,
maxHttpRequestsPerMinute: 200
}
});
// Initialize stability monitor with enhanced configuration
const stabilityConfig = {
monitoringIntervalMs: 15000, // More frequent monitoring for v2
healthCheckIntervalMs: 30000,
circuitBreaker: {
failureThreshold: 3, // Lower threshold for faster detection
recoveryTimeoutMs: 30000,
halfOpenMaxAttempts: 2,
successThreshold: 2
},
alerts: {
cpuThreshold: 75,
memoryThresholdMB: 400,
errorRateThreshold: 0.03,
responseTimeThreshold: 3000,
diskUsageThreshold: 80
},
autoRecovery: {
enabled: true,
maxAttempts: 5,
cooldownMs: 180000,
criticalOnlyMode: false
},
httpTransport: {
maxConnectionsPerSession: 8,
requestTimeoutMs: 25000,
retryAttempts: 2,
rateLimit: {
windowMs: 60000,
maxRequests: 150
}
}
};
this.stabilityMonitor = new V2StabilityMonitor(this.sessionRegistry, this.advancedMemoryManager, stabilityConfig);
this.debugService = new StatelessDebugService();
this.setupProcessHandlers();
this.setupStabilityEventHandlers();
}
setupProcessHandlers() {
// Graceful shutdown handlers
process.on('SIGTERM', () => this.gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => this.gracefulShutdown('SIGINT'));
// Error handlers that don't crash the process
process.on('uncaughtException', (error) => {
console.error('๐จ V2 Uncaught Exception:', error);
this.stabilityMonitor.recordComponentFailure('process_supervision', error.message);
// Don't crash - log and continue with circuit breaker protection
});
process.on('unhandledRejection', (reason, promise) => {
console.error('๐จ V2 Unhandled Rejection at:', promise, 'reason:', reason);
this.stabilityMonitor.recordComponentFailure('promise_handling', String(reason));
// Don't crash - log and continue
});
// Memory monitoring
process.on('warning', (warning) => {
console.warn('โ ๏ธ V2 Process Warning:', warning.message);
if (warning.name === 'MaxListenersExceededWarning') {
this.stabilityMonitor.recordComponentFailure('event_listeners', warning.message);
}
});
// Exit handlers
process.on('exit', (code) => {
console.error(`๐ V2 Process exiting with code: ${code}`);
});
}
setupStabilityEventHandlers() {
// Handle stability events
this.stabilityMonitor.on('stability_event', (event) => {
if (event.level === 'critical') {
console.error(`๐จ V2 Critical stability event: ${event.type}`, event.data);
}
else if (event.level === 'warning') {
console.warn(`โ ๏ธ V2 Stability warning: ${event.type}`, event.data);
}
});
// Handle health reports
this.stabilityMonitor.on('health_report', (report) => {
if (report.overallHealth === 'critical' || report.overallHealth === 'unhealthy') {
console.error(`๐ฅ V2 Health status: ${report.overallHealth}`, {
recommendations: report.recommendations,
recoverySuggestions: report.recoverySuggestions.length
});
}
});
// Handle alerts
this.stabilityMonitor.on('alert', (alert) => {
const icon = alert.level === 'critical' ? '๐จ' : alert.level === 'warning' ? 'โ ๏ธ' : 'โน๏ธ';
console.log(`${icon} V2 Alert [${alert.level.toUpperCase()}]: ${alert.message}`);
});
}
async start() {
try {
console.error('๐ Starting AI-Debug v2 Server with Advanced Stability Monitoring...');
console.error('๐ Architecture: Stateless + HTTP Transport + Circuit Breakers');
console.error('๐ก๏ธ Features: Real-time monitoring, auto-recovery, performance tracking');
console.error('๐ฏ Goal: Zero crashes, comprehensive observability, automatic healing');
// Record startup success
this.stabilityMonitor.recordComponentSuccess('server_startup');
// Start HTTP transport
console.error('๐ Starting HTTP MCP transport...');
await this.httpTransport.start();
this.stabilityMonitor.recordComponentSuccess('http_transport');
// Initialize debug service
console.error('๐ง Initializing stateless debug service...');
await this.debugService.initialize();
this.stabilityMonitor.recordComponentSuccess('debug_service');
// Start health monitoring with enhanced intervals
this.startHealthMonitoring();
// Start performance monitoring
this.startPerformanceMonitoring();
const uptime = Date.now() - this.startTime;
console.error(`โ
V2 Server started successfully in ${uptime}ms`);
console.error('๐ Advanced stability monitoring active');
console.error('๐ Real-time health tracking enabled');
console.error('๐ Auto-recovery systems online');
console.error('๐ก๏ธ Circuit breakers protecting all critical components');
// Log stability metrics summary
const metrics = this.stabilityMonitor.getStabilityMetrics();
console.error('๐ Initial metrics:', {
httpRequests: metrics.httpTransport.requestsPerSecond,
availability: metrics.performanceIndicators.availability,
reliability: metrics.performanceIndicators.reliability,
healthyTools: metrics.toolReliability.healthyTools
});
}
catch (error) {
console.error('โ V2 Server startup failed:', error);
this.stabilityMonitor.recordComponentFailure('server_startup', error.message);
await this.stabilityMonitor.emergencyRecovery('startup_failure');
throw error;
}
}
startHealthMonitoring() {
this.healthCheckInterval = setInterval(async () => {
try {
await this.performHealthCheck();
this.stabilityMonitor.recordComponentSuccess('health_monitoring');
}
catch (error) {
console.error('โ V2 Health check failed:', error);
this.stabilityMonitor.recordComponentFailure('health_monitoring', error.message);
}
}, 30000); // Every 30 seconds
}
startPerformanceMonitoring() {
this.performanceInterval = setInterval(async () => {
try {
await this.performPerformanceCheck();
this.stabilityMonitor.recordComponentSuccess('performance_monitoring');
}
catch (error) {
console.error('โ V2 Performance check failed:', error);
this.stabilityMonitor.recordComponentFailure('performance_monitoring', error.message);
}
}, 60000); // Every minute
}
async performHealthCheck() {
const metrics = this.stabilityMonitor.getStabilityMetrics();
const systemHealth = this.stabilityMonitor.getSystemHealthOverview();
// Check if HTTP transport is responsive
const transportCheck = this.stabilityMonitor.canExecuteComponent('http_transport');
if (!transportCheck.allowed) {
console.warn(`โ ๏ธ HTTP transport unavailable: ${transportCheck.reason}`);
}
// Check memory pressure
if (metrics.systemResources.memoryUsageMB > 400) {
console.warn(`๐ง High memory usage: ${metrics.systemResources.memoryUsageMB.toFixed(1)}MB`);
await this.advancedMemoryManager.triggerEmergencyCleanup('high_memory_usage');
}
// Check session health
const resourceSummary = this.sessionRegistry.getResourceSummary();
if (resourceSummary.quotaUtilization > 85) {
console.warn(`๐ High resource utilization: ${resourceSummary.quotaUtilization.toFixed(1)}%`);
await this.sessionRegistry.performCleanup();
}
// Log health summary every 5 minutes
if (Math.floor(Date.now() / 1000) % 300 === 0) {
console.error('๐ V2 Health Summary:', {
uptime: Math.floor(systemHealth.uptime),
memory: `${metrics.systemResources.memoryUsageMB.toFixed(1)}MB`,
cpu: `${metrics.systemResources.cpuUsagePercent.toFixed(1)}%`,
availability: `${metrics.performanceIndicators.availability.toFixed(1)}%`,
activeSessions: metrics.sessionHealth.activeSessions,
healthyTools: `${metrics.toolReliability.healthyTools}/${metrics.toolReliability.totalTools}`
});
}
}
async performPerformanceCheck() {
const healthReport = this.stabilityMonitor.getHealthReport();
if (healthReport) {
// Check for performance degradation
if (healthReport.overallHealth === 'degraded') {
console.warn('โก V2 Performance degraded - implementing optimizations');
// Trigger optimization actions
if (healthReport.recoverySuggestions.length > 0) {
for (const suggestion of healthReport.recoverySuggestions.slice(0, 2)) {
if (suggestion.autoExecutable) {
console.error(`๐ค Auto-executing: ${suggestion.description}`);
}
}
}
}
// Log performance trends
if (healthReport.trends.length > 0) {
console.error('๐ V2 Performance trends:', healthReport.trends.slice(0, 3));
}
}
}
async gracefulShutdown(signal) {
if (this.isShuttingDown) {
console.error('๐ V2 Shutdown already in progress...');
return;
}
this.isShuttingDown = true;
console.error(`๐ V2 Graceful shutdown initiated (${signal})`);
try {
// Stop monitoring intervals
if (this.healthCheckInterval) {
clearInterval(this.healthCheckInterval);
}
if (this.performanceInterval) {
clearInterval(this.performanceInterval);
}
// Shutdown stability monitor
console.error('๐ก๏ธ Shutting down stability monitor...');
await this.stabilityMonitor.shutdown();
// Shutdown session registry
console.error('๐ Shutting down session registry...');
await this.sessionRegistry.shutdown();
// Shutdown HTTP transport
console.error('๐ Shutting down HTTP transport...');
await this.httpTransport.stop();
// Shutdown debug service
console.error('๐ง Shutting down debug service...');
await this.debugService.cleanup();
// Final memory cleanup
console.error('๐งน Final memory cleanup...');
await this.advancedMemoryManager.triggerEmergencyCleanup('shutdown');
const totalUptime = Date.now() - this.startTime;
console.error(`โ
V2 Graceful shutdown completed in ${Date.now() - this.startTime}ms`);
console.error(`๐ Total uptime: ${Math.floor(totalUptime / 1000)}s`);
process.exit(0);
}
catch (error) {
console.error('โ V2 Error during shutdown:', error);
process.exit(1);
}
}
/**
* Get comprehensive server status
*/
getStatus() {
return {
server: {
uptime: Date.now() - this.startTime,
version: 'v2.0.0-stability',
architecture: 'stateless-http',
status: this.isShuttingDown ? 'shutting_down' : 'running'
},
stability: this.stabilityMonitor.getStabilityMetrics(),
health: this.stabilityMonitor.getHealthReport(),
sessions: this.sessionRegistry.getResourceSummary(),
memory: this.advancedMemoryManager.getMemoryStats()
};
}
}
// Main execution with enhanced error handling
async function main() {
const supervisor = new ProcessSupervisor();
try {
await supervisor.start();
// Keep the process alive and responsive
process.stdin.resume();
}
catch (error) {
console.error('๐ฅ V2 Fatal error during startup:', error);
process.exit(1);
}
}
// Start the server with proper error boundaries
if (import.meta.url === `file://${process.argv[1]}`) {
main().catch((error) => {
console.error('๐ฅ V2 Unhandled startup error:', error);
process.exit(1);
});
}
export { ProcessSupervisor };
//# sourceMappingURL=server-v2.js.map