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
487 lines โข 22.9 kB
JavaScript
/**
* Smart Workflow Orchestration Handler
* Revolutionary AI-powered workflow automation system
* Transforms AI-Debug from manual tool selection to intelligent workflow orchestration
*
* Key Innovation: Context-aware AI that understands developer intent and automatically
* orchestrates optimal tool sequences instead of requiring manual tool selection
*/
import { BaseToolHandler } from './base-handler.js';
import { FlutterAnalysisWorkflow } from '../workflows/flutter-analysis-workflow.js';
export class SmartWorkflowOrchestrationHandler extends BaseToolHandler {
tools = [
{
name: 'smart_flutter_analysis',
description: 'Revolutionary AI-guided Flutter debugging workflow. Automatically orchestrates comprehensive Flutter analysis: health check โ screenshot โ console โ performance โ widget tree โ accessibility. Intelligence adapts tool sequence based on findings.',
inputSchema: {
type: 'object',
properties: {
sessionId: {
type: 'string',
description: 'Debug session ID for Flutter application'
},
context: {
type: 'string',
description: 'Development context',
enum: ['TDD_service_modularization', 'debugging', 'performance_optimization', 'refactoring', 'general'],
default: 'general'
},
intelligenceLevel: {
type: 'string',
description: 'AI analysis depth',
enum: ['basic', 'comprehensive', 'expert'],
default: 'comprehensive'
},
autoCapture: {
type: 'boolean',
description: 'Automatically capture screenshots and debug data',
default: true
},
userIntent: {
type: 'string',
description: 'What you want to accomplish (e.g., "validate TDD refactoring", "investigate performance issues")',
default: 'comprehensive Flutter analysis'
}
},
required: ['sessionId']
}
},
{
name: 'smart_tdd_workflow',
description: 'Revolutionary TDD cycle orchestration with multi-ecosystem support. Automatically bridges test assertions with runtime behavior across Flutter, Phoenix, and JavaScript frameworks. Adapts to red-green-refactor cycles.',
inputSchema: {
type: 'object',
properties: {
testFile: {
type: 'string',
description: 'Test file path (supports .dart, .exs, .js, .ts)'
},
sessionId: {
type: 'string',
description: 'Debug session ID for runtime validation'
},
cycleType: {
type: 'string',
description: 'TDD cycle type',
enum: ['red', 'green', 'refactor'],
default: 'red'
},
framework: {
type: 'string',
description: 'Test framework (auto-detected if not provided)',
enum: ['flutter', 'phoenix', 'jest', 'react', 'vue', 'angular', 'nextjs', 'auto'],
default: 'auto'
},
intelligenceLevel: {
type: 'string',
description: 'Analysis depth',
enum: ['basic', 'comprehensive', 'expert'],
default: 'comprehensive'
},
userIntent: {
type: 'string',
description: 'TDD goal (e.g., "validate service extraction", "implement new feature")',
default: 'TDD cycle validation'
}
},
required: ['testFile']
}
},
{
name: 'smart_performance_analysis',
description: 'AI-guided performance investigation workflow. Automatically orchestrates: baseline capture โ audit โ bundle analysis โ memory leak detection โ optimization recommendations. Adapts analysis based on detected issues.',
inputSchema: {
type: 'object',
properties: {
sessionId: {
type: 'string',
description: 'Debug session ID'
},
context: {
type: 'string',
description: 'Performance context',
enum: ['regression_investigation', 'optimization', 'baseline_establishment', 'general'],
default: 'general'
},
intelligenceLevel: {
type: 'string',
description: 'Analysis depth',
enum: ['basic', 'comprehensive', 'expert'],
default: 'comprehensive'
},
includeVisualRegression: {
type: 'boolean',
description: 'Include visual comparison analysis',
default: false
},
userIntent: {
type: 'string',
description: 'Performance goal (e.g., "investigate slow loading", "optimize Core Web Vitals")',
default: 'comprehensive performance analysis'
}
},
required: ['sessionId']
}
},
{
name: 'smart_debugging_workflow',
description: 'Universal AI-guided debugging workflow for any web application. Automatically orchestrates: session injection โ error capture โ framework detection โ targeted analysis โ solution recommendations. Works across all frameworks.',
inputSchema: {
type: 'object',
properties: {
url: {
type: 'string',
description: 'Application URL to debug'
},
context: {
type: 'string',
description: 'Debugging context',
enum: ['error_investigation', 'functionality_validation', 'integration_testing', 'general'],
default: 'general'
},
intelligenceLevel: {
type: 'string',
description: 'Analysis depth',
enum: ['basic', 'comprehensive', 'expert'],
default: 'comprehensive'
},
framework: {
type: 'string',
description: 'Application framework (auto-detected if not provided)',
enum: ['react', 'vue', 'angular', 'nextjs', 'flutter', 'phoenix', 'auto'],
default: 'auto'
},
userIntent: {
type: 'string',
description: 'Debugging goal (e.g., "fix login issues", "validate user flow")',
default: 'comprehensive debugging analysis'
}
},
required: ['url']
}
}
];
workflows = new Map();
toolHandlers = new Map();
constructor(toolHandlers) {
super();
this.initializeWorkflows();
if (toolHandlers) {
this.toolHandlers = toolHandlers;
}
}
initializeWorkflows() {
this.workflows.set('smart_flutter_analysis', new FlutterAnalysisWorkflow());
// Additional workflows will be added as they are implemented
}
async handle(toolName, args, sessions) {
try {
switch (toolName) {
case 'smart_flutter_analysis':
return this.executeSmartFlutterAnalysis(args, sessions);
case 'smart_tdd_workflow':
return this.executeSmartTDDWorkflow(args, sessions);
case 'smart_performance_analysis':
return this.executeSmartPerformanceAnalysis(args, sessions);
case 'smart_debugging_workflow':
return this.executeSmartDebuggingWorkflow(args, sessions);
default:
return this.createErrorResponse(`Unknown smart workflow: ${toolName}`);
}
}
catch (error) {
return this.createErrorResponse(error instanceof Error ? error.message : String(error));
}
}
async executeSmartFlutterAnalysis(args, sessions) {
const workflow = this.workflows.get('smart_flutter_analysis');
if (!workflow) {
return this.createErrorResponse('Flutter analysis workflow not available');
}
// Build workflow context
const context = {
sessionId: args.sessionId,
intelligenceLevel: args.intelligenceLevel || 'comprehensive',
userIntent: args.userIntent || `Flutter analysis with context: ${args.context || 'general'}`,
frameworks: ['flutter'],
autoCapture: args.autoCapture !== false
};
try {
// Get all tool handlers from the global registry
const toolHandlers = this.getToolHandlers();
// Execute workflow
const result = await workflow.execute(context, sessions, toolHandlers);
// Format results
const sections = [
'๐ **Smart Flutter Analysis Complete**',
'',
result.summary,
'',
'## ๐ฎ **Next Steps**'
];
result.nextSteps.forEach((step) => sections.push(step));
// Add workflow metadata
sections.push('');
sections.push('---');
sections.push('*โจ Powered by AI-Debug Smart Workflow Orchestration*');
sections.push('*๐ง Context-aware tool sequencing with adaptive intelligence*');
return this.createTextResponse(sections.join('\n'));
}
catch (error) {
return this.createErrorResponse(`Smart Flutter Analysis failed: ${error}`);
}
}
async executeSmartTDDWorkflow(args, sessions) {
// For MVP, delegate to existing TDD tools with smart orchestration
const context = {
sessionId: args.sessionId,
intelligenceLevel: args.intelligenceLevel || 'comprehensive',
userIntent: args.userIntent || `TDD ${args.cycleType} cycle for ${args.testFile}`,
frameworks: [args.framework || 'auto'],
autoCapture: true
};
try {
const sections = [
'๐งช **Smart TDD Workflow Orchestration**',
'',
`**Test File**: ${args.testFile}`,
`**Cycle Type**: ${args.cycleType.toUpperCase()}`,
`**Framework**: ${args.framework || 'Auto-detected'}`,
`**Intelligence**: ${context.intelligenceLevel}`,
'',
'## ๐ฏ **Intelligent TDD Orchestration**'
];
// Detect framework from test file
const detectedFramework = this.detectTestFramework(args.testFile);
sections.push(`**Detected Framework**: ${detectedFramework}`);
sections.push('');
// Route to appropriate TDD handler based on framework
const toolHandlers = this.getToolHandlers();
let tddResult;
if (detectedFramework === 'flutter') {
const flutterTDDHandler = this.findHandlerByTool('flutter_tdd_cycle_start', toolHandlers);
if (flutterTDDHandler) {
tddResult = await flutterTDDHandler.handle('flutter_tdd_cycle_start', {
testFile: args.testFile,
sessionId: args.sessionId,
cycleType: args.cycleType,
autoValidate: true
}, sessions);
}
}
else if (detectedFramework === 'phoenix') {
const phoenixTDDHandler = this.findHandlerByTool('phoenix_tdd_cycle_start', toolHandlers);
if (phoenixTDDHandler) {
tddResult = await phoenixTDDHandler.handle('phoenix_tdd_cycle_start', {
testFile: args.testFile,
sessionId: args.sessionId,
cycleType: args.cycleType,
autoValidate: true
}, sessions);
}
}
else {
const generalTDDHandler = this.findHandlerByTool('tdd_cycle_start', toolHandlers);
if (generalTDDHandler) {
tddResult = await generalTDDHandler.handle('tdd_cycle_start', {
testFile: args.testFile,
sessionId: args.sessionId,
cycleType: args.cycleType,
autoValidate: true
}, sessions);
}
}
if (tddResult && !tddResult.isError) {
sections.push('โ
**TDD Workflow Successfully Orchestrated**');
sections.push('');
sections.push(tddResult.content[0].text);
}
else {
sections.push('โ ๏ธ **TDD Orchestration Encountered Issues**');
sections.push('');
sections.push(`Error: ${tddResult?.content?.[0]?.text || 'Unknown error'}`);
}
sections.push('');
sections.push('## ๐ **Smart TDD Recommendations**');
sections.push('- Use framework-specific validation tools for deeper insights');
sections.push(`- Consider running smart_${detectedFramework}_analysis for comprehensive validation`);
sections.push('- Bridge test assertions with runtime behavior using AI validation');
return this.createTextResponse(sections.join('\n'));
}
catch (error) {
return this.createErrorResponse(`Smart TDD Workflow failed: ${error}`);
}
}
async executeSmartPerformanceAnalysis(args, sessions) {
const context = {
sessionId: args.sessionId,
intelligenceLevel: args.intelligenceLevel || 'comprehensive',
userIntent: args.userIntent || `Performance analysis with context: ${args.context}`,
frameworks: ['auto'],
autoCapture: true
};
const sections = [
'โก **Smart Performance Analysis Orchestration**',
'',
`**Session ID**: ${args.sessionId}`,
`**Context**: ${args.context}`,
`**Intelligence**: ${args.intelligenceLevel}`,
'',
'## ๐ฏ **AI-Guided Performance Workflow**'
];
try {
// Orchestrate performance analysis workflow
const toolHandlers = this.getToolHandlers();
const results = [];
// 1. Baseline performance capture
const performanceHandler = this.findHandlerByTool('get_performance_metrics', toolHandlers);
if (performanceHandler) {
const perfResult = await performanceHandler.handle('get_performance_metrics', {
sessionId: args.sessionId,
detailed: true
}, sessions);
results.push({ tool: 'performance_metrics', result: perfResult });
}
// 2. Comprehensive audit
const auditHandler = this.findHandlerByTool('run_audit', toolHandlers);
if (auditHandler) {
const auditResult = await auditHandler.handle('run_audit', {
sessionId: args.sessionId,
categories: ['performance', 'accessibility']
}, sessions);
results.push({ tool: 'audit', result: auditResult });
}
// 3. Bundle analysis if applicable
const bundleHandler = this.findHandlerByTool('analyze_bundles', toolHandlers);
if (bundleHandler) {
const bundleResult = await bundleHandler.handle('analyze_bundles', {
sessionId: args.sessionId
}, sessions);
results.push({ tool: 'bundle_analysis', result: bundleResult });
}
// Synthesize results
sections.push('โ
**Performance Analysis Complete**');
sections.push('');
results.forEach((result, index) => {
sections.push(`### ${index + 1}. ${result.tool.toUpperCase()} Results`);
if (result.result && !result.result.isError) {
const content = result.result.content?.[0]?.text || 'Analysis completed';
const preview = content.substring(0, 200) + (content.length > 200 ? '...' : '');
sections.push(preview);
}
else {
sections.push('โ ๏ธ Analysis encountered issues');
}
sections.push('');
});
sections.push('## ๐ง **AI Performance Insights**');
sections.push('- Performance baseline established with detailed metrics');
sections.push('- Comprehensive audit reveals optimization opportunities');
sections.push('- Bundle analysis identifies potential size optimizations');
return this.createTextResponse(sections.join('\n'));
}
catch (error) {
return this.createErrorResponse(`Smart Performance Analysis failed: ${error}`);
}
}
async executeSmartDebuggingWorkflow(args, sessions) {
const context = {
intelligenceLevel: args.intelligenceLevel || 'comprehensive',
userIntent: args.userIntent || `Debug application at ${args.url}`,
frameworks: [args.framework || 'auto'],
autoCapture: true
};
const sections = [
'๐ **Smart Debugging Workflow Orchestration**',
'',
`**URL**: ${args.url}`,
`**Context**: ${args.context || context.userIntent}`,
`**Framework**: ${args.framework || 'Auto-detect'}`,
`**Intelligence**: ${context.intelligenceLevel}`,
'',
'## ๐ฏ **AI-Guided Debugging Sequence**'
];
try {
const toolHandlers = this.getToolHandlers();
// 1. Inject debugging session
const coreHandler = this.findHandlerByTool('inject_debugging', toolHandlers);
let sessionId = '';
if (coreHandler) {
const injectResult = await coreHandler.handle('inject_debugging', {
url: args.url,
framework: args.framework
}, sessions);
if (!injectResult.isError) {
sessionId = injectResult.sessionId;
context.sessionId = sessionId;
sections.push('โ
**Debug Session Established**');
sections.push(`Session ID: ${sessionId}`);
}
}
if (sessionId) {
// 2. Capture errors and console logs
const errorResult = await coreHandler.handle('get_errors', {
sessionId: sessionId,
includeWarnings: true
}, sessions);
// 3. Framework-specific analysis
const detectedFramework = args.framework || 'auto';
if (detectedFramework === 'flutter') {
sections.push('๐ฏ **Flutter-Specific Analysis Triggered**');
// Delegate to smart_flutter_analysis
const flutterResult = await this.executeSmartFlutterAnalysis({
sessionId: sessionId,
context: args.context,
intelligenceLevel: args.intelligenceLevel,
userIntent: `Debug Flutter app: ${args.userIntent}`
}, sessions);
sections.push('');
sections.push(flutterResult.content[0].text);
}
else {
// General web app analysis
sections.push('๐ **General Web Application Analysis**');
sections.push('- Error capture and console log analysis complete');
sections.push('- Performance metrics gathered');
sections.push('- Framework detection and optimization suggestions');
}
}
sections.push('');
sections.push('## ๐ **Smart Debugging Recommendations**');
sections.push('- Follow framework-specific debugging workflows for deeper insights');
sections.push('- Use smart_performance_analysis for performance-related issues');
sections.push('- Consider smart_tdd_workflow for test-driven debugging validation');
return this.createTextResponse(sections.join('\n'));
}
catch (error) {
return this.createErrorResponse(`Smart Debugging Workflow failed: ${error}`);
}
}
detectTestFramework(testFile) {
const extension = testFile.split('.').pop()?.toLowerCase();
switch (extension) {
case 'dart':
return 'flutter';
case 'exs':
return 'phoenix';
case 'js':
case 'ts':
return 'jest';
default:
return 'unknown';
}
}
getToolHandlers() {
// Return injected tool handlers for testing, or empty map in production
return this.toolHandlers;
}
findHandlerByTool(toolName, toolHandlers) {
for (const handler of toolHandlers.values()) {
if (handler.tools && handler.tools.some((t) => t.name === toolName)) {
return handler;
}
}
return null;
}
}
//# sourceMappingURL=smart-workflow-orchestration-handler.js.map