#!/usr/bin/env node
/**
* Debugger MCP Server
*
* A comprehensive development companion tool that provides real-time debugging,
* code quality monitoring, and AI-enhanced insights for React/Next.js applications.
*
* Features:
* - Traditional debugging (errors, breakpoints, variables, call stack)
* - Real-time code quality monitoring (complexity, rules, patterns)
* - Performance tracking (renders, memory, network)
* - AI-enhanced analysis (categorization, pattern detection, trends)
* - React/Next.js specific monitoring (components, hooks, SSR, hydration)
*/
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { DebuggerCore } from "./core/DebuggerCore.js";
import { ConfigManager } from "./config/ConfigManager.js";
import { Logger } from "./utils/Logger.js";
const logger = new Logger("DebuggerMCP");
/**
* Main MCP Server instance
*/
const server = new McpServer({
name: "debugger-mcp-server",
version: "1.0.0"
});
/**
* Initialize the debugger core and configuration
*/
async function initializeServer() {
try {
logger.info("Initializing Debugger MCP Server...");
// Initialize configuration manager
const configManager = new ConfigManager();
await configManager.initialize();
// Initialize debugger core
const debuggerCore = new DebuggerCore(configManager);
await debuggerCore.initialize();
// Register MCP tools
await registerTools(debuggerCore);
// Register MCP resources
await registerResources(debuggerCore);
logger.info("Debugger MCP Server initialized successfully");
return { debuggerCore, configManager };
} catch (error) {
logger.error("Failed to initialize server:", error);
throw error;
}
}
/**
* Register MCP tools for debugging operations
*/
async function registerTools(debuggerCore: DebuggerCore) {
// Get current debugging session info
server.registerTool(
"get-debug-session",
{
title: "Get Debug Session",
description: "Get current debugging session information",
inputSchema: {}
},
async () => {
const session = await debuggerCore.getDebugSession();
return {
content: [{
type: "text",
text: JSON.stringify(session, null, 2)
}]
};
}
);
// Get real-time errors
server.registerTool(
"get-errors",
{
title: "Get Errors",
description: "Get current errors and exceptions",
inputSchema: {
severity: z.enum(["error", "warning", "info"]).optional(),
timeframe: z.string().optional().describe("Time range like '1h', '30m', '5m'")
}
},
async ({ severity, timeframe }) => {
const errors = await debuggerCore.getErrors({ severity, timeframe });
return {
content: [{
type: "text",
text: JSON.stringify(errors, null, 2)
}]
};
}
);
// Get code quality violations
server.registerTool(
"get-violations",
{
title: "Get Code Quality Violations",
description: "Get current code quality rule violations",
inputSchema: {
severity: z.enum(["error", "warning", "info"]).optional(),
filePath: z.string().optional()
}
},
async ({ severity, filePath }) => {
const violations = await debuggerCore.getViolations({ severity, filePath });
return {
content: [{
type: "text",
text: JSON.stringify(violations, null, 2)
}]
};
}
);
// Analyze file complexity
server.registerTool(
"analyze-complexity",
{
title: "Analyze File Complexity",
description: "Analyze complexity metrics for a specific file",
inputSchema: {
filePath: z.string().describe("Path to the file to analyze")
}
},
async ({ filePath }) => {
const analysis = await debuggerCore.analyzeComplexity(filePath);
return {
content: [{
type: "text",
text: JSON.stringify(analysis, null, 2)
}]
};
}
);
// Get performance metrics
server.registerTool(
"get-performance",
{
title: "Get Performance Metrics",
description: "Get current performance metrics and insights",
inputSchema: {
timeframe: z.string().optional().describe("Time range like '1h', '30m', '5m'"),
type: z.enum(['cpu', 'memory', 'network', 'render']).optional().describe("Type of metrics to retrieve"),
limit: z.number().optional().describe("Maximum number of metrics to return")
}
},
async ({ timeframe, type, limit }) => {
const metrics = await debuggerCore.getPerformanceMetrics({ timeframe, type, limit });
return {
content: [{
type: "text",
text: JSON.stringify(metrics, null, 2)
}]
};
}
);
// Start CPU profiling
server.registerTool(
"start-cpu-profiling",
{
title: "Start CPU Profiling",
description: "Start CPU profiling to analyze performance bottlenecks and generate flame graphs",
inputSchema: {
title: z.string().optional().describe("Optional title for the profiling session")
}
},
async ({ title }) => {
try {
const profileId = await debuggerCore.startCPUProfiling(title);
return {
content: [{
type: "text",
text: JSON.stringify({
success: true,
profileId,
message: `CPU profiling started with ID: ${profileId}`
}, null, 2)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
}, null, 2)
}]
};
}
}
);
// Stop CPU profiling
server.registerTool(
"stop-cpu-profiling",
{
title: "Stop CPU Profiling",
description: "Stop CPU profiling and get the profile data with flame graph",
inputSchema: {
profileId: z.string().describe("Profile ID returned from start-cpu-profiling")
}
},
async ({ profileId }) => {
try {
const profile = await debuggerCore.stopCPUProfiling(profileId);
return {
content: [{
type: "text",
text: JSON.stringify({
success: true,
profile: {
id: profile.id,
title: profile.title,
duration: profile.duration,
startTime: profile.startTime,
endTime: profile.endTime,
flameGraphNodes: profile.flameGraph?.length || 0
},
message: `CPU profiling completed. Duration: ${profile.duration}ms`
}, null, 2)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
}, null, 2)
}]
};
}
}
);
// Get memory snapshots
server.registerTool(
"get-memory-snapshots",
{
title: "Get Memory Snapshots",
description: "Get memory usage snapshots for leak detection and analysis",
inputSchema: {
limit: z.number().optional().describe("Maximum number of snapshots to return")
}
},
async ({ limit }) => {
const snapshots = await debuggerCore.getMemorySnapshots(limit);
return {
content: [{
type: "text",
text: JSON.stringify(snapshots, null, 2)
}]
};
}
);
// Get network metrics
server.registerTool(
"get-network-metrics",
{
title: "Get Network Performance Metrics",
description: "Get network request performance metrics and timing analysis",
inputSchema: {
limit: z.number().optional().describe("Maximum number of network metrics to return")
}
},
async ({ limit }) => {
const networkMetrics = await debuggerCore.getNetworkMetrics(limit);
return {
content: [{
type: "text",
text: JSON.stringify(networkMetrics, null, 2)
}]
};
}
);
// Get render metrics
server.registerTool(
"get-render-metrics",
{
title: "Get Render Performance Metrics",
description: "Get React component render performance metrics and optimization insights",
inputSchema: {
limit: z.number().optional().describe("Maximum number of render metrics to return")
}
},
async ({ limit }) => {
const renderMetrics = await debuggerCore.getRenderMetrics(limit);
return {
content: [{
type: "text",
text: JSON.stringify(renderMetrics, null, 2)
}]
};
}
);
// Get performance alerts
server.registerTool(
"get-performance-alerts",
{
title: "Get Performance Alerts",
description: "Get performance alerts and warnings for CPU, memory, network, and render issues",
inputSchema: {
resolved: z.boolean().optional().describe("Filter by resolved status (true for resolved, false for unresolved)")
}
},
async ({ resolved }) => {
const alerts = await debuggerCore.getPerformanceAlerts(resolved);
return {
content: [{
type: "text",
text: JSON.stringify(alerts, null, 2)
}]
};
}
);
// Resolve performance alert
server.registerTool(
"resolve-performance-alert",
{
title: "Resolve Performance Alert",
description: "Mark a performance alert as resolved",
inputSchema: {
alertId: z.string().describe("ID of the alert to resolve")
}
},
async ({ alertId }) => {
const success = await debuggerCore.resolvePerformanceAlert(alertId);
return {
content: [{
type: "text",
text: JSON.stringify({
success,
message: success ? `Alert ${alertId} resolved` : `Alert ${alertId} not found`
}, null, 2)
}]
};
}
);
// Take detailed heap snapshot
server.registerTool(
"take-heap-snapshot",
{
title: "Take Detailed Heap Snapshot",
description: "Take a detailed heap snapshot using Chrome DevTools for memory analysis",
inputSchema: {}
},
async () => {
try {
const snapshot = await debuggerCore.takeDetailedHeapSnapshot();
return {
content: [{
type: "text",
text: JSON.stringify({
success: true,
snapshot: {
timestamp: new Date().toISOString(),
size: snapshot ? Object.keys(snapshot).length : 0
},
message: "Heap snapshot taken successfully"
}, null, 2)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
}, null, 2)
}]
};
}
}
);
// Start heap sampling
server.registerTool(
"start-heap-sampling",
{
title: "Start Heap Sampling",
description: "Start heap sampling for memory profiling and leak detection",
inputSchema: {
samplingInterval: z.number().optional().describe("Sampling interval in bytes (default: 32768)")
}
},
async ({ samplingInterval }) => {
try {
await debuggerCore.startHeapSampling(samplingInterval);
return {
content: [{
type: "text",
text: JSON.stringify({
success: true,
samplingInterval: samplingInterval || 32768,
message: "Heap sampling started successfully"
}, null, 2)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
}, null, 2)
}]
};
}
}
);
// Stop heap sampling
server.registerTool(
"stop-heap-sampling",
{
title: "Stop Heap Sampling",
description: "Stop heap sampling and get the memory profile",
inputSchema: {}
},
async () => {
try {
const profile = await debuggerCore.stopHeapSampling();
return {
content: [{
type: "text",
text: JSON.stringify({
success: true,
profile: {
timestamp: new Date().toISOString(),
samples: profile?.samples?.length || 0,
head: profile?.head ? "Available" : "Not available"
},
message: "Heap sampling stopped and profile collected"
}, null, 2)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
}, null, 2)
}]
};
}
}
);
// Force garbage collection
server.registerTool(
"force-garbage-collection",
{
title: "Force Garbage Collection",
description: "Force garbage collection to free memory and analyze memory leaks",
inputSchema: {}
},
async () => {
try {
await debuggerCore.forceGarbageCollection();
return {
content: [{
type: "text",
text: JSON.stringify({
success: true,
message: "Garbage collection forced successfully"
}, null, 2)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
}, null, 2)
}]
};
}
}
);
// Analyze network performance
server.registerTool(
"analyze-network-performance",
{
title: "Analyze Network Performance",
description: "Analyze network request patterns, identify slow requests, and get optimization recommendations",
inputSchema: {
timeframe: z.number().optional().describe("Timeframe in milliseconds (default: 300000 = 5 minutes)")
}
},
async ({ timeframe }) => {
try {
const analysis = await debuggerCore.analyzeNetworkPerformance(timeframe);
return {
content: [{
type: "text",
text: JSON.stringify(analysis, null, 2)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
}, null, 2)
}]
};
}
}
);
// Clear browser cache
server.registerTool(
"clear-browser-cache",
{
title: "Clear Browser Cache",
description: "Clear the browser cache to test performance without cached resources",
inputSchema: {}
},
async () => {
try {
await debuggerCore.clearBrowserCache();
return {
content: [{
type: "text",
text: JSON.stringify({
success: true,
message: "Browser cache cleared successfully"
}, null, 2)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
}, null, 2)
}]
};
}
}
);
// Clear browser cookies
server.registerTool(
"clear-browser-cookies",
{
title: "Clear Browser Cookies",
description: "Clear browser cookies for testing authentication and session handling",
inputSchema: {}
},
async () => {
try {
await debuggerCore.clearBrowserCookies();
return {
content: [{
type: "text",
text: JSON.stringify({
success: true,
message: "Browser cookies cleared successfully"
}, null, 2)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
}, null, 2)
}]
};
}
}
);
// Set network throttling
server.registerTool(
"set-network-throttling",
{
title: "Set Network Throttling",
description: "Configure network throttling to simulate different connection speeds",
inputSchema: {
offline: z.boolean().optional().describe("Set to offline mode"),
downloadThroughput: z.number().optional().describe("Download speed in bytes/second (-1 for unlimited)"),
uploadThroughput: z.number().optional().describe("Upload speed in bytes/second (-1 for unlimited)"),
latency: z.number().optional().describe("Network latency in milliseconds")
}
},
async ({ offline, downloadThroughput, uploadThroughput, latency }) => {
try {
await debuggerCore.setNetworkThrottling({
offline,
downloadThroughput,
uploadThroughput,
latency
});
return {
content: [{
type: "text",
text: JSON.stringify({
success: true,
configuration: {
offline: offline || false,
downloadThroughput: downloadThroughput || -1,
uploadThroughput: uploadThroughput || -1,
latency: latency || 0
},
message: "Network throttling configured successfully"
}, null, 2)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
}, null, 2)
}]
};
}
}
);
// Analyze render performance
server.registerTool(
"analyze-render-performance",
{
title: "Analyze Render Performance",
description: "Analyze React component render performance, identify slow renders, and get optimization recommendations",
inputSchema: {
timeframe: z.number().optional().describe("Timeframe in milliseconds (default: 300000 = 5 minutes)")
}
},
async ({ timeframe }) => {
try {
const analysis = await debuggerCore.analyzeRenderPerformance(timeframe);
return {
content: [{
type: "text",
text: JSON.stringify(analysis, null, 2)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
}, null, 2)
}]
};
}
}
);
// Get detailed render metrics
server.registerTool(
"get-detailed-render-metrics",
{
title: "Get Detailed Render Metrics",
description: "Get comprehensive render metrics including component-level performance data and trends",
inputSchema: {}
},
async () => {
try {
const metrics = await debuggerCore.getDetailedRenderMetrics();
return {
content: [{
type: "text",
text: JSON.stringify(metrics, null, 2)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
}, null, 2)
}]
};
}
}
);
// Start render tracking
server.registerTool(
"start-render-tracking",
{
title: "Start Render Tracking",
description: "Start tracking render performance for a specific component",
inputSchema: {
componentId: z.string().describe("Component ID to track"),
reason: z.string().optional().describe("Reason for the render (props, state, context, etc.)"),
changedProps: z.array(z.string()).optional().describe("List of changed prop names"),
changedState: z.array(z.string()).optional().describe("List of changed state names")
}
},
async ({ componentId, reason, changedProps, changedState }) => {
try {
await debuggerCore.startRenderTracking(componentId, reason, changedProps, changedState);
return {
content: [{
type: "text",
text: JSON.stringify({
success: true,
componentId,
message: "Render tracking started"
}, null, 2)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
}, null, 2)
}]
};
}
}
);
// Track component render
server.registerTool(
"track-component-render",
{
title: "Track Component Render",
description: "Complete render tracking for a component and record performance metrics",
inputSchema: {
componentId: z.string().describe("Component ID that finished rendering"),
reason: z.string().optional().describe("Reason for the render (props, state, context, etc.)"),
changedProps: z.array(z.string()).optional().describe("List of changed prop names"),
changedState: z.array(z.string()).optional().describe("List of changed state names")
}
},
async ({ componentId, reason, changedProps, changedState }) => {
try {
await debuggerCore.trackComponentRender(componentId, reason, changedProps, changedState);
return {
content: [{
type: "text",
text: JSON.stringify({
success: true,
componentId,
message: "Component render tracked successfully"
}, null, 2)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
}, null, 2)
}]
};
}
}
);
// Performance dashboard
server.registerTool(
"get-performance-dashboard",
{
title: "Get Performance Dashboard",
description: "Get a comprehensive performance dashboard with all key metrics, alerts, and recommendations",
inputSchema: {
timeframe: z.number().optional().describe("Timeframe in milliseconds (default: 300000 = 5 minutes)")
}
},
async ({ timeframe = 300000 }) => {
try {
const [
generalMetrics,
networkAnalysis,
renderAnalysis,
memorySnapshots,
alerts,
detailedRenderMetrics
] = await Promise.all([
debuggerCore.getPerformanceMetrics({ timeframe: `${timeframe}ms` }),
debuggerCore.analyzeNetworkPerformance(timeframe),
debuggerCore.analyzeRenderPerformance(timeframe),
debuggerCore.getMemorySnapshots(10),
debuggerCore.getPerformanceAlerts(false), // Only unresolved alerts
debuggerCore.getDetailedRenderMetrics()
]);
const dashboard = {
timestamp: new Date().toISOString(),
timeframe,
summary: {
totalAlerts: alerts.length,
criticalAlerts: alerts.filter((a: any) => a.severity === 'critical').length,
performanceScore: renderAnalysis.performanceScore || 0,
averageRenderTime: renderAnalysis.averageRenderTime || 0,
networkRequests: networkAnalysis.totalRequests || 0,
memoryUsage: memorySnapshots[0]?.heapUsed || 0
},
metrics: {
general: generalMetrics.slice(-5), // Last 5 general metrics
network: networkAnalysis,
render: renderAnalysis,
memory: memorySnapshots.slice(-5), // Last 5 memory snapshots
detailedRender: detailedRenderMetrics
},
alerts: alerts.slice(0, 10), // Top 10 alerts
recommendations: [
...(networkAnalysis.recommendations || []),
...(renderAnalysis.recommendations || [])
].slice(0, 10) // Top 10 recommendations
};
return {
content: [{
type: "text",
text: JSON.stringify(dashboard, null, 2)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
}, null, 2)
}]
};
}
}
);
// Performance optimization recommendations
server.registerTool(
"get-performance-optimization-recommendations",
{
title: "Get Performance Optimization Recommendations",
description: "Get comprehensive performance optimization recommendations with prioritized actions, quick wins, and long-term goals",
inputSchema: {
timeframe: z.number().optional().describe("Timeframe in milliseconds (default: 300000 = 5 minutes)")
}
},
async ({ timeframe = 300000 }) => {
try {
const recommendations = await debuggerCore.getPerformanceOptimizationRecommendations(timeframe);
return {
content: [{
type: "text",
text: JSON.stringify(recommendations, null, 2)
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error)
}, null, 2)
}]
};
}
}
);
// Update configuration
server.registerTool(
"update-config",
{
title: "Update Configuration",
description: "Update debugger configuration rules and settings",
inputSchema: {
config: z.record(z.any()).describe("Configuration object to update")
}
},
async ({ config }) => {
const result = await debuggerCore.updateConfig(config);
return {
content: [{
type: "text",
text: JSON.stringify(result, null, 2)
}]
};
}
);
// Manage breakpoints
server.registerTool(
"manage-breakpoints",
{
title: "Manage Breakpoints",
description: "Set, remove, list, and manage breakpoints for debugging",
inputSchema: {
action: z.enum(["set", "remove", "list", "clear", "toggle", "analytics"]).describe("Breakpoint action to perform"),
location: z.object({
url: z.string().optional().describe("URL of the file (for web pages)"),
filePath: z.string().optional().describe("File path relative to project root"),
lineNumber: z.number().describe("Line number (1-based)"),
columnNumber: z.number().optional().describe("Column number (0-based)")
}).optional().describe("Breakpoint location (required for 'set' action)"),
options: z.object({
condition: z.string().optional().describe("Conditional expression for breakpoint"),
logMessage: z.string().optional().describe("Log message for logpoints"),
hitCountCondition: z.string().optional().describe("Hit count condition (e.g., '>5', '==3')"),
enabled: z.boolean().optional().describe("Whether breakpoint is enabled")
}).optional().describe("Breakpoint options"),
breakpointId: z.string().optional().describe("Breakpoint ID (required for 'remove' action)"),
active: z.boolean().optional().describe("Active state (required for 'toggle' action)")
}
},
async ({ action, location, options, breakpointId, active }) => {
const command = {
action,
location,
options,
breakpointId,
active
};
const result = await debuggerCore.executeBreakpointCommand(command);
return {
content: [{
type: "text",
text: JSON.stringify(result, null, 2)
}]
};
}
);
// Variable inspection tools
server.registerTool(
"inspect-variables",
{
title: "Inspect Variables",
description: "Inspect variables in a specific scope of a call frame",
inputSchema: {
callFrameId: z.string().optional().describe("Call frame ID to inspect (defaults to top frame)"),
scopeNumber: z.number().optional().describe("Scope index to inspect (defaults to 0 - local scope)"),
includeNonEnumerable: z.boolean().optional().describe("Include non-enumerable properties"),
generatePreview: z.boolean().optional().describe("Generate object previews for complex objects")
}
},
async ({ callFrameId, scopeNumber, includeNonEnumerable, generatePreview }) => {
const command = {
action: "inspect" as const,
callFrameId,
scopeNumber,
options: {
includeNonEnumerable,
generatePreview
}
};
const result = await debuggerCore.executeVariableCommand(command);
return {
content: [{
type: "text",
text: JSON.stringify(result, null, 2)
}]
};
}
);
server.registerTool(
"get-scope-chain",
{
title: "Get Scope Chain",
description: "Get the complete scope chain for a call frame",
inputSchema: {
callFrameId: z.string().optional().describe("Call frame ID (defaults to top frame)")
}
},
async ({ callFrameId }) => {
const result = await debuggerCore.getScopeChain(callFrameId);
return {
content: [{
type: "text",
text: JSON.stringify(result, null, 2)
}]
};
}
);
server.registerTool(
"evaluate-expression",
{
title: "Evaluate Expression",
description: "Evaluate JavaScript expressions in the context of a call frame",
inputSchema: {
expression: z.string().describe("JavaScript expression to evaluate"),
callFrameId: z.string().optional().describe("Call frame ID for context (defaults to top frame)"),
includeCommandLineAPI: z.boolean().optional().describe("Include console API (default: false)"),
returnByValue: z.boolean().optional().describe("Return result by value instead of object reference"),
throwOnSideEffect: z.boolean().optional().describe("Throw if expression has side effects"),
timeout: z.number().optional().describe("Evaluation timeout in milliseconds")
}
},
async ({ expression, callFrameId, includeCommandLineAPI, returnByValue, throwOnSideEffect, timeout }) => {
const command = {
action: "evaluate" as const,
expression,
callFrameId,
options: {
includeCommandLineAPI,
returnByValue,
throwOnSideEffect,
timeout
}
};
const result = await debuggerCore.executeVariableCommand(command);
return {
content: [{
type: "text",
text: JSON.stringify(result, null, 2)
}]
};
}
);
server.registerTool(
"modify-variable",
{
title: "Modify Variable",
description: "Modify variable values in a specific scope",
inputSchema: {
callFrameId: z.string().describe("Call frame ID containing the variable"),
scopeNumber: z.number().describe("Scope index containing the variable"),
variableName: z.string().describe("Name of variable to modify"),
newValue: z.any().describe("New value for the variable")
}
},
async ({ callFrameId, scopeNumber, variableName, newValue }) => {
const command = {
action: "modify" as const,
callFrameId,
scopeNumber,
variableName,
newValue
};
const result = await debuggerCore.executeVariableCommand(command);
return {
content: [{
type: "text",
text: JSON.stringify(result, null, 2)
}]
};
}
);
server.registerTool(
"manage-watch-expressions",
{
title: "Manage Watch Expressions",
description: "Manage persistent watch expressions",
inputSchema: {
action: z.enum(["add", "remove", "list", "clear", "evaluate"]).describe("Watch expression action"),
expression: z.string().optional().describe("Expression to watch (for add action)"),
watchId: z.string().optional().describe("Watch expression ID (for remove action)"),
callFrameId: z.string().optional().describe("Call frame context for evaluation")
}
},
async ({ action, expression, watchId, callFrameId }) => {
const command = {
action: "watch" as const,
expression,
watchId,
callFrameId,
watchAction: action // Pass the watch-specific action
};
const result = await debuggerCore.executeVariableCommand(command);
return {
content: [{
type: "text",
text: JSON.stringify(result, null, 2)
}]
};
}
);
// React Component Analysis
server.registerTool(
"analyze-react-component",
{
title: "Analyze React Component",
description: "Analyze React components for state, props, hooks, and performance issues",
inputSchema: {
filePath: z.string().describe("Path to the React component file"),
componentName: z.string().optional().describe("Specific component name to analyze")
}
},
async ({ filePath, componentName }) => {
const analysis = await debuggerCore.analyzeReactComponent(filePath, componentName);
return {
content: [{
type: "text",
text: JSON.stringify(analysis, null, 2)
}]
};
}
);
// React Hook Monitoring
server.registerTool(
"monitor-react-hooks",
{
title: "Monitor React Hooks",
description: "Monitor React hooks for compliance with rules of hooks and performance issues",
inputSchema: {
filePath: z.string().describe("Path to the React file to analyze"),
hookType: z.enum(["useState", "useEffect", "useCallback", "useMemo", "custom", "all"]).optional().describe("Specific hook type to focus on")
}
},
async ({ filePath, hookType }) => {
const analysis = await debuggerCore.analyzeReactHooks(filePath, hookType);
return {
content: [{
type: "text",
text: JSON.stringify(analysis, null, 2)
}]
};
}
);
// React Performance Analysis
server.registerTool(
"get-react-performance",
{
title: "Get React Performance Metrics",
description: "Get React-specific performance metrics including render counts, component optimization opportunities",
inputSchema: {
timeframe: z.string().optional().describe("Time range like '1h', '30m', '5m'"),
componentName: z.string().optional().describe("Specific component to analyze")
}
},
async ({ timeframe, componentName }) => {
const metrics = await debuggerCore.getReactPerformanceMetrics({ timeframe, componentName });
return {
content: [{
type: "text",
text: JSON.stringify(metrics, null, 2)
}]
};
}
);
// React Issues Detection
server.registerTool(
"detect-react-issues",
{
title: "Detect React Issues",
description: "Detect common React anti-patterns, props drilling, unnecessary re-renders, and optimization opportunities",
inputSchema: {
filePath: z.string().optional().describe("Specific file to analyze (analyzes all React files if not provided)"),
issueType: z.enum(["props-drilling", "unnecessary-rerenders", "hook-violations", "performance", "all"]).optional().describe("Type of issues to detect")
}
},
async ({ filePath, issueType }) => {
const issues = await debuggerCore.detectReactIssues({ filePath, issueType });
return {
content: [{
type: "text",
text: JSON.stringify(issues, null, 2)
}]
};
}
);
// AI-Enhanced Error Analysis
server.registerTool(
"analyze-errors-ai",
{
title: "AI Error Analysis",
description: "Analyze errors using AI for categorization, pattern detection, and intelligent insights",
inputSchema: {
errorId: z.string().optional().describe("Specific error ID to analyze (analyzes all errors for patterns if not provided)")
}
},
async ({ errorId }) => {
const analysis = await debuggerCore.analyzeErrorsWithAI(errorId);
return {
content: [{
type: "text",
text: JSON.stringify(analysis, null, 2)
}]
};
}
);
// AI-Enhanced Performance Insights
server.registerTool(
"get-performance-insights",
{
title: "AI Performance Insights",
description: "Get AI-powered performance analysis including bottleneck identification, optimization suggestions, and regression detection",
inputSchema: {}
},
async () => {
const insights = await debuggerCore.getPerformanceInsightsWithAI();
return {
content: [{
type: "text",
text: JSON.stringify(insights, null, 2)
}]
};
}
);
// AI-Enhanced Code Quality Analysis
server.registerTool(
"analyze-code-quality-ai",
{
title: "AI Code Quality Analysis",
description: "Analyze code quality using AI for advanced code smell detection, refactoring opportunities, and technical debt analysis",
inputSchema: {
filePath: z.string().optional().describe("Specific file to analyze (analyzes entire codebase if not provided)")
}
},
async ({ filePath }) => {
const analysis = await debuggerCore.analyzeCodeQualityWithAI(filePath);
return {
content: [{
type: "text",
text: JSON.stringify(analysis, null, 2)
}]
};
}
);
// AI-Powered Optimization Suggestions
server.registerTool(
"suggest-optimizations",
{
title: "AI Optimization Suggestions",
description: "Get AI-powered optimization suggestions across performance, code quality, and architecture",
inputSchema: {
category: z.enum(["performance", "codeQuality", "quickWins", "criticalIssues"]).optional().describe("Category of suggestions to focus on")
}
},
async ({ category }) => {
const suggestions = await debuggerCore.getOptimizationSuggestions(category);
return {
content: [{
type: "text",
text: JSON.stringify(suggestions, null, 2)
}]
};
}
);
logger.info("MCP tools registered successfully (including AI-enhanced tools)");
}
/**
* Register MCP resources for streaming data
*/
async function registerResources(debuggerCore: DebuggerCore) {
// Real-time error stream
server.registerResource(
"error-stream",
"stream://errors",
{
title: "Error Stream",
description: "Real-time stream of errors and exceptions",
mimeType: "application/json"
},
async (uri) => {
const stream = await debuggerCore.getErrorStream();
return {
contents: [{
uri: uri.href,
text: JSON.stringify(stream, null, 2)
}]
};
}
);
// Real-time violation stream
server.registerResource(
"violation-stream",
"stream://violations",
{
title: "Violation Stream",
description: "Real-time stream of code quality violations",
mimeType: "application/json"
},
async (uri) => {
const stream = await debuggerCore.getViolationStream();
return {
contents: [{
uri: uri.href,
text: JSON.stringify(stream, null, 2)
}]
};
}
);
// Performance metrics stream
server.registerResource(
"performance-stream",
"stream://performance",
{
title: "Performance Stream",
description: "Real-time stream of performance metrics",
mimeType: "application/json"
},
async (uri) => {
const stream = await debuggerCore.getPerformanceStream();
return {
contents: [{
uri: uri.href,
text: JSON.stringify(stream, null, 2)
}]
};
}
);
logger.info("MCP resources registered successfully");
}
/**
* Main entry point
*/
async function main() {
try {
// Initialize server
const { debuggerCore } = await initializeServer();
// Connect to stdio transport
const transport = new StdioServerTransport();
await server.connect(transport);
logger.info("Debugger MCP Server is running and ready for connections");
// Handle graceful shutdown
process.on('SIGINT', async () => {
logger.info("Received SIGINT, shutting down gracefully...");
await debuggerCore.shutdown();
process.exit(0);
});
process.on('SIGTERM', async () => {
logger.info("Received SIGTERM, shutting down gracefully...");
await debuggerCore.shutdown();
process.exit(0);
});
} catch (error) {
logger.error("Failed to start server:", error);
process.exit(1);
}
}
// Start the server
if (import.meta.url === `file://${process.argv[1]}`) {
main().catch((error) => {
console.error("Fatal error:", error);
process.exit(1);
});
}