Skip to main content
Glama
answer-q13-cloudwatch-fixed.cjs11.2 kB
#!/usr/bin/env node const { spawn } = require('child_process'); async function answerQ13CloudWatchFixed() { console.log('📊 Q13: FIXED - LAST 30 DAYS (PER DAY) AMORTIZED COST FOR CLOUDWATCH SERVICE'); console.log('=' .repeat(80)); const endDate = '2025-08-27'; const startDate = '2025-07-28'; // 30 days back console.log(`📅 Period: ${startDate} to ${endDate} (30 days)`); console.log('☁️ Cloud: AWS'); console.log('🔧 Service: AmazonCloudWatch (using groupBy service filter)'); console.log('💰 Cost Type: Amortized'); console.log('📈 Granularity: Daily'); console.log(''); const server = spawn('node', ['dist/index.js'], { stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, UMBRELLA_API_BASE_URL: 'https://api-front.umbrellacost.io/api/v1' } }); const responses = []; server.stdout.on('data', (data) => { const lines = data.toString().split('\n').filter(line => line.trim()); for (const line of lines) { try { const response = JSON.parse(line); responses.push(response); } catch (e) {} } }); server.stderr.on('data', () => {}); // Suppress server logs await new Promise(resolve => setTimeout(resolve, 2000)); // Authenticate server.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: 'authenticate_user', arguments: { username: 'david+saola@umbrellacost.com', password: 'Dsamsung1!' } } }) + '\n'); console.log('🔐 Authenticating...\n'); await new Promise(resolve => setTimeout(resolve, 5000)); // Q13 FIXED: Get daily data grouped by service, then filter for CloudWatch console.log('📡 Making API call for Q13 (FIXED APPROACH)...'); console.log('Strategy: Get all services daily, then extract CloudWatch data'); console.log('Parameters:'); console.log(` • Start Date: ${startDate}`); console.log(` • End Date: ${endDate}`); console.log(' • Group By: service (to get individual service breakdowns)'); console.log(' • Period: day'); console.log(' • Cost Type: cost (amortized)'); console.log(' • Cloud Context: aws'); console.log(' • Account ID: 932213950603'); console.log(''); server.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: 'api___invoices_caui', arguments: { startDate: startDate, endDate: endDate, groupBy: 'service', periodGranLevel: 'day', costType: ['cost'], isAmortized: true, cloud_context: 'aws', accountId: '932213950603' } } }) + '\n'); console.log('⏳ Waiting for response...\n'); await new Promise(resolve => setTimeout(resolve, 20000)); // Longer wait for large dataset const response = responses.find(r => r.id === 2); if (!response) { console.log('❌ NO RESPONSE RECEIVED'); server.kill(); return; } if (response.error) { console.log('❌ ERROR:', response.error.message || 'Unknown error'); server.kill(); return; } if (response.result?.content?.[0]?.text) { const text = response.result.content[0].text; console.log('📄 API RESPONSE RECEIVED'); console.log('=' .repeat(60)); console.log(`Response length: ${text.length} characters`); // Parse JSON if present const jsonMatch = text.match(/```json\n([\s\S]*?)\n```/); if (jsonMatch) { try { const data = JSON.parse(jsonMatch[1]); console.log('\n📊 EXTRACTING CLOUDWATCH DATA:'); console.log('=' .repeat(50)); if (Array.isArray(data)) { console.log(`• Total service records: ${data.length}`); // Filter for CloudWatch services only const cloudWatchData = data.filter(item => { const serviceName = (item.service_name || item.group_by || '').toLowerCase(); return serviceName.includes('cloudwatch') || serviceName === 'amazoncloudwatch'; }); console.log(`• CloudWatch records found: ${cloudWatchData.length}`); if (cloudWatchData.length === 0) { console.log('❌ No CloudWatch data found in response'); console.log('\n📋 Available services sample:'); data.slice(0, 10).forEach(item => { console.log(` • ${item.service_name || item.group_by}`); }); server.kill(); return; } // Group CloudWatch data by date const dailyCosts = {}; let totalCost = 0; let daysWithData = 0; cloudWatchData.forEach(item => { const date = item.usage_date || item.date || ''; const cost = parseFloat(item.total_cost || item.cost || 0); if (!dailyCosts[date]) { dailyCosts[date] = 0; } dailyCosts[date] += cost; totalCost += cost; }); // Get unique days const uniqueDays = Object.keys(dailyCosts).sort(); daysWithData = uniqueDays.length; if (daysWithData === 0) { console.log('❌ No valid CloudWatch cost data found'); server.kill(); return; } // Calculate statistics const dailyCostValues = Object.values(dailyCosts).filter(cost => cost > 0); const maxDailyCost = Math.max(...dailyCostValues); const minDailyCost = Math.min(...dailyCostValues); const maxDay = uniqueDays.find(date => dailyCosts[date] === maxDailyCost); const minDay = uniqueDays.find(date => dailyCosts[date] === minDailyCost); console.log(`💰 TOTAL CLOUDWATCH COST (30 days): $${totalCost.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`); console.log(`📊 STATISTICS:`); console.log(` • Days with data: ${daysWithData}/30`); console.log(` • Average daily cost: $${(totalCost / Math.max(daysWithData, 1)).toFixed(2)}`); console.log(` • Highest daily cost: $${maxDailyCost.toFixed(2)} (${maxDay})`); console.log(` • Lowest daily cost: $${minDailyCost.toFixed(2)} (${minDay})`); console.log('\n📅 DAILY CLOUDWATCH COST BREAKDOWN:'); console.log('-'.repeat(50)); // Display daily costs uniqueDays.forEach(date => { const cost = dailyCosts[date]; const dayName = new Date(date).toLocaleDateString('en-US', { weekday: 'short' }); const costStr = `$${cost.toFixed(2)}`; // Highlight significant days let indicator = ''; if (cost === maxDailyCost) indicator = ' ⭐ PEAK DAY'; else if (cost === minDailyCost && cost > 0) indicator = ' ⭐ LOWEST DAY'; console.log(`📅 ${date} (${dayName}): ${costStr.padStart(10)}${indicator}`); }); // Weekly aggregation console.log('\n📊 WEEKLY AGGREGATION:'); console.log('-'.repeat(40)); const weeklyTotals = {}; uniqueDays.forEach(date => { const dateObj = new Date(date); const weekStart = new Date(dateObj); weekStart.setDate(dateObj.getDate() - dateObj.getDay()); // Start of week (Sunday) const weekKey = weekStart.toISOString().split('T')[0]; if (!weeklyTotals[weekKey]) { weeklyTotals[weekKey] = 0; } weeklyTotals[weekKey] += dailyCosts[date]; }); Object.entries(weeklyTotals) .sort(([a], [b]) => a.localeCompare(b)) .forEach(([weekStart, cost]) => { const daysInWeek = uniqueDays.filter(date => { const dateObj = new Date(date); const weekStartObj = new Date(weekStart); const weekEndObj = new Date(weekStart); weekEndObj.setDate(weekEndObj.getDate() + 6); return dateObj >= weekStartObj && dateObj <= weekEndObj; }).length; console.log(`📅 Week of ${weekStart}: $${cost.toFixed(2)} (avg: $${(cost / daysInWeek).toFixed(2)}/day)`); }); // Cost trend analysis console.log('\n📈 COST TREND ANALYSIS:'); console.log('-'.repeat(40)); if (uniqueDays.length >= 14) { const firstWeekDays = uniqueDays.slice(0, 7); const lastWeekDays = uniqueDays.slice(-7); const firstWeekAvg = firstWeekDays.reduce((sum, date) => sum + dailyCosts[date], 0) / firstWeekDays.length; const lastWeekAvg = lastWeekDays.reduce((sum, date) => sum + dailyCosts[date], 0) / lastWeekDays.length; const trend = ((lastWeekAvg - firstWeekAvg) / firstWeekAvg * 100); console.log(` • First week average: $${firstWeekAvg.toFixed(2)}`); console.log(` • Last week average: $${lastWeekAvg.toFixed(2)}`); console.log(` • Overall trend: ${trend > 0 ? '↗️' : '↘️'} ${Math.abs(trend).toFixed(1)}% ${trend > 0 ? 'increase' : 'decrease'}`); } // Key insights console.log('\n🎯 KEY INSIGHTS:'); console.log('-'.repeat(40)); const percentOfTotal = ((totalCost / 136045.96) * 100); // Based on total AWS cost from earlier console.log(` • CloudWatch represents ~${percentOfTotal.toFixed(1)}% of total AWS costs`); if (maxDailyCost / minDailyCost > 2) { console.log(` • High cost variation: ${((maxDailyCost / minDailyCost - 1) * 100).toFixed(0)}% difference between peak and low`); } const avgCost = totalCost / daysWithData; const recentDays = uniqueDays.slice(-7); const recentAvg = recentDays.reduce((sum, date) => sum + dailyCosts[date], 0) / recentDays.length; if (Math.abs(recentAvg - avgCost) / avgCost > 0.2) { const change = recentAvg > avgCost ? 'increase' : 'decrease'; const pctChange = Math.abs((recentAvg - avgCost) / avgCost * 100); console.log(` • Recent trend: ${pctChange.toFixed(1)}% ${change} in final week`); } console.log('\n✅ Q13 ANSWER COMPLETE - CloudWatch daily costs properly filtered and analyzed'); } else { console.log('• Data Type: Object'); console.log('• Keys:', Object.keys(data).join(', ')); } } catch (e) { console.log('❌ JSON parsing error:', e.message); } } else { console.log('\n⚠️ No JSON data found in response'); } } else { console.log('❌ INVALID RESPONSE FORMAT'); } server.kill(); } answerQ13CloudWatchFixed().catch(console.error);

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/daviddraiumbrella/invoice-monitoring'

If you have feedback or need assistance with the MCP directory API, please join our Discord server