@jaypie/mcp 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1202 @@
1
+ import * as https from 'node:https';
2
+ import { Llm } from '@jaypie/llm';
3
+ import { spawn } from 'node:child_process';
4
+ import * as fs from 'node:fs/promises';
5
+ import * as os from 'node:os';
6
+ import * as path from 'node:path';
7
+
8
+ /**
9
+ * Datadog API integration module
10
+ */
11
+ const nullLogger$1 = {
12
+ info: () => { },
13
+ error: () => { },
14
+ };
15
+ /**
16
+ * Get Datadog credentials from environment variables
17
+ */
18
+ function getDatadogCredentials() {
19
+ const apiKey = process.env.DATADOG_API_KEY || process.env.DD_API_KEY;
20
+ const appKey = process.env.DATADOG_APP_KEY ||
21
+ process.env.DATADOG_APPLICATION_KEY ||
22
+ process.env.DD_APP_KEY ||
23
+ process.env.DD_APPLICATION_KEY;
24
+ if (!apiKey || !appKey) {
25
+ return null;
26
+ }
27
+ return { apiKey, appKey };
28
+ }
29
+ /**
30
+ * Build query string from environment variables and options
31
+ */
32
+ function buildDatadogQuery(options) {
33
+ const ddEnv = process.env.DD_ENV;
34
+ const ddService = process.env.DD_SERVICE;
35
+ const ddSource = process.env.DD_SOURCE;
36
+ const ddQuery = process.env.DD_QUERY;
37
+ const queryParts = [];
38
+ // Add source (parameter > env var > default 'lambda')
39
+ const effectiveSource = options.source || ddSource || "lambda";
40
+ queryParts.push(`source:${effectiveSource}`);
41
+ // Add env (parameter > env var)
42
+ const effectiveEnv = options.env || ddEnv;
43
+ if (effectiveEnv) {
44
+ queryParts.push(`env:${effectiveEnv}`);
45
+ }
46
+ // Add service (parameter > env var)
47
+ const effectiveService = options.service || ddService;
48
+ if (effectiveService) {
49
+ queryParts.push(`service:${effectiveService}`);
50
+ }
51
+ // Add base query from DD_QUERY if available
52
+ if (ddQuery) {
53
+ queryParts.push(ddQuery);
54
+ }
55
+ // Add user-provided query terms
56
+ if (options.query) {
57
+ queryParts.push(options.query);
58
+ }
59
+ return queryParts.join(" ");
60
+ }
61
+ /**
62
+ * Search Datadog logs
63
+ */
64
+ async function searchDatadogLogs(credentials, options = {}, logger = nullLogger$1) {
65
+ const effectiveQuery = buildDatadogQuery(options);
66
+ const effectiveFrom = options.from || "now-15m";
67
+ const effectiveTo = options.to || "now";
68
+ const effectiveLimit = Math.min(options.limit || 50, 1000);
69
+ const effectiveSort = options.sort || "-timestamp";
70
+ logger.info(`Effective query: ${effectiveQuery}`);
71
+ logger.info(`Search params: from=${effectiveFrom}, to=${effectiveTo}, limit=${effectiveLimit}, sort=${effectiveSort}`);
72
+ const requestBody = JSON.stringify({
73
+ filter: {
74
+ query: effectiveQuery,
75
+ from: effectiveFrom,
76
+ to: effectiveTo,
77
+ },
78
+ page: {
79
+ limit: effectiveLimit,
80
+ },
81
+ sort: effectiveSort,
82
+ });
83
+ return new Promise((resolve) => {
84
+ const requestOptions = {
85
+ hostname: "api.datadoghq.com",
86
+ port: 443,
87
+ path: "/api/v2/logs/events/search",
88
+ method: "POST",
89
+ headers: {
90
+ "Content-Type": "application/json",
91
+ "DD-API-KEY": credentials.apiKey,
92
+ "DD-APPLICATION-KEY": credentials.appKey,
93
+ "Content-Length": Buffer.byteLength(requestBody),
94
+ },
95
+ };
96
+ const req = https.request(requestOptions, (res) => {
97
+ let data = "";
98
+ res.on("data", (chunk) => {
99
+ data += chunk.toString();
100
+ });
101
+ res.on("end", () => {
102
+ logger.info(`Response status: ${res.statusCode}`);
103
+ if (res.statusCode !== 200) {
104
+ logger.error(`Datadog API error: ${res.statusCode}`);
105
+ let errorMessage = `Datadog API returned status ${res.statusCode}: ${data}`;
106
+ if (res.statusCode === 400) {
107
+ errorMessage = `Invalid query syntax. Check your query: "${effectiveQuery}". Datadog error: ${data}`;
108
+ }
109
+ else if (res.statusCode === 403) {
110
+ errorMessage =
111
+ "Access denied. Verify your API and Application keys have logs_read permission.";
112
+ }
113
+ else if (res.statusCode === 429) {
114
+ errorMessage =
115
+ "Rate limited by Datadog. Wait a moment and try again, or reduce your query scope.";
116
+ }
117
+ resolve({
118
+ success: false,
119
+ query: effectiveQuery,
120
+ timeRange: { from: effectiveFrom, to: effectiveTo },
121
+ logs: [],
122
+ error: errorMessage,
123
+ });
124
+ return;
125
+ }
126
+ try {
127
+ const response = JSON.parse(data);
128
+ const logs = (response.data || []).map((log) => {
129
+ const attrs = log.attributes || {};
130
+ return {
131
+ id: log.id,
132
+ timestamp: attrs.timestamp,
133
+ status: attrs.status,
134
+ service: attrs.service,
135
+ message: attrs.message,
136
+ attributes: attrs.attributes,
137
+ };
138
+ });
139
+ logger.info(`Retrieved ${logs.length} log entries`);
140
+ resolve({
141
+ success: true,
142
+ query: effectiveQuery,
143
+ timeRange: { from: effectiveFrom, to: effectiveTo },
144
+ logs,
145
+ });
146
+ }
147
+ catch (parseError) {
148
+ logger.error("Failed to parse Datadog response:", parseError);
149
+ resolve({
150
+ success: false,
151
+ query: effectiveQuery,
152
+ timeRange: { from: effectiveFrom, to: effectiveTo },
153
+ logs: [],
154
+ error: `Failed to parse response: ${parseError instanceof Error ? parseError.message : "Unknown error"}`,
155
+ });
156
+ }
157
+ });
158
+ });
159
+ req.on("error", (error) => {
160
+ logger.error("Request error:", error);
161
+ resolve({
162
+ success: false,
163
+ query: effectiveQuery,
164
+ timeRange: { from: effectiveFrom, to: effectiveTo },
165
+ logs: [],
166
+ error: `Connection error: ${error.message}`,
167
+ });
168
+ });
169
+ req.write(requestBody);
170
+ req.end();
171
+ });
172
+ }
173
+ /**
174
+ * Aggregate Datadog logs using the Analytics API
175
+ * Groups logs by specified fields and computes aggregations
176
+ */
177
+ async function aggregateDatadogLogs(credentials, options, logger = nullLogger$1) {
178
+ const effectiveQuery = buildDatadogQuery(options);
179
+ const effectiveFrom = options.from || "now-15m";
180
+ const effectiveTo = options.to || "now";
181
+ const groupBy = options.groupBy;
182
+ const compute = options.compute || [{ aggregation: "count" }];
183
+ logger.info(`Analytics query: ${effectiveQuery}`);
184
+ logger.info(`Group by: ${groupBy.join(", ")}`);
185
+ logger.info(`Time range: ${effectiveFrom} to ${effectiveTo}`);
186
+ // Build compute array - each item needs aggregation and type
187
+ const computeItems = compute.map((c) => {
188
+ const item = {
189
+ aggregation: c.aggregation,
190
+ type: "total",
191
+ };
192
+ if (c.metric) {
193
+ item.metric = c.metric;
194
+ }
195
+ return item;
196
+ });
197
+ // Build group_by with proper sort configuration
198
+ const groupByItems = groupBy.map((field) => {
199
+ const item = {
200
+ facet: field,
201
+ limit: 100,
202
+ sort: {
203
+ type: "measure",
204
+ order: "desc",
205
+ aggregation: compute[0]?.aggregation || "count",
206
+ },
207
+ };
208
+ return item;
209
+ });
210
+ const requestBody = JSON.stringify({
211
+ filter: {
212
+ query: effectiveQuery,
213
+ from: effectiveFrom,
214
+ to: effectiveTo,
215
+ },
216
+ group_by: groupByItems,
217
+ compute: computeItems,
218
+ page: {
219
+ limit: 100,
220
+ },
221
+ });
222
+ return new Promise((resolve) => {
223
+ const requestOptions = {
224
+ hostname: "api.datadoghq.com",
225
+ port: 443,
226
+ path: "/api/v2/logs/analytics/aggregate",
227
+ method: "POST",
228
+ headers: {
229
+ "Content-Type": "application/json",
230
+ "DD-API-KEY": credentials.apiKey,
231
+ "DD-APPLICATION-KEY": credentials.appKey,
232
+ "Content-Length": Buffer.byteLength(requestBody),
233
+ },
234
+ };
235
+ const req = https.request(requestOptions, (res) => {
236
+ let data = "";
237
+ res.on("data", (chunk) => {
238
+ data += chunk.toString();
239
+ });
240
+ res.on("end", () => {
241
+ logger.info(`Response status: ${res.statusCode}`);
242
+ if (res.statusCode !== 200) {
243
+ logger.error(`Datadog Analytics API error: ${res.statusCode}`);
244
+ let errorMessage = `Datadog API returned status ${res.statusCode}: ${data}`;
245
+ if (res.statusCode === 400) {
246
+ errorMessage = `Invalid query or groupBy fields. Verify facet names exist: ${groupBy.join(", ")}. Datadog error: ${data}`;
247
+ }
248
+ else if (res.statusCode === 403) {
249
+ errorMessage =
250
+ "Access denied. Verify your API and Application keys have logs_read permission.";
251
+ }
252
+ else if (res.statusCode === 429) {
253
+ errorMessage =
254
+ "Rate limited by Datadog. Wait a moment and try again, or reduce your query scope.";
255
+ }
256
+ resolve({
257
+ success: false,
258
+ query: effectiveQuery,
259
+ timeRange: { from: effectiveFrom, to: effectiveTo },
260
+ groupBy,
261
+ buckets: [],
262
+ error: errorMessage,
263
+ });
264
+ return;
265
+ }
266
+ try {
267
+ const response = JSON.parse(data);
268
+ const buckets = (response.data?.buckets || []).map((bucket) => ({
269
+ by: bucket.by || {},
270
+ computes: bucket.computes || {},
271
+ }));
272
+ logger.info(`Retrieved ${buckets.length} aggregation buckets`);
273
+ resolve({
274
+ success: true,
275
+ query: effectiveQuery,
276
+ timeRange: { from: effectiveFrom, to: effectiveTo },
277
+ groupBy,
278
+ buckets,
279
+ });
280
+ }
281
+ catch (parseError) {
282
+ logger.error("Failed to parse Datadog analytics response:", parseError);
283
+ resolve({
284
+ success: false,
285
+ query: effectiveQuery,
286
+ timeRange: { from: effectiveFrom, to: effectiveTo },
287
+ groupBy,
288
+ buckets: [],
289
+ error: `Failed to parse response: ${parseError instanceof Error ? parseError.message : "Unknown error"}`,
290
+ });
291
+ }
292
+ });
293
+ });
294
+ req.on("error", (error) => {
295
+ logger.error("Request error:", error);
296
+ resolve({
297
+ success: false,
298
+ query: effectiveQuery,
299
+ timeRange: { from: effectiveFrom, to: effectiveTo },
300
+ groupBy,
301
+ buckets: [],
302
+ error: `Connection error: ${error.message}`,
303
+ });
304
+ });
305
+ req.write(requestBody);
306
+ req.end();
307
+ });
308
+ }
309
+ /**
310
+ * List Datadog monitors with optional filtering
311
+ */
312
+ async function listDatadogMonitors(credentials, options = {}, logger = nullLogger$1) {
313
+ logger.info("Fetching Datadog monitors");
314
+ const queryParams = new URLSearchParams();
315
+ if (options.tags && options.tags.length > 0) {
316
+ queryParams.set("tags", options.tags.join(","));
317
+ }
318
+ if (options.monitorTags && options.monitorTags.length > 0) {
319
+ queryParams.set("monitor_tags", options.monitorTags.join(","));
320
+ }
321
+ if (options.name) {
322
+ queryParams.set("name", options.name);
323
+ }
324
+ const queryString = queryParams.toString();
325
+ const path = `/api/v1/monitor${queryString ? `?${queryString}` : ""}`;
326
+ logger.info(`Request path: ${path}`);
327
+ return new Promise((resolve) => {
328
+ const requestOptions = {
329
+ hostname: "api.datadoghq.com",
330
+ port: 443,
331
+ path,
332
+ method: "GET",
333
+ headers: {
334
+ "DD-API-KEY": credentials.apiKey,
335
+ "DD-APPLICATION-KEY": credentials.appKey,
336
+ },
337
+ };
338
+ const req = https.request(requestOptions, (res) => {
339
+ let data = "";
340
+ res.on("data", (chunk) => {
341
+ data += chunk.toString();
342
+ });
343
+ res.on("end", () => {
344
+ logger.info(`Response status: ${res.statusCode}`);
345
+ if (res.statusCode !== 200) {
346
+ logger.error(`Datadog Monitors API error: ${res.statusCode}`);
347
+ let errorMessage = `Datadog API returned status ${res.statusCode}: ${data}`;
348
+ if (res.statusCode === 403) {
349
+ errorMessage =
350
+ "Access denied. Verify your API and Application keys have monitors_read permission.";
351
+ }
352
+ else if (res.statusCode === 429) {
353
+ errorMessage =
354
+ "Rate limited by Datadog. Wait a moment and try again.";
355
+ }
356
+ resolve({
357
+ success: false,
358
+ monitors: [],
359
+ error: errorMessage,
360
+ });
361
+ return;
362
+ }
363
+ try {
364
+ const response = JSON.parse(data);
365
+ let monitors = response.map((monitor) => ({
366
+ id: monitor.id,
367
+ name: monitor.name,
368
+ type: monitor.type,
369
+ status: monitor.overall_state || "Unknown",
370
+ message: monitor.message,
371
+ tags: monitor.tags || [],
372
+ priority: monitor.priority,
373
+ query: monitor.query,
374
+ overallState: monitor.overall_state,
375
+ }));
376
+ // Filter by status if specified
377
+ if (options.status && options.status.length > 0) {
378
+ monitors = monitors.filter((m) => options.status.includes(m.status));
379
+ }
380
+ logger.info(`Retrieved ${monitors.length} monitors`);
381
+ resolve({
382
+ success: true,
383
+ monitors,
384
+ });
385
+ }
386
+ catch (parseError) {
387
+ logger.error("Failed to parse Datadog monitors response:", parseError);
388
+ resolve({
389
+ success: false,
390
+ monitors: [],
391
+ error: `Failed to parse response: ${parseError instanceof Error ? parseError.message : "Unknown error"}`,
392
+ });
393
+ }
394
+ });
395
+ });
396
+ req.on("error", (error) => {
397
+ logger.error("Request error:", error);
398
+ resolve({
399
+ success: false,
400
+ monitors: [],
401
+ error: `Connection error: ${error.message}`,
402
+ });
403
+ });
404
+ req.end();
405
+ });
406
+ }
407
+ /**
408
+ * List Datadog Synthetic tests
409
+ */
410
+ async function listDatadogSynthetics(credentials, options = {}, logger = nullLogger$1) {
411
+ logger.info("Fetching Datadog Synthetic tests");
412
+ return new Promise((resolve) => {
413
+ const requestOptions = {
414
+ hostname: "api.datadoghq.com",
415
+ port: 443,
416
+ path: "/api/v1/synthetics/tests",
417
+ method: "GET",
418
+ headers: {
419
+ "DD-API-KEY": credentials.apiKey,
420
+ "DD-APPLICATION-KEY": credentials.appKey,
421
+ },
422
+ };
423
+ const req = https.request(requestOptions, (res) => {
424
+ let data = "";
425
+ res.on("data", (chunk) => {
426
+ data += chunk.toString();
427
+ });
428
+ res.on("end", () => {
429
+ logger.info(`Response status: ${res.statusCode}`);
430
+ if (res.statusCode !== 200) {
431
+ logger.error(`Datadog Synthetics API error: ${res.statusCode}`);
432
+ let errorMessage = `Datadog API returned status ${res.statusCode}: ${data}`;
433
+ if (res.statusCode === 403) {
434
+ errorMessage =
435
+ "Access denied. Verify your API and Application keys have synthetics_read permission.";
436
+ }
437
+ else if (res.statusCode === 429) {
438
+ errorMessage =
439
+ "Rate limited by Datadog. Wait a moment and try again.";
440
+ }
441
+ resolve({
442
+ success: false,
443
+ tests: [],
444
+ error: errorMessage,
445
+ });
446
+ return;
447
+ }
448
+ try {
449
+ const response = JSON.parse(data);
450
+ let tests = (response.tests || []).map((test) => ({
451
+ publicId: test.public_id,
452
+ name: test.name,
453
+ type: test.type,
454
+ status: test.status,
455
+ tags: test.tags || [],
456
+ locations: test.locations || [],
457
+ message: test.message,
458
+ }));
459
+ // Filter by type if specified
460
+ if (options.type) {
461
+ tests = tests.filter((t) => t.type === options.type);
462
+ }
463
+ // Filter by tags if specified
464
+ if (options.tags && options.tags.length > 0) {
465
+ tests = tests.filter((t) => options.tags.some((tag) => t.tags.includes(tag)));
466
+ }
467
+ logger.info(`Retrieved ${tests.length} synthetic tests`);
468
+ resolve({
469
+ success: true,
470
+ tests,
471
+ });
472
+ }
473
+ catch (parseError) {
474
+ logger.error("Failed to parse Datadog synthetics response:", parseError);
475
+ resolve({
476
+ success: false,
477
+ tests: [],
478
+ error: `Failed to parse response: ${parseError instanceof Error ? parseError.message : "Unknown error"}`,
479
+ });
480
+ }
481
+ });
482
+ });
483
+ req.on("error", (error) => {
484
+ logger.error("Request error:", error);
485
+ resolve({
486
+ success: false,
487
+ tests: [],
488
+ error: `Connection error: ${error.message}`,
489
+ });
490
+ });
491
+ req.end();
492
+ });
493
+ }
494
+ /**
495
+ * Get recent results for a specific Synthetic test
496
+ */
497
+ async function getDatadogSyntheticResults(credentials, publicId, logger = nullLogger$1) {
498
+ logger.info(`Fetching results for Synthetic test: ${publicId}`);
499
+ return new Promise((resolve) => {
500
+ const requestOptions = {
501
+ hostname: "api.datadoghq.com",
502
+ port: 443,
503
+ path: `/api/v1/synthetics/tests/${publicId}/results`,
504
+ method: "GET",
505
+ headers: {
506
+ "DD-API-KEY": credentials.apiKey,
507
+ "DD-APPLICATION-KEY": credentials.appKey,
508
+ },
509
+ };
510
+ const req = https.request(requestOptions, (res) => {
511
+ let data = "";
512
+ res.on("data", (chunk) => {
513
+ data += chunk.toString();
514
+ });
515
+ res.on("end", () => {
516
+ logger.info(`Response status: ${res.statusCode}`);
517
+ if (res.statusCode !== 200) {
518
+ logger.error(`Datadog Synthetics Results API error: ${res.statusCode}`);
519
+ let errorMessage = `Datadog API returned status ${res.statusCode}: ${data}`;
520
+ if (res.statusCode === 403) {
521
+ errorMessage =
522
+ "Access denied. Verify your API and Application keys have synthetics_read permission.";
523
+ }
524
+ else if (res.statusCode === 404) {
525
+ errorMessage = `Synthetic test '${publicId}' not found. Use datadog_synthetics (without testId) to list available tests.`;
526
+ }
527
+ else if (res.statusCode === 429) {
528
+ errorMessage =
529
+ "Rate limited by Datadog. Wait a moment and try again.";
530
+ }
531
+ resolve({
532
+ success: false,
533
+ publicId,
534
+ results: [],
535
+ error: errorMessage,
536
+ });
537
+ return;
538
+ }
539
+ try {
540
+ const response = JSON.parse(data);
541
+ const results = (response.results || []).map((result) => ({
542
+ publicId,
543
+ resultId: result.result_id,
544
+ status: result.status,
545
+ checkTime: result.check_time,
546
+ passed: result.result?.passed ?? result.status === 0,
547
+ location: result.dc_id?.toString(),
548
+ }));
549
+ logger.info(`Retrieved ${results.length} synthetic results`);
550
+ resolve({
551
+ success: true,
552
+ publicId,
553
+ results,
554
+ });
555
+ }
556
+ catch (parseError) {
557
+ logger.error("Failed to parse Datadog synthetic results:", parseError);
558
+ resolve({
559
+ success: false,
560
+ publicId,
561
+ results: [],
562
+ error: `Failed to parse response: ${parseError instanceof Error ? parseError.message : "Unknown error"}`,
563
+ });
564
+ }
565
+ });
566
+ });
567
+ req.on("error", (error) => {
568
+ logger.error("Request error:", error);
569
+ resolve({
570
+ success: false,
571
+ publicId,
572
+ results: [],
573
+ error: `Connection error: ${error.message}`,
574
+ });
575
+ });
576
+ req.end();
577
+ });
578
+ }
579
+ /**
580
+ * Query Datadog metrics
581
+ */
582
+ async function queryDatadogMetrics(credentials, options, logger = nullLogger$1) {
583
+ logger.info(`Querying metrics: ${options.query}`);
584
+ logger.info(`Time range: ${options.from} to ${options.to}`);
585
+ const queryParams = new URLSearchParams({
586
+ query: options.query,
587
+ from: options.from.toString(),
588
+ to: options.to.toString(),
589
+ });
590
+ return new Promise((resolve) => {
591
+ const requestOptions = {
592
+ hostname: "api.datadoghq.com",
593
+ port: 443,
594
+ path: `/api/v1/query?${queryParams.toString()}`,
595
+ method: "GET",
596
+ headers: {
597
+ "DD-API-KEY": credentials.apiKey,
598
+ "DD-APPLICATION-KEY": credentials.appKey,
599
+ },
600
+ };
601
+ const req = https.request(requestOptions, (res) => {
602
+ let data = "";
603
+ res.on("data", (chunk) => {
604
+ data += chunk.toString();
605
+ });
606
+ res.on("end", () => {
607
+ logger.info(`Response status: ${res.statusCode}`);
608
+ if (res.statusCode !== 200) {
609
+ logger.error(`Datadog Metrics API error: ${res.statusCode}`);
610
+ let errorMessage = `Datadog API returned status ${res.statusCode}: ${data}`;
611
+ if (res.statusCode === 400) {
612
+ errorMessage = `Invalid metric query. Check format: 'aggregation:metric.name{tags}'. Query: "${options.query}". Datadog error: ${data}`;
613
+ }
614
+ else if (res.statusCode === 403) {
615
+ errorMessage =
616
+ "Access denied. Verify your API and Application keys have metrics_read permission.";
617
+ }
618
+ else if (res.statusCode === 429) {
619
+ errorMessage =
620
+ "Rate limited by Datadog. Wait a moment and try again, or reduce your time range.";
621
+ }
622
+ resolve({
623
+ success: false,
624
+ query: options.query,
625
+ timeRange: { from: options.from, to: options.to },
626
+ series: [],
627
+ error: errorMessage,
628
+ });
629
+ return;
630
+ }
631
+ try {
632
+ const response = JSON.parse(data);
633
+ const series = (response.series || []).map((s) => ({
634
+ metric: s.metric,
635
+ scope: s.scope,
636
+ pointlist: s.pointlist,
637
+ unit: s.unit?.[0]?.name,
638
+ }));
639
+ logger.info(`Retrieved ${series.length} metric series`);
640
+ resolve({
641
+ success: true,
642
+ query: options.query,
643
+ timeRange: { from: options.from, to: options.to },
644
+ series,
645
+ });
646
+ }
647
+ catch (parseError) {
648
+ logger.error("Failed to parse Datadog metrics response:", parseError);
649
+ resolve({
650
+ success: false,
651
+ query: options.query,
652
+ timeRange: { from: options.from, to: options.to },
653
+ series: [],
654
+ error: `Failed to parse response: ${parseError instanceof Error ? parseError.message : "Unknown error"}`,
655
+ });
656
+ }
657
+ });
658
+ });
659
+ req.on("error", (error) => {
660
+ logger.error("Request error:", error);
661
+ resolve({
662
+ success: false,
663
+ query: options.query,
664
+ timeRange: { from: options.from, to: options.to },
665
+ series: [],
666
+ error: `Connection error: ${error.message}`,
667
+ });
668
+ });
669
+ req.end();
670
+ });
671
+ }
672
+ /**
673
+ * Search Datadog RUM events
674
+ */
675
+ async function searchDatadogRum(credentials, options = {}, logger = nullLogger$1) {
676
+ const effectiveQuery = options.query || "*";
677
+ const effectiveFrom = options.from || "now-15m";
678
+ const effectiveTo = options.to || "now";
679
+ const effectiveLimit = Math.min(options.limit || 50, 1000);
680
+ const effectiveSort = options.sort || "-timestamp";
681
+ logger.info(`RUM query: ${effectiveQuery}`);
682
+ logger.info(`Time range: ${effectiveFrom} to ${effectiveTo}`);
683
+ const requestBody = JSON.stringify({
684
+ filter: {
685
+ query: effectiveQuery,
686
+ from: effectiveFrom,
687
+ to: effectiveTo,
688
+ },
689
+ page: {
690
+ limit: effectiveLimit,
691
+ },
692
+ sort: effectiveSort,
693
+ });
694
+ return new Promise((resolve) => {
695
+ const requestOptions = {
696
+ hostname: "api.datadoghq.com",
697
+ port: 443,
698
+ path: "/api/v2/rum/events/search",
699
+ method: "POST",
700
+ headers: {
701
+ "Content-Type": "application/json",
702
+ "DD-API-KEY": credentials.apiKey,
703
+ "DD-APPLICATION-KEY": credentials.appKey,
704
+ "Content-Length": Buffer.byteLength(requestBody),
705
+ },
706
+ };
707
+ const req = https.request(requestOptions, (res) => {
708
+ let data = "";
709
+ res.on("data", (chunk) => {
710
+ data += chunk.toString();
711
+ });
712
+ res.on("end", () => {
713
+ logger.info(`Response status: ${res.statusCode}`);
714
+ if (res.statusCode !== 200) {
715
+ logger.error(`Datadog RUM API error: ${res.statusCode}`);
716
+ let errorMessage = `Datadog API returned status ${res.statusCode}: ${data}`;
717
+ // Check for specific "No valid indexes" error which means no RUM app is configured
718
+ if (data.includes("No valid indexes")) {
719
+ errorMessage =
720
+ "No RUM application found. Ensure you have a RUM application configured in Datadog and it has collected data. " +
721
+ "You can create a RUM application at https://app.datadoghq.com/rum/list";
722
+ }
723
+ else if (res.statusCode === 400) {
724
+ errorMessage = `Invalid RUM query. Check syntax: "${effectiveQuery}". Datadog error: ${data}`;
725
+ }
726
+ else if (res.statusCode === 403) {
727
+ errorMessage =
728
+ "Access denied. Verify your API and Application keys have rum_read permission.";
729
+ }
730
+ else if (res.statusCode === 429) {
731
+ errorMessage =
732
+ "Rate limited by Datadog. Wait a moment and try again, or reduce your query scope.";
733
+ }
734
+ resolve({
735
+ success: false,
736
+ query: effectiveQuery,
737
+ timeRange: { from: effectiveFrom, to: effectiveTo },
738
+ events: [],
739
+ error: errorMessage,
740
+ });
741
+ return;
742
+ }
743
+ try {
744
+ const response = JSON.parse(data);
745
+ const events = (response.data || []).map((event) => {
746
+ const attrs = event.attributes?.attributes || {};
747
+ return {
748
+ id: event.id,
749
+ type: event.type,
750
+ timestamp: event.attributes?.timestamp,
751
+ sessionId: attrs.session?.id,
752
+ viewUrl: attrs.view?.url,
753
+ viewName: attrs.view?.name,
754
+ errorMessage: attrs.error?.message,
755
+ errorType: attrs.error?.type,
756
+ attributes: attrs,
757
+ };
758
+ });
759
+ logger.info(`Retrieved ${events.length} RUM events`);
760
+ resolve({
761
+ success: true,
762
+ query: effectiveQuery,
763
+ timeRange: { from: effectiveFrom, to: effectiveTo },
764
+ events,
765
+ });
766
+ }
767
+ catch (parseError) {
768
+ logger.error("Failed to parse Datadog RUM response:", parseError);
769
+ resolve({
770
+ success: false,
771
+ query: effectiveQuery,
772
+ timeRange: { from: effectiveFrom, to: effectiveTo },
773
+ events: [],
774
+ error: `Failed to parse response: ${parseError instanceof Error ? parseError.message : "Unknown error"}`,
775
+ });
776
+ }
777
+ });
778
+ });
779
+ req.on("error", (error) => {
780
+ logger.error("Request error:", error);
781
+ resolve({
782
+ success: false,
783
+ query: effectiveQuery,
784
+ timeRange: { from: effectiveFrom, to: effectiveTo },
785
+ events: [],
786
+ error: `Connection error: ${error.message}`,
787
+ });
788
+ });
789
+ req.write(requestBody);
790
+ req.end();
791
+ });
792
+ }
793
+
794
+ /**
795
+ * LLM debugging utilities for inspecting raw provider responses
796
+ */
797
+ // Default models for each provider
798
+ const DEFAULT_MODELS = {
799
+ anthropic: "claude-sonnet-4-20250514",
800
+ gemini: "gemini-2.0-flash",
801
+ openai: "gpt-4o-mini",
802
+ openrouter: "openai/gpt-4o-mini",
803
+ };
804
+ /**
805
+ * Make a debug LLM call and return the raw response data for inspection
806
+ */
807
+ async function debugLlmCall(params, log) {
808
+ const { provider, message } = params;
809
+ const model = params.model || DEFAULT_MODELS[provider];
810
+ log.info(`Making debug LLM call to ${provider} with model ${model}`);
811
+ try {
812
+ const llm = new Llm(provider, { model });
813
+ const result = await llm.operate(message, {
814
+ user: "[jaypie-mcp] Debug LLM Call",
815
+ });
816
+ if (result.error) {
817
+ return {
818
+ success: false,
819
+ provider,
820
+ model,
821
+ error: `${result.error.title}: ${result.error.detail || "Unknown error"}`,
822
+ };
823
+ }
824
+ // Calculate total reasoning tokens
825
+ const reasoningTokens = result.usage.reduce((sum, u) => sum + (u.reasoning || 0), 0);
826
+ return {
827
+ success: true,
828
+ provider,
829
+ model,
830
+ content: typeof result.content === "string"
831
+ ? result.content
832
+ : JSON.stringify(result.content),
833
+ reasoning: result.reasoning,
834
+ reasoningTokens,
835
+ history: result.history,
836
+ rawResponses: result.responses,
837
+ usage: result.usage,
838
+ };
839
+ }
840
+ catch (error) {
841
+ log.error(`Error calling ${provider}:`, error);
842
+ return {
843
+ success: false,
844
+ provider,
845
+ model,
846
+ error: error instanceof Error ? error.message : String(error),
847
+ };
848
+ }
849
+ }
850
+ /**
851
+ * List available providers and their default/reasoning models
852
+ */
853
+ function listLlmProviders() {
854
+ return {
855
+ providers: [
856
+ {
857
+ name: "openai",
858
+ defaultModel: DEFAULT_MODELS.openai,
859
+ reasoningModels: ["o3-mini", "o1-preview", "o1-mini"],
860
+ },
861
+ {
862
+ name: "anthropic",
863
+ defaultModel: DEFAULT_MODELS.anthropic,
864
+ reasoningModels: [], // Anthropic doesn't expose reasoning the same way
865
+ },
866
+ {
867
+ name: "gemini",
868
+ defaultModel: DEFAULT_MODELS.gemini,
869
+ reasoningModels: [], // Gemini has thoughtsTokenCount but unclear on content
870
+ },
871
+ {
872
+ name: "openrouter",
873
+ defaultModel: DEFAULT_MODELS.openrouter,
874
+ reasoningModels: ["openai/o3-mini", "openai/o1-preview"],
875
+ },
876
+ ],
877
+ };
878
+ }
879
+
880
+ /**
881
+ * AWS CLI integration module
882
+ * Provides a structured interface for common AWS operations via the AWS CLI
883
+ */
884
+ const nullLogger = {
885
+ info: () => { },
886
+ error: () => { },
887
+ };
888
+ /**
889
+ * Parse AWS CLI error messages into user-friendly descriptions
890
+ */
891
+ function parseAwsError(stderr, service, command) {
892
+ if (stderr.includes("ExpiredToken") || stderr.includes("Token has expired")) {
893
+ return "AWS credentials have expired. Run 'aws sso login' or refresh your credentials.";
894
+ }
895
+ if (stderr.includes("NoCredentialProviders") ||
896
+ stderr.includes("Unable to locate credentials")) {
897
+ return "No AWS credentials found. Configure credentials with 'aws configure' or 'aws sso login'.";
898
+ }
899
+ if (stderr.includes("AccessDenied") || stderr.includes("Access Denied")) {
900
+ return `Access denied for ${service}:${command}. Check your IAM permissions.`;
901
+ }
902
+ if (stderr.includes("ResourceNotFoundException")) {
903
+ return `Resource not found. Check that the specified resource exists in the correct region.`;
904
+ }
905
+ if (stderr.includes("ValidationException")) {
906
+ const match = stderr.match(/ValidationException[^:]*:\s*(.+)/);
907
+ return match
908
+ ? `Validation error: ${match[1].trim()}`
909
+ : "Validation error in request parameters.";
910
+ }
911
+ if (stderr.includes("ThrottlingException") ||
912
+ stderr.includes("Rate exceeded")) {
913
+ return "AWS API rate limit exceeded. Wait a moment and try again.";
914
+ }
915
+ if (stderr.includes("InvalidParameterValue")) {
916
+ const match = stderr.match(/InvalidParameterValue[^:]*:\s*(.+)/);
917
+ return match
918
+ ? `Invalid parameter: ${match[1].trim()}`
919
+ : "Invalid parameter value provided.";
920
+ }
921
+ return stderr.trim();
922
+ }
923
+ /**
924
+ * Parse relative time strings like 'now-1h' to Unix timestamps
925
+ */
926
+ function parseRelativeTime(timeStr) {
927
+ const now = Date.now();
928
+ if (timeStr === "now") {
929
+ return now;
930
+ }
931
+ // Handle relative time like 'now-15m', 'now-1h', 'now-1d'
932
+ const relativeMatch = timeStr.match(/^now-(\d+)([smhd])$/);
933
+ if (relativeMatch) {
934
+ const value = parseInt(relativeMatch[1], 10);
935
+ const unit = relativeMatch[2];
936
+ const multipliers = {
937
+ s: 1000,
938
+ m: 60 * 1000,
939
+ h: 60 * 60 * 1000,
940
+ d: 24 * 60 * 60 * 1000,
941
+ };
942
+ return now - value * multipliers[unit];
943
+ }
944
+ // Handle ISO 8601 format
945
+ const parsed = Date.parse(timeStr);
946
+ if (!isNaN(parsed)) {
947
+ return parsed;
948
+ }
949
+ // Default to the current time if parsing fails
950
+ return now;
951
+ }
952
+ /**
953
+ * Execute an AWS CLI command and return parsed JSON output
954
+ */
955
+ async function executeAwsCommand(service, command, args, options = {}, logger = nullLogger) {
956
+ const fullArgs = [service, command, ...args, "--output", "json"];
957
+ if (options.profile) {
958
+ fullArgs.push("--profile", options.profile);
959
+ }
960
+ if (options.region) {
961
+ fullArgs.push("--region", options.region);
962
+ }
963
+ logger.info(`Executing: aws ${fullArgs.join(" ")}`);
964
+ return new Promise((resolve) => {
965
+ const proc = spawn("aws", fullArgs);
966
+ let stdout = "";
967
+ let stderr = "";
968
+ proc.stdout.on("data", (data) => {
969
+ stdout += data.toString();
970
+ });
971
+ proc.stderr.on("data", (data) => {
972
+ stderr += data.toString();
973
+ });
974
+ proc.on("close", (code) => {
975
+ if (code !== 0) {
976
+ logger.error(`AWS CLI error: ${stderr}`);
977
+ resolve({
978
+ success: false,
979
+ error: parseAwsError(stderr, service, command),
980
+ });
981
+ return;
982
+ }
983
+ // Handle empty output (some commands return nothing on success)
984
+ if (!stdout.trim()) {
985
+ resolve({ success: true });
986
+ return;
987
+ }
988
+ try {
989
+ const data = JSON.parse(stdout);
990
+ resolve({ success: true, data });
991
+ }
992
+ catch {
993
+ // Some commands return plain text
994
+ resolve({ success: true, data: stdout.trim() });
995
+ }
996
+ });
997
+ proc.on("error", (error) => {
998
+ if (error.message.includes("ENOENT")) {
999
+ resolve({
1000
+ success: false,
1001
+ error: "AWS CLI not found. Install it from https://aws.amazon.com/cli/",
1002
+ });
1003
+ }
1004
+ else {
1005
+ resolve({ success: false, error: error.message });
1006
+ }
1007
+ });
1008
+ });
1009
+ }
1010
+ /**
1011
+ * List available AWS profiles from ~/.aws/config and ~/.aws/credentials
1012
+ */
1013
+ async function listAwsProfiles(logger = nullLogger) {
1014
+ const profiles = [];
1015
+ const homeDir = os.homedir();
1016
+ try {
1017
+ // Parse ~/.aws/config
1018
+ const configPath = path.join(homeDir, ".aws", "config");
1019
+ try {
1020
+ const configContent = await fs.readFile(configPath, "utf-8");
1021
+ const profileRegex = /\[profile\s+([^\]]+)\]|\[default\]/g;
1022
+ let match;
1023
+ while ((match = profileRegex.exec(configContent)) !== null) {
1024
+ const name = match[1] || "default";
1025
+ profiles.push({
1026
+ name,
1027
+ source: "config",
1028
+ });
1029
+ }
1030
+ logger.info(`Found ${profiles.length} profiles in config`);
1031
+ }
1032
+ catch {
1033
+ logger.info("No ~/.aws/config file found");
1034
+ }
1035
+ // Parse ~/.aws/credentials
1036
+ const credentialsPath = path.join(homeDir, ".aws", "credentials");
1037
+ try {
1038
+ const credentialsContent = await fs.readFile(credentialsPath, "utf-8");
1039
+ const profileRegex = /\[([^\]]+)\]/g;
1040
+ let match;
1041
+ while ((match = profileRegex.exec(credentialsContent)) !== null) {
1042
+ const name = match[1];
1043
+ // Only add if not already in the list
1044
+ if (!profiles.find((p) => p.name === name)) {
1045
+ profiles.push({
1046
+ name,
1047
+ source: "credentials",
1048
+ });
1049
+ }
1050
+ }
1051
+ logger.info(`Total profiles after credentials: ${profiles.length}`);
1052
+ }
1053
+ catch {
1054
+ logger.info("No ~/.aws/credentials file found");
1055
+ }
1056
+ return { success: true, data: profiles };
1057
+ }
1058
+ catch (error) {
1059
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
1060
+ logger.error(`Error listing profiles: ${errorMessage}`);
1061
+ return { success: false, error: errorMessage };
1062
+ }
1063
+ }
1064
+ // Step Functions operations
1065
+ async function listStepFunctionExecutions(options, logger = nullLogger) {
1066
+ const args = ["--state-machine-arn", options.stateMachineArn];
1067
+ if (options.statusFilter) {
1068
+ args.push("--status-filter", options.statusFilter);
1069
+ }
1070
+ if (options.maxResults) {
1071
+ args.push("--max-results", String(options.maxResults));
1072
+ }
1073
+ return executeAwsCommand("stepfunctions", "list-executions", args, { profile: options.profile, region: options.region }, logger);
1074
+ }
1075
+ async function stopStepFunctionExecution(options, logger = nullLogger) {
1076
+ const args = ["--execution-arn", options.executionArn];
1077
+ if (options.cause) {
1078
+ args.push("--cause", options.cause);
1079
+ }
1080
+ return executeAwsCommand("stepfunctions", "stop-execution", args, { profile: options.profile, region: options.region }, logger);
1081
+ }
1082
+ // Lambda operations
1083
+ async function listLambdaFunctions(options = {}, logger = nullLogger) {
1084
+ const args = [];
1085
+ if (options.maxResults) {
1086
+ args.push("--max-items", String(options.maxResults));
1087
+ }
1088
+ const result = await executeAwsCommand("lambda", "list-functions", args, { profile: options.profile, region: options.region }, logger);
1089
+ // Filter by prefix if specified
1090
+ if (result.success && result.data && options.functionNamePrefix) {
1091
+ result.data.Functions = result.data.Functions.filter((f) => f.FunctionName.startsWith(options.functionNamePrefix));
1092
+ }
1093
+ return result;
1094
+ }
1095
+ async function getLambdaFunction(options, logger = nullLogger) {
1096
+ return executeAwsCommand("lambda", "get-function", ["--function-name", options.functionName], { profile: options.profile, region: options.region }, logger);
1097
+ }
1098
+ // CloudWatch Logs operations
1099
+ async function filterLogEvents(options, logger = nullLogger) {
1100
+ const args = ["--log-group-name", options.logGroupName];
1101
+ if (options.filterPattern) {
1102
+ args.push("--filter-pattern", options.filterPattern);
1103
+ }
1104
+ if (options.startTime) {
1105
+ const startMs = parseRelativeTime(options.startTime);
1106
+ args.push("--start-time", String(startMs));
1107
+ }
1108
+ if (options.endTime) {
1109
+ const endMs = parseRelativeTime(options.endTime);
1110
+ args.push("--end-time", String(endMs));
1111
+ }
1112
+ if (options.limit) {
1113
+ args.push("--limit", String(options.limit));
1114
+ }
1115
+ return executeAwsCommand("logs", "filter-log-events", args, { profile: options.profile, region: options.region }, logger);
1116
+ }
1117
+ // S3 operations
1118
+ async function listS3Objects(options, logger = nullLogger) {
1119
+ const args = ["--bucket", options.bucket];
1120
+ if (options.prefix) {
1121
+ args.push("--prefix", options.prefix);
1122
+ }
1123
+ if (options.maxResults) {
1124
+ args.push("--max-items", String(options.maxResults));
1125
+ }
1126
+ return executeAwsCommand("s3api", "list-objects-v2", args, { profile: options.profile, region: options.region }, logger);
1127
+ }
1128
+ // CloudFormation operations
1129
+ async function describeStack(options, logger = nullLogger) {
1130
+ return executeAwsCommand("cloudformation", "describe-stacks", ["--stack-name", options.stackName], { profile: options.profile, region: options.region }, logger);
1131
+ }
1132
+ // DynamoDB operations
1133
+ async function describeDynamoDBTable(options, logger = nullLogger) {
1134
+ return executeAwsCommand("dynamodb", "describe-table", ["--table-name", options.tableName], { profile: options.profile, region: options.region }, logger);
1135
+ }
1136
+ async function scanDynamoDB(options, logger = nullLogger) {
1137
+ const args = ["--table-name", options.tableName];
1138
+ if (options.filterExpression) {
1139
+ args.push("--filter-expression", options.filterExpression);
1140
+ }
1141
+ if (options.expressionAttributeValues) {
1142
+ args.push("--expression-attribute-values", options.expressionAttributeValues);
1143
+ }
1144
+ if (options.limit) {
1145
+ args.push("--limit", String(options.limit));
1146
+ }
1147
+ return executeAwsCommand("dynamodb", "scan", args, { profile: options.profile, region: options.region }, logger);
1148
+ }
1149
+ async function queryDynamoDB(options, logger = nullLogger) {
1150
+ const args = [
1151
+ "--table-name",
1152
+ options.tableName,
1153
+ "--key-condition-expression",
1154
+ options.keyConditionExpression,
1155
+ "--expression-attribute-values",
1156
+ options.expressionAttributeValues,
1157
+ ];
1158
+ if (options.indexName) {
1159
+ args.push("--index-name", options.indexName);
1160
+ }
1161
+ if (options.filterExpression) {
1162
+ args.push("--filter-expression", options.filterExpression);
1163
+ }
1164
+ if (options.limit) {
1165
+ args.push("--limit", String(options.limit));
1166
+ }
1167
+ if (options.scanIndexForward === false) {
1168
+ args.push("--no-scan-index-forward");
1169
+ }
1170
+ return executeAwsCommand("dynamodb", "query", args, { profile: options.profile, region: options.region }, logger);
1171
+ }
1172
+ async function getDynamoDBItem(options, logger = nullLogger) {
1173
+ return executeAwsCommand("dynamodb", "get-item", ["--table-name", options.tableName, "--key", options.key], { profile: options.profile, region: options.region }, logger);
1174
+ }
1175
+ // SQS operations
1176
+ async function listSQSQueues(options = {}, logger = nullLogger) {
1177
+ const args = [];
1178
+ if (options.queueNamePrefix) {
1179
+ args.push("--queue-name-prefix", options.queueNamePrefix);
1180
+ }
1181
+ return executeAwsCommand("sqs", "list-queues", args, { profile: options.profile, region: options.region }, logger);
1182
+ }
1183
+ async function getSQSQueueAttributes(options, logger = nullLogger) {
1184
+ return executeAwsCommand("sqs", "get-queue-attributes", ["--queue-url", options.queueUrl, "--attribute-names", "All"], { profile: options.profile, region: options.region }, logger);
1185
+ }
1186
+ async function receiveSQSMessage(options, logger = nullLogger) {
1187
+ const args = ["--queue-url", options.queueUrl];
1188
+ if (options.maxNumberOfMessages) {
1189
+ args.push("--max-number-of-messages", String(options.maxNumberOfMessages));
1190
+ }
1191
+ if (options.visibilityTimeout) {
1192
+ args.push("--visibility-timeout", String(options.visibilityTimeout));
1193
+ }
1194
+ args.push("--attribute-names", "All");
1195
+ return executeAwsCommand("sqs", "receive-message", args, { profile: options.profile, region: options.region }, logger);
1196
+ }
1197
+ async function purgeSQSQueue(options, logger = nullLogger) {
1198
+ return executeAwsCommand("sqs", "purge-queue", ["--queue-url", options.queueUrl], { profile: options.profile, region: options.region }, logger);
1199
+ }
1200
+
1201
+ export { aggregateDatadogLogs as a, getDatadogSyntheticResults as b, listDatadogSynthetics as c, searchDatadogRum as d, debugLlmCall as e, listLlmProviders as f, getDatadogCredentials as g, listAwsProfiles as h, listStepFunctionExecutions as i, stopStepFunctionExecution as j, listLambdaFunctions as k, listDatadogMonitors as l, getLambdaFunction as m, filterLogEvents as n, listS3Objects as o, describeStack as p, queryDatadogMetrics as q, describeDynamoDBTable as r, searchDatadogLogs as s, scanDynamoDB as t, queryDynamoDB as u, getDynamoDBItem as v, listSQSQueues as w, getSQSQueueAttributes as x, receiveSQSMessage as y, purgeSQSQueue as z };
1202
+ //# sourceMappingURL=aws-B3dW_-bD.js.map