UNPKG

@logspace/mcp-server

Version:

MCP server for Logspace log analysis integration with AI models.

260 lines 11.7 kB
/** * Examples demonstrating the enhanced LogSpace API capabilities * Shows how AI can now detect issues that the old findSuspiciousPatterns missed */ import { logspace } from './codeExecutionAPI.js'; /** * Example 1: Detecting 200 OK responses with error data * Old approach would miss this since status = 200 */ async function detectMaskedApiErrors(bugId) { // Get all network requests with bodies const networkData = await logspace.getNetworkRequests(bugId, { includeBodies: true, limit: 100, }); // AI can now analyze response bodies even for "successful" requests const maskedErrors = networkData.requests.filter((req) => { if (req.status !== 200) return false; const responseBody = req.responseBody?.toLowerCase() || ''; return (responseBody.includes('error') || responseBody.includes('exception') || responseBody.includes('failed') || responseBody.includes('"success": false') || responseBody.includes('"status": "error"')); }); return { maskedErrorsFound: maskedErrors.length, issues: maskedErrors.map((req) => ({ url: req.url, method: req.method, responsePreview: req.responseBody?.substring(0, 200), timestamp: req.timestamp, })), }; } /** * Example 2: Correlating user interactions with missing network calls * Detects when user clicked something but expected API call didn't happen */ async function detectMissingApiCalls(bugId) { const [interactions, networkRequests] = await Promise.all([ logspace.getInteractions(bugId, { type: 'click' }), logspace.getNetworkRequests(bugId), ]); const suspiciousClicks = []; for (const click of interactions.interactions) { // Look for network requests within 3 seconds after click const followingRequests = networkRequests.requests.filter((req) => req.timestamp > click.timestamp && req.timestamp - click.timestamp < 3000); // If user clicked on button/form but no API call followed if (followingRequests.length === 0 && click.element && (click.element.includes('button') || click.element.includes('submit') || click.element.includes('save'))) { suspiciousClicks.push({ clickElement: click.element, timestamp: click.timestamp, issue: 'User clicked action element but no API call followed', }); } } return { suspiciousClicksCount: suspiciousClicks.length, details: suspiciousClicks, }; } /** * Example 3: Advanced timeline analysis * Finds complex patterns across multiple data types */ async function analyzeComplexFailurePattern(bugId) { // Get comprehensive session data with 60-second timeline const investigation = await logspace.investigateSession(bugId, { includeFullNetworkBodies: true, timeWindowSeconds: 60, }); // Look for this pattern: // 1. User interaction // 2. Slow network request (>3s) // 3. JavaScript error // 4. User frustrated actions (rapid clicks) const patterns = []; const timeline = investigation.timeline; for (let i = 0; i < timeline.length - 3; i++) { const event1 = timeline[i]; const event2 = timeline[i + 1]; const event3 = timeline[i + 2]; const event4 = timeline[i + 3]; if (event1.eventType === 'interaction' && event2.eventType === 'network' && event2.duration > 3000 && event3.eventType === 'console' && event3.type === 'error' && event4.eventType === 'interaction' && event4.timestamp - event1.timestamp < 10000) { // Within 10 seconds patterns.push({ type: 'slow_request_error_frustration', sequence: [ { type: 'user_action', element: event1.element }, { type: 'slow_request', url: event2.url, duration: event2.duration }, { type: 'js_error', message: event3.message }, { type: 'user_reaction', element: event4.element }, ], timespan: event4.timestamp - event1.timestamp, severity: 'high', }); } } return { complexPatternsFound: patterns.length, patterns, insights: patterns.length > 0 ? 'Found failure cascade: slow API → error → user frustration' : 'No complex failure patterns detected', }; } /** * Example 4: Performance correlation analysis * Links performance issues to user behavior and errors */ async function analyzePerformanceImpact(bugId) { const [performance, interactions, consoleLogs] = await Promise.all([ logspace.getPerformanceLogs(bugId), logspace.getInteractions(bugId), logspace.getConsoleLogs(bugId, { level: 'error' }), ]); // Find slow operations that correlate with errors or user frustration const correlations = []; for (const perfLog of performance.logs) { if (perfLog.duration > 2000) { // Slow operation // Check for errors within 5 seconds after const relatedErrors = consoleLogs.logs.filter((error) => error.timestamp > perfLog.timestamp && error.timestamp - perfLog.timestamp < 5000); // Check for user interactions indicating frustration const frustratedInteractions = interactions.interactions.filter((interaction) => interaction.timestamp > perfLog.timestamp && interaction.timestamp - perfLog.timestamp < 10000 && interaction.type === 'click'); if (relatedErrors.length > 0 || frustratedInteractions.length > 2) { correlations.push({ slowOperation: { name: perfLog.name, duration: perfLog.duration, type: perfLog.type, }, followingErrors: relatedErrors.length, userFrustrationIndicators: frustratedInteractions.length, impact: relatedErrors.length > 0 ? 'caused_errors' : 'caused_frustration', }); } } } return { performanceIssuesWithImpact: correlations.length, correlations, recommendation: correlations.length > 0 ? 'Performance bottlenecks are directly impacting user experience and causing errors' : 'Performance issues appear isolated without user impact', }; } /** * Example 5: Smart investigation workflow with fallback * AI can run this to get comprehensive insights */ async function smartInvestigation(bugId) { console.log(`🔍 Starting smart investigation for session ${bugId}...`); // Phase 1: Get overview const sessionMeta = await logspace.getSessionMetadata(bugId); console.log(`📊 Session: ${sessionMeta.sessionInfo.username} on ${sessionMeta.sessionInfo.environment}`); // Phase 2: Quick pattern detection const quickPatterns = await logspace.findSuspiciousPatterns(bugId); console.log(`⚠️ Quick scan found ${quickPatterns.criticalIssues.length} potential issues`); // Phase 3: Deep investigation if issues found if (quickPatterns.criticalIssues.length > 0) { const deepAnalysis = await Promise.all([ detectMaskedApiErrors(bugId), detectMissingApiCalls(bugId), analyzeComplexFailurePattern(bugId), analyzePerformanceImpact(bugId), ]); const [maskedErrors, missingCalls, complexPatterns, performanceImpact] = deepAnalysis; return { sessionOverview: sessionMeta, quickFindings: quickPatterns, deepAnalysis: { maskedApiErrors: maskedErrors, missingApiCalls: missingCalls, complexFailurePatterns: complexPatterns, performanceCorrelations: performanceImpact, }, overallAssessment: { severity: complexPatterns.complexPatternsFound > 0 ? 'critical' : maskedErrors.maskedErrorsFound > 0 ? 'high' : 'medium', primaryIssues: [ maskedErrors.maskedErrorsFound > 0 && 'API returning errors as 200 OK', missingCalls.suspiciousClicksCount > 0 && 'UI actions not triggering expected API calls', complexPatterns.complexPatternsFound > 0 && 'Complex failure cascades detected', performanceImpact.performanceIssuesWithImpact > 0 && 'Performance issues impacting users', ].filter(Boolean), recommendations: [ 'Review API error handling and response codes', 'Check frontend event handlers and API integration', 'Investigate performance bottlenecks', 'Improve user feedback for loading states', ], }, }; } // Phase 4: FALLBACK - No issues found in smart analysis, fetch everything console.log(`🔄 No critical issues found in targeted analysis. Falling back to comprehensive data fetch...`); const comprehensiveData = await Promise.all([ logspace.investigateSession(bugId, { includeFullNetworkBodies: true, timeWindowSeconds: 300, // 5 minutes - much larger window maxEventsPerType: 500, // Much higher limit }), logspace.getNetworkRequests(bugId, { includeBodies: true, limit: 200, failedOnly: false, // Include all responses, not just failed ones }), logspace.getConsoleLogs(bugId, { limit: 500, // Much higher limit to get all logs }), logspace.getPerformanceLogs(bugId), logspace.getInteractions(bugId), logspace.getAnnotations(bugId), ]); const [fullInvestigation, networkRequests, consoleLogs, performance, interactions, annotations] = comprehensiveData; return { sessionOverview: sessionMeta, quickFindings: quickPatterns, fallbackReason: 'Smart analysis found no critical issues, performed comprehensive data fetch', comprehensiveData: { fullTimeline: fullInvestigation.timeline, allNetworkRequests: networkRequests.requests, allConsoleLogs: consoleLogs.logs, allPerformanceData: performance.logs, allInteractions: interactions.interactions, userAnnotations: annotations.annotations, }, overallAssessment: { severity: 'unknown', message: 'No obvious issues detected. Full data provided for manual analysis.', dataStats: { networkRequestCount: networkRequests.requests.length, consoleLogCount: consoleLogs.logs.length, performanceEventCount: performance.logs.length, userInteractionCount: interactions.interactions.length, timelineEventCount: fullInvestigation.timeline.length, }, recommendation: 'Review the comprehensive data for subtle patterns or issues that automated analysis might have missed', }, }; } // Export example functions export { detectMaskedApiErrors, detectMissingApiCalls, analyzeComplexFailurePattern, analyzePerformanceImpact, smartInvestigation, }; //# sourceMappingURL=investigationExamples.js.map