UNPKG

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

781 lines • 33.8 kB
/** * Claude Code Debugging Handler * Specialized tools for debugging Claude Code itself - sessions, MCP communication, context analysis, tool decisions */ import { BaseToolHandler } from './base-handler-migrated.js'; import * as fs from 'fs'; import * as path from 'path'; import { exec } from 'child_process'; import { promisify } from 'util'; const execAsync = promisify(exec); export class ClaudeCodeDebuggingHandler extends BaseToolHandler { get tools() { return [ { name: 'claude_session_analyzer', description: 'Analyze active Claude Code sessions: metadata, performance, context usage, tool activity. Essential for debugging Claude Code behavior.', inputSchema: { type: 'object', properties: { sessionId: { type: 'string', description: 'Specific Claude session ID to analyze (optional - analyzes current session if not provided)' }, analyzePerformance: { type: 'boolean', default: true, description: 'Analyze performance metrics and resource usage' }, analyzeContext: { type: 'boolean', default: true, description: 'Analyze context window utilization and composition' }, analyzeToolUsage: { type: 'boolean', default: true, description: 'Analyze tool usage patterns and success rates' }, includeMemoryUsage: { type: 'boolean', default: true, description: 'Include memory usage analysis' } } } }, { name: 'claude_mcp_monitor', description: 'Monitor MCP server communications in real-time: protocol messages, tool calls, performance bottlenecks, error patterns.', inputSchema: { type: 'object', properties: { monitorDuration: { type: 'number', default: 30000, description: 'Monitoring duration in milliseconds' }, logLevel: { type: 'string', enum: ['all', 'errors', 'warnings', 'info'], default: 'all', description: 'MCP message log level to capture' }, trackPerformance: { type: 'boolean', default: true, description: 'Track MCP call performance and latency' }, analyzeToolCalls: { type: 'boolean', default: true, description: 'Analyze tool call patterns and success rates' }, mcpServerFilter: { type: 'array', items: { type: 'string' }, description: 'Filter specific MCP servers to monitor (optional)' } } } }, { name: 'claude_context_inspector', description: 'Deep analysis of Claude\'s context composition: files, conversation history, token usage, relevance scoring.', inputSchema: { type: 'object', properties: { analyzeTokenUsage: { type: 'boolean', default: true, description: 'Analyze token usage breakdown by source' }, analyzeFileContext: { type: 'boolean', default: true, description: 'Analyze included files and their relevance' }, analyzeConversationHistory: { type: 'boolean', default: true, description: 'Analyze conversation history utilization' }, contextRelevanceScoring: { type: 'boolean', default: true, description: 'Score context relevance to current task' }, suggestOptimizations: { type: 'boolean', default: true, description: 'Suggest context optimization strategies' } } } }, { name: 'claude_tool_decision_tracer', description: 'Trace Claude\'s tool selection reasoning: decision patterns, alternative analysis, optimization suggestions.', inputSchema: { type: 'object', properties: { traceDepth: { type: 'number', default: 10, description: 'Number of recent tool decisions to analyze' }, analyzeAlternatives: { type: 'boolean', default: true, description: 'Analyze alternative tools that could have been chosen' }, patternRecognition: { type: 'boolean', default: true, description: 'Identify patterns in tool selection' }, suggestionEngine: { type: 'boolean', default: true, description: 'Suggest tool usage optimizations' }, includeTimingAnalysis: { type: 'boolean', default: true, description: 'Include timing analysis of tool decisions' } } } }, { name: 'claude_response_analyzer', description: 'Analyze Claude\'s response patterns: structure, quality, task completion success, code generation analysis.', inputSchema: { type: 'object', properties: { responseCount: { type: 'number', default: 5, description: 'Number of recent responses to analyze' }, analyzeCodeQuality: { type: 'boolean', default: true, description: 'Analyze quality of generated code' }, analyzeTaskCompletion: { type: 'boolean', default: true, description: 'Analyze task completion success rates' }, analyzeResponseStructure: { type: 'boolean', default: true, description: 'Analyze response structure and organization' }, includeUserSatisfaction: { type: 'boolean', default: true, description: 'Include user satisfaction indicators' } } } }, { name: 'claude_config_validator', description: 'Validate Claude Code configuration: settings, paths, MCP servers, hooks, environment setup.', inputSchema: { type: 'object', properties: { validatePaths: { type: 'boolean', default: true, description: 'Validate all configured paths' }, validateMcpServers: { type: 'boolean', default: true, description: 'Validate MCP server configurations' }, validateHooks: { type: 'boolean', default: true, description: 'Validate hook configurations and executability' }, validateEnvironment: { type: 'boolean', default: true, description: 'Validate environment variables and dependencies' }, suggestImprovements: { type: 'boolean', default: true, description: 'Suggest configuration improvements' } } } }, { name: 'claude_performance_profiler', description: 'Profile Claude Code performance: API calls, memory usage, response times, resource utilization analysis.', inputSchema: { type: 'object', properties: { profileDuration: { type: 'number', default: 60000, description: 'Profiling duration in milliseconds' }, trackApiCalls: { type: 'boolean', default: true, description: 'Track API call timing and optimization opportunities' }, trackMemoryUsage: { type: 'boolean', default: true, description: 'Track memory usage patterns' }, trackResourceUtilization: { type: 'boolean', default: true, description: 'Track CPU and I/O resource utilization' }, generateOptimizationReport: { type: 'boolean', default: true, description: 'Generate performance optimization recommendations' } } } }, { name: 'claude_integration_debugger', description: 'Debug Claude Code integrations: IDE plugins, file operations, Git integration, system hooks.', inputSchema: { type: 'object', properties: { debugIdeIntegration: { type: 'boolean', default: true, description: 'Debug IDE plugin communication (VS Code, Cursor, etc.)' }, debugFileOperations: { type: 'boolean', default: true, description: 'Debug file system operations and permissions' }, debugGitIntegration: { type: 'boolean', default: true, description: 'Debug Git integration and commit operations' }, debugSystemHooks: { type: 'boolean', default: true, description: 'Debug system hook execution and configuration' }, includeEnvironmentAnalysis: { type: 'boolean', default: true, description: 'Include environment and path analysis' } } } }, { name: 'claude_conversation_flow_analyzer', description: 'Analyze conversation flow and context management: context evolution, conversation coherence, memory management.', inputSchema: { type: 'object', properties: { analyzeContextEvolution: { type: 'boolean', default: true, description: 'Analyze how context evolves throughout conversation' }, analyzeCoherence: { type: 'boolean', default: true, description: 'Analyze conversation coherence and consistency' }, analyzeMemoryManagement: { type: 'boolean', default: true, description: 'Analyze memory management and context retention' }, conversationDepth: { type: 'number', default: 20, description: 'Number of conversation turns to analyze' }, suggestImprovements: { type: 'boolean', default: true, description: 'Suggest conversation flow improvements' } } } } ]; } async handle(toolName, args, sessions) { switch (toolName) { case 'claude_session_analyzer': return this.analyzeClaudeSession(args); case 'claude_mcp_monitor': return this.monitorMcpCommunication(args); case 'claude_context_inspector': return this.inspectContext(args); case 'claude_tool_decision_tracer': return this.traceToolDecisions(args); case 'claude_response_analyzer': return this.analyzeResponses(args); case 'claude_config_validator': return this.validateConfig(args); case 'claude_performance_profiler': return this.profilePerformance(args); case 'claude_integration_debugger': return this.debugIntegrations(args); case 'claude_conversation_flow_analyzer': return this.analyzeConversationFlow(args); default: throw new Error(`Unknown tool: ${toolName}`); } } /** * Analyze Claude Code session */ async analyzeClaudeSession(args) { const { sessionId, analyzePerformance, analyzeContext, analyzeToolUsage, includeMemoryUsage } = args; const results = { success: false, sessionId: sessionId || 'current', findings: [], analysis: {}, recommendations: [] }; try { // Check if Claude Code is running try { const { stdout } = await execAsync('ps aux | grep -E "(claude|Claude)" | grep -v grep'); const claudeProcesses = stdout.split('\n').filter(line => line.trim()); results.findings.push({ severity: 'info', message: `Found ${claudeProcesses.length} Claude-related processes`, details: claudeProcesses }); if (claudeProcesses.length === 0) { results.findings.push({ severity: 'warning', message: 'No active Claude Code processes detected', recommendation: 'Start Claude Code session to enable detailed analysis' }); } } catch (error) { results.findings.push({ severity: 'info', message: 'No Claude Code processes detected' }); } // Analyze Claude configuration directory const claudeConfigDir = `${process.env.HOME}/.claude`; if (fs.existsSync(claudeConfigDir)) { const configFiles = fs.readdirSync(claudeConfigDir); results.findings.push({ severity: 'success', message: `Found Claude configuration directory with ${configFiles.length} files`, details: configFiles }); // Check for specific configuration files const importantFiles = ['claude_desktop_config.json', 'config.json', 'CLAUDE.md']; for (const file of importantFiles) { if (configFiles.includes(file)) { results.findings.push({ severity: 'success', message: `Configuration file found: ${file}` }); } } } else { results.findings.push({ severity: 'warning', message: 'Claude configuration directory not found', recommendation: 'Ensure Claude Code is properly installed' }); } // Analyze memory usage if requested if (includeMemoryUsage) { try { const { stdout } = await execAsync('ps -o pid,ppid,comm,rss | grep -E "(claude|Claude)" | grep -v grep'); if (stdout.trim()) { results.analysis.memoryUsage = { processes: stdout.split('\n').filter(line => line.trim()), timestamp: new Date().toISOString() }; } } catch (error) { results.findings.push({ severity: 'info', message: 'Could not analyze memory usage for Claude processes' }); } } results.success = true; results.summary = `Claude session analysis completed. Processes: ${results.findings.filter((f) => f.message.includes('processes')).length}`; } catch (error) { results.findings.push({ severity: 'error', message: 'Claude session analysis failed', error: error instanceof Error ? error.message : String(error) }); } return results; } /** * Monitor MCP communication */ async monitorMcpCommunication(args) { const { monitorDuration, logLevel, trackPerformance, analyzeToolCalls, mcpServerFilter } = args; return { success: true, message: 'MCP communication monitoring - would monitor protocol messages, tool calls, and performance', monitoring: { duration: monitorDuration, logLevel, trackPerformance, analyzeToolCalls, serverFilter: mcpServerFilter }, findings: [ { severity: 'info', message: 'MCP monitoring requires active Claude Code session with MCP servers', recommendation: 'Start Claude Code and enable MCP debugging for detailed analysis' } ] }; } /** * Inspect context composition */ async inspectContext(args) { const { analyzeTokenUsage, analyzeFileContext, analyzeConversationHistory, contextRelevanceScoring, suggestOptimizations } = args; const results = { success: false, findings: [], contextAnalysis: {} }; try { // Check for CLAUDE.md files in current directory and parent directories let currentDir = process.cwd(); const claudeMdFiles = []; for (let i = 0; i < 5; i++) { // Check up to 5 levels up const claudeMdPath = path.join(currentDir, 'CLAUDE.md'); if (fs.existsSync(claudeMdPath)) { claudeMdFiles.push(claudeMdPath); const stats = fs.statSync(claudeMdPath); results.findings.push({ severity: 'success', message: `Found CLAUDE.md context file: ${claudeMdPath}`, details: { size: stats.size, modified: stats.mtime, lines: fs.readFileSync(claudeMdPath, 'utf8').split('\n').length } }); } const parentDir = path.dirname(currentDir); if (parentDir === currentDir) break; // Reached root currentDir = parentDir; } results.contextAnalysis.claudeMdFiles = claudeMdFiles; // Analyze git repository context try { const { stdout } = await execAsync('git status --porcelain'); const modifiedFiles = stdout.split('\n').filter(line => line.trim()); results.findings.push({ severity: 'info', message: `Git context: ${modifiedFiles.length} modified files`, details: modifiedFiles }); results.contextAnalysis.gitContext = { modifiedFiles: modifiedFiles.length, hasChanges: modifiedFiles.length > 0 }; } catch (error) { results.findings.push({ severity: 'info', message: 'No git repository context available' }); } results.success = true; } catch (error) { results.findings.push({ severity: 'error', message: 'Context inspection failed', error: error instanceof Error ? error.message : String(error) }); } return results; } /** * Trace tool decision patterns */ async traceToolDecisions(args) { return { success: true, message: 'Tool decision tracing - would analyze recent tool selections and reasoning patterns', tracing: { depth: args.traceDepth, analyzeAlternatives: args.analyzeAlternatives, patternRecognition: args.patternRecognition, suggestionEngine: args.suggestionEngine }, findings: [ { severity: 'info', message: 'Tool decision tracing requires active Claude Code session with logging enabled', recommendation: 'Enable Claude Code debugging mode for detailed tool decision analysis' } ] }; } /** * Analyze response patterns */ async analyzeResponses(args) { return { success: true, message: 'Response analysis - would analyze Claude response patterns, quality, and task completion', analysis: { responseCount: args.responseCount, analyzeCodeQuality: args.analyzeCodeQuality, analyzeTaskCompletion: args.analyzeTaskCompletion, analyzeResponseStructure: args.analyzeResponseStructure }, findings: [ { severity: 'info', message: 'Response analysis requires conversation history access', recommendation: 'Enable conversation logging for detailed response analysis' } ] }; } /** * Validate Claude Code configuration */ async validateConfig(args) { const { validatePaths, validateMcpServers, validateHooks, validateEnvironment, suggestImprovements } = args; const results = { success: false, findings: [], validation: {}, suggestions: [] }; try { // Check Claude Code installation const claudePaths = [ '/Users/og/.claude/local/claude', `${process.env.HOME}/.claude/local/claude`, 'claude' ]; let claudeFound = false; for (const claudePath of claudePaths) { try { const { stdout } = await execAsync(`${claudePath} --version`); results.findings.push({ severity: 'success', message: `Claude Code found: ${stdout.trim()} at ${claudePath}` }); claudeFound = true; break; } catch { } } if (!claudeFound) { results.findings.push({ severity: 'error', message: 'Claude Code not found in expected paths', recommendation: 'Verify Claude Code installation' }); } // Validate configuration directory const configDir = `${process.env.HOME}/.claude`; if (fs.existsSync(configDir)) { results.findings.push({ severity: 'success', message: `Configuration directory exists: ${configDir}` }); // Check desktop config const desktopConfig = path.join(configDir, 'claude_desktop_config.json'); if (fs.existsSync(desktopConfig)) { try { const configContent = JSON.parse(fs.readFileSync(desktopConfig, 'utf8')); results.findings.push({ severity: 'success', message: 'Desktop configuration file is valid JSON', details: { mcpServers: Object.keys(configContent.mcpServers || {}), hasGlobalSettings: !!configContent.globalSettings } }); } catch (error) { results.findings.push({ severity: 'error', message: 'Desktop configuration file has invalid JSON', error: error instanceof Error ? error.message : String(error) }); } } } else { results.findings.push({ severity: 'warning', message: 'Configuration directory not found', recommendation: 'Run Claude Code setup to create configuration' }); } results.success = true; } catch (error) { results.findings.push({ severity: 'error', message: 'Configuration validation failed', error: error instanceof Error ? error.message : String(error) }); } return results; } /** * Profile performance */ async profilePerformance(args) { return { success: true, message: 'Performance profiling - would monitor API calls, memory usage, and resource utilization', profiling: { duration: args.profileDuration, trackApiCalls: args.trackApiCalls, trackMemoryUsage: args.trackMemoryUsage, trackResourceUtilization: args.trackResourceUtilization }, findings: [ { severity: 'info', message: 'Performance profiling requires active Claude Code session', recommendation: 'Start Claude Code and enable performance monitoring' } ] }; } /** * Debug integrations */ async debugIntegrations(args) { const { debugIdeIntegration, debugFileOperations, debugGitIntegration, debugSystemHooks, includeEnvironmentAnalysis } = args; const results = { success: false, findings: [], integrations: {} }; try { // Check IDE integration if (debugIdeIntegration) { const ideProcesses = ['code', 'cursor', 'nvim', 'vim']; for (const ide of ideProcesses) { try { const { stdout } = await execAsync(`ps aux | grep ${ide} | grep -v grep`); if (stdout.trim()) { results.findings.push({ severity: 'info', message: `${ide.toUpperCase()} process detected`, details: stdout.split('\n').filter(line => line.trim()) }); } } catch { } } } // Check Git integration if (debugGitIntegration) { try { const { stdout: gitVersion } = await execAsync('git --version'); const { stdout: gitConfig } = await execAsync('git config --list'); results.findings.push({ severity: 'success', message: `Git integration available: ${gitVersion.trim()}`, details: { configLines: gitConfig.split('\n').length } }); } catch (error) { results.findings.push({ severity: 'warning', message: 'Git not available or not configured', recommendation: 'Install and configure Git for version control integration' }); } } // Check environment if (includeEnvironmentAnalysis) { const envVars = ['PATH', 'NODE_PATH', 'CLAUDE_API_KEY', 'ANTHROPIC_API_KEY']; for (const envVar of envVars) { if (process.env[envVar]) { results.findings.push({ severity: 'success', message: `Environment variable ${envVar} is set`, details: { length: process.env[envVar].length } }); } else { results.findings.push({ severity: 'info', message: `Environment variable ${envVar} not set` }); } } } results.success = true; } catch (error) { results.findings.push({ severity: 'error', message: 'Integration debugging failed', error: error instanceof Error ? error.message : String(error) }); } return results; } /** * Analyze conversation flow */ async analyzeConversationFlow(args) { return { success: true, message: 'Conversation flow analysis - would analyze context evolution, coherence, and memory management', analysis: { contextEvolution: args.analyzeContextEvolution, coherence: args.analyzeCoherence, memoryManagement: args.analyzeMemoryManagement, conversationDepth: args.conversationDepth }, findings: [ { severity: 'info', message: 'Conversation flow analysis requires access to conversation history', recommendation: 'Enable conversation logging for detailed flow analysis' } ] }; } } //# sourceMappingURL=claude-code-debugging-handler.js.map