@fload-ai/mcp 0.5.0 → 0.7.0

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.
Files changed (44) hide show
  1. package/README.md +1 -1
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/api-client.d.ts +5 -0
  4. package/dist/api-client.d.ts.map +1 -1
  5. package/dist/api-client.js +21 -2
  6. package/dist/api-client.js.map +2 -2
  7. package/dist/bin.d.ts +1 -1
  8. package/dist/bin.d.ts.map +1 -1
  9. package/dist/bin.js +646 -711
  10. package/dist/bin.js.map +4 -4
  11. package/dist/config.d.ts +1 -2
  12. package/dist/config.d.ts.map +1 -1
  13. package/dist/index.js +567 -638
  14. package/dist/index.js.map +4 -4
  15. package/dist/rate-limiter.d.ts.map +1 -1
  16. package/dist/tools/actions.d.ts +20 -37
  17. package/dist/tools/actions.d.ts.map +1 -1
  18. package/dist/tools/ads.d.ts +8 -15
  19. package/dist/tools/ads.d.ts.map +1 -1
  20. package/dist/tools/agents.d.ts +22 -48
  21. package/dist/tools/agents.d.ts.map +1 -1
  22. package/dist/tools/analytics.d.ts +12 -34
  23. package/dist/tools/analytics.d.ts.map +1 -1
  24. package/dist/tools/apps.d.ts +8 -17
  25. package/dist/tools/apps.d.ts.map +1 -1
  26. package/dist/tools/aso.d.ts +43 -51
  27. package/dist/tools/aso.d.ts.map +1 -1
  28. package/dist/tools/chat.d.ts +7 -23
  29. package/dist/tools/chat.d.ts.map +1 -1
  30. package/dist/tools/dashboard.d.ts +2 -2
  31. package/dist/tools/dashboard.d.ts.map +1 -1
  32. package/dist/tools/index.d.ts +0 -3
  33. package/dist/tools/index.d.ts.map +1 -1
  34. package/dist/tools/index.js +563 -644
  35. package/dist/tools/index.js.map +4 -4
  36. package/dist/tools/reviews.d.ts +17 -60
  37. package/dist/tools/reviews.d.ts.map +1 -1
  38. package/package.json +1 -1
  39. package/dist/tools/anomalies.d.ts +0 -107
  40. package/dist/tools/anomalies.d.ts.map +0 -1
  41. package/dist/tools/forecasting.d.ts +0 -32
  42. package/dist/tools/forecasting.d.ts.map +0 -1
  43. package/dist/tools/growth.d.ts +0 -43
  44. package/dist/tools/growth.d.ts.map +0 -1
package/dist/bin.js CHANGED
@@ -1,23 +1,30 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/bin.ts
4
+ import "dotenv/config";
4
5
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
6
 
6
7
  // src/config.ts
7
- import "dotenv/config";
8
8
  import { readFileSync, existsSync } from "fs";
9
9
  import { homedir } from "os";
10
10
  import { join } from "path";
11
- function loadConfig() {
12
- const apiKey = process.env.FLOAD_API_KEY;
13
- const apiUrl = process.env.FLOAD_API_URL || "https://api.fload.com";
11
+ import { z } from "zod";
12
+ var ConfigFileSchema = z.object({
13
+ apiKey: z.string().optional().catch(void 0),
14
+ apiUrl: z.string().optional().catch(void 0)
15
+ });
16
+ function loadConfig(env = process.env) {
17
+ const apiKey = env.FLOAD_API_KEY;
18
+ const apiUrl = env.FLOAD_API_URL || "https://api.fload.com";
14
19
  if (apiKey) {
15
20
  return { apiKey, apiUrl };
16
21
  }
17
22
  const configPath = join(homedir(), ".fload", "config.json");
18
23
  if (existsSync(configPath)) {
19
24
  try {
20
- const configData = JSON.parse(readFileSync(configPath, "utf-8"));
25
+ const configData = ConfigFileSchema.parse(
26
+ JSON.parse(readFileSync(configPath, "utf-8"))
27
+ );
21
28
  if (configData.apiKey) {
22
29
  return {
23
30
  apiKey: configData.apiKey,
@@ -42,6 +49,8 @@ var RateLimiter = class {
42
49
  this.maxCalls = maxCalls;
43
50
  this.windowMs = windowMs;
44
51
  }
52
+ maxCalls;
53
+ windowMs;
45
54
  calls = /* @__PURE__ */ new Map();
46
55
  check(key) {
47
56
  const now = Date.now();
@@ -49,8 +58,8 @@ var RateLimiter = class {
49
58
  let timestamps = this.calls.get(key) || [];
50
59
  timestamps = timestamps.filter((t) => t > windowStart);
51
60
  if (timestamps.length >= this.maxCalls) {
52
- const oldestInWindow = timestamps[0];
53
- const retryAfterMs = oldestInWindow + this.windowMs - now;
61
+ const [oldestInWindow] = timestamps;
62
+ const retryAfterMs = oldestInWindow === void 0 ? Number.NaN : oldestInWindow + this.windowMs - now;
54
63
  this.calls.set(key, timestamps);
55
64
  return { allowed: false, remaining: 0, retryAfterMs };
56
65
  }
@@ -65,7 +74,7 @@ var RateLimiter = class {
65
74
  };
66
75
 
67
76
  // src/tools/apps.ts
68
- import { z } from "zod";
77
+ import { z as z2 } from "zod";
69
78
 
70
79
  // src/lib/format.ts
71
80
  function formatAsJson(data) {
@@ -79,13 +88,13 @@ function formatError(error) {
79
88
  }
80
89
 
81
90
  // src/tools/apps.ts
82
- var listAppsSchema = z.object({
83
- platform: z.enum(["ios", "android"]).optional().describe("Filter by platform (ios or android)"),
84
- limit: z.number().int().min(1).max(100).default(50).describe("Maximum number of apps to return")
91
+ var listAppsSchema = z2.object({
92
+ platform: z2.enum(["ios", "android"]).optional().describe("Filter by platform (ios or android)"),
93
+ limit: z2.number().int().min(1).max(100).default(50).describe("Maximum number of apps to return")
85
94
  });
86
- var getAppDetailsSchema = z.object({
87
- assetId: z.string().uuid().optional().describe("App UUID from Fload database"),
88
- bundleId: z.string().optional().describe("App bundle ID (e.g., com.example.app)")
95
+ var getAppDetailsSchema = z2.object({
96
+ assetId: z2.string().uuid().optional().describe("App UUID from Fload database"),
97
+ bundleId: z2.string().optional().describe("App bundle ID (e.g., com.example.app)")
89
98
  });
90
99
  async function listApps(input, client) {
91
100
  try {
@@ -98,10 +107,8 @@ async function listApps(input, client) {
98
107
  });
99
108
  const apps = response.data ?? [];
100
109
  const filtered = input.platform ? apps.filter((app) => {
101
- if (input.platform === "ios")
102
- return !!app.appleAppId;
103
- if (input.platform === "android")
104
- return !!app.googleAppId;
110
+ if (input.platform === "ios") return !!app.appleAppId;
111
+ if (input.platform === "android") return !!app.googleAppId;
105
112
  return true;
106
113
  }) : apps;
107
114
  return {
@@ -201,37 +208,40 @@ async function getAppDetails(input, client) {
201
208
  }
202
209
 
203
210
  // src/tools/reviews.ts
204
- import { z as z2 } from "zod";
205
- var getReviewsSchema = z2.object({
206
- assetId: z2.string().uuid().optional().describe("App UUID to filter reviews"),
207
- bundleId: z2.string().optional().describe("App bundle ID to filter reviews"),
208
- platform: z2.enum(["ios", "android"]).optional().describe("Filter by platform"),
209
- rating: z2.number().int().min(1).max(5).optional().describe("Filter by star rating (1-5)"),
210
- replied: z2.boolean().optional().describe("Filter by replied status (true = has reply, false = no reply)"),
211
- startDate: z2.string().optional().describe("Filter reviews from this date (ISO format: YYYY-MM-DD)"),
212
- endDate: z2.string().optional().describe("Filter reviews until this date (ISO format: YYYY-MM-DD)"),
213
- limit: z2.number().int().min(1).max(200).default(50).describe("Maximum number of reviews to return"),
214
- sortBy: z2.enum(["date", "rating"]).default("date").describe("Sort reviews by date or rating")
211
+ import { z as z3 } from "zod";
212
+ var getReviewsSchema = z3.object({
213
+ assetId: z3.string().uuid().optional().describe("App UUID to filter reviews"),
214
+ bundleId: z3.string().optional().describe("App bundle ID to filter reviews"),
215
+ platform: z3.enum(["ios", "android"]).optional().describe("Filter by platform"),
216
+ rating: z3.number().int().min(1).max(5).optional().describe("Filter by star rating (1-5)"),
217
+ replied: z3.boolean().optional().describe("Filter by replied status (true = has reply, false = no reply)"),
218
+ startDate: z3.string().optional().describe("Filter reviews from this date (ISO format: YYYY-MM-DD)"),
219
+ endDate: z3.string().optional().describe("Filter reviews until this date (ISO format: YYYY-MM-DD)"),
220
+ limit: z3.number().int().min(1).max(200).default(50).describe("Maximum number of reviews to return"),
221
+ cursor: z3.string().optional().describe(
222
+ "nextCursor from the previous get_reviews call, to fetch the next page with the same app and filters"
223
+ ),
224
+ sortBy: z3.enum(["date", "rating"]).default("date").describe("Sort reviews by date or rating")
215
225
  });
216
- var generateReviewReplySchema = z2.object({
217
- reviewId: z2.string().describe("The review UUID to generate a reply for"),
218
- assetId: z2.string().uuid().describe("The app UUID the review belongs to")
226
+ var generateReviewReplySchema = z3.object({
227
+ reviewId: z3.string().describe("The review UUID to generate a reply for"),
228
+ assetId: z3.string().uuid().describe("The app UUID the review belongs to")
219
229
  });
220
- var sendReviewReplySchema = z2.object({
221
- reviewId: z2.string().describe("The review UUID to reply to"),
222
- assetId: z2.string().uuid().describe("The app UUID the review belongs to"),
223
- response: z2.string().describe("The reply text to send")
230
+ var sendReviewReplySchema = z3.object({
231
+ reviewId: z3.string().describe("The review UUID to reply to"),
232
+ assetId: z3.string().uuid().describe("The app UUID the review belongs to"),
233
+ response: z3.string().describe("The reply text to send")
224
234
  });
225
- var translateReviewSchema = z2.object({
226
- reviewId: z2.string().describe("The review UUID to translate"),
227
- assetId: z2.string().uuid().describe("The app UUID the review belongs to"),
235
+ var translateReviewSchema = z3.object({
236
+ reviewId: z3.string().describe("The review UUID to translate"),
237
+ assetId: z3.string().uuid().describe("The app UUID the review belongs to"),
228
238
  // The translate endpoint receives the review content in the request body
229
239
  // (it does not re-fetch it). Pass the fields from a get_reviews result.
230
- rating: z2.number().int().min(1).max(5).describe("The review star rating, from get_reviews"),
231
- title: z2.string().default("").describe("The review title, from get_reviews"),
232
- body: z2.string().describe("The review text to translate, from get_reviews"),
233
- storeFront: z2.string().default("").describe('The review storefront (e.g. "SE"), from get_reviews'),
234
- appVersionString: z2.string().default("").describe("The app version the review was left on, from get_reviews")
240
+ rating: z3.number().int().min(1).max(5).describe("The review star rating, from get_reviews"),
241
+ title: z3.string().default("").describe("The review title, from get_reviews"),
242
+ body: z3.string().describe("The review text to translate, from get_reviews"),
243
+ storeFront: z3.string().default("").describe('The review storefront (e.g. "SE"), from get_reviews'),
244
+ appVersionString: z3.string().default("").describe("The app version the review was left on, from get_reviews")
235
245
  });
236
246
  async function getReviews(input, client) {
237
247
  try {
@@ -269,19 +279,7 @@ async function getReviews(input, client) {
269
279
  isError: true
270
280
  };
271
281
  }
272
- const params = {
273
- limit: input.limit
274
- };
275
- if (input.platform)
276
- params.platform = input.platform;
277
- if (input.rating !== void 0)
278
- params.rating = input.rating;
279
- if (input.replied !== void 0)
280
- params.responseStatus = input.replied ? "replied" : "unreplied";
281
- if (input.startDate)
282
- params.startDate = input.startDate;
283
- if (input.endDate)
284
- params.endDate = input.endDate;
282
+ const params = reviewQueryParameters(input);
285
283
  const response = await client.get(
286
284
  `/api/assets/${assetId}/reviews`,
287
285
  params
@@ -308,6 +306,8 @@ async function getReviews(input, client) {
308
306
  type: "text",
309
307
  text: formatAsJson({
310
308
  summary,
309
+ // Pass back as `cursor` to get the next page; null = last page.
310
+ nextCursor: response.data?.nextCursor ?? null,
311
311
  reviews: reviews.map((review) => ({
312
312
  id: review.id,
313
313
  appId: review.appId,
@@ -342,6 +342,19 @@ async function getReviews(input, client) {
342
342
  };
343
343
  }
344
344
  }
345
+ function reviewQueryParameters(input) {
346
+ const params = {
347
+ limit: input.limit
348
+ };
349
+ if (input.cursor) params.cursor = input.cursor;
350
+ if (input.platform) params.platform = input.platform;
351
+ if (input.rating !== void 0) params.rating = input.rating;
352
+ if (input.replied !== void 0)
353
+ params.responseStatus = input.replied ? "replied" : "unreplied";
354
+ if (input.startDate) params.startDate = input.startDate;
355
+ if (input.endDate) params.endDate = input.endDate;
356
+ return params;
357
+ }
345
358
  async function generateReviewReply(input, client) {
346
359
  try {
347
360
  const response = await client.post(
@@ -431,46 +444,141 @@ async function translateReview(input, client) {
431
444
  }
432
445
 
433
446
  // src/tools/analytics.ts
434
- import { z as z3 } from "zod";
435
- var discoverMetricsSchema = z3.object({
436
- assetId: z3.string().uuid().describe("App UUID to check available metrics for")
447
+ import { z as z4 } from "zod";
448
+ function summarize(points, change) {
449
+ const values = (Array.isArray(points) ? points : []).map((point) => point.value ?? point.total).filter((value) => typeof value === "number");
450
+ return {
451
+ value: change?.currentValue ?? null,
452
+ effectiveFromDate: change?.effectiveFromDate ?? null,
453
+ effectiveToDate: change?.effectiveToDate ?? null,
454
+ min: values.length > 0 ? Math.min(...values) : null,
455
+ max: values.length > 0 ? Math.max(...values) : null,
456
+ dataPoints: values.length
457
+ };
458
+ }
459
+ var discoverMetricsSchema = z4.object({
460
+ assetId: z4.string().uuid().describe("App UUID to check available metrics for")
437
461
  });
438
- var getMetricsSchema = z3.object({
439
- assetId: z3.string().uuid().describe("App UUID"),
440
- metrics: z3.array(z3.string()).min(1).describe('Metric names to query (e.g., ["proceeds", "totalDownloads"]). Use discover_metrics first to see available metrics.'),
441
- startDate: z3.string().optional().describe("Start date (YYYY-MM-DD). Defaults to 30 days ago."),
442
- endDate: z3.string().optional().describe("End date (YYYY-MM-DD). Defaults to today."),
443
- granularity: z3.enum(["daily", "weekly", "monthly"]).default("daily").describe("Data granularity"),
444
- dimension: z3.string().optional().describe('Optional dimension to break down by (e.g., "storefront" for country, "platform" for device). Use discover_dimensions to see options.'),
445
- dimensionFilter: z3.string().optional().describe('Filter to a specific dimension value (e.g., "US" when dimension is "storefront")')
462
+ var getMetricsSchema = z4.object({
463
+ assetId: z4.string().uuid().describe("App UUID"),
464
+ metrics: z4.array(z4.string()).min(1).describe(
465
+ 'Metric names to query (e.g., ["proceeds", "totalDownloads"]). Use discover_metrics first to see available metrics.'
466
+ ),
467
+ startDate: z4.string().optional().describe("Start date (YYYY-MM-DD). Defaults to 30 days ago."),
468
+ endDate: z4.string().optional().describe("End date (YYYY-MM-DD). Defaults to today."),
469
+ granularity: z4.enum(["daily", "weekly", "monthly"]).default("daily").describe("Data granularity"),
470
+ dimension: z4.string().optional().describe(
471
+ 'Optional dimension to break down by (e.g., "storefront" for country, "platform" for device). Use discover_dimensions to see options.'
472
+ ),
473
+ dimensionFilter: z4.string().optional().describe(
474
+ 'Filter to a specific dimension value (e.g., "US" when dimension is "storefront")'
475
+ )
446
476
  });
447
- var discoverDimensionsSchema = z3.object({
448
- assetId: z3.string().uuid().describe("App UUID"),
449
- dimension: z3.string().optional().describe('If provided, returns the available values for this dimension (e.g., countries for "storefront")')
477
+ var discoverDimensionsSchema = z4.object({
478
+ assetId: z4.string().uuid().describe("App UUID"),
479
+ dimension: z4.string().optional().describe(
480
+ 'If provided, returns the available values for this dimension (e.g., countries for "storefront")'
481
+ )
450
482
  });
451
483
  var METRIC_INFO = {
452
- proceeds: { displayName: "Net Revenue (after store cut)", category: "Revenue", type: "currency" },
453
- total_revenue: { displayName: "Gross Revenue", category: "Revenue", type: "currency" },
454
- total_downloads: { displayName: "Total Downloads", category: "Downloads", type: "count" },
455
- units: { displayName: "First-time Downloads", category: "Downloads", type: "count" },
456
- redownloads: { displayName: "Re-downloads", category: "Downloads", type: "count" },
457
- page_views: { displayName: "App Store Page Views", category: "Downloads", type: "count" },
458
- impressions: { displayName: "App Store Impressions", category: "Downloads", type: "count" },
459
- sessions: { displayName: "App Sessions", category: "Engagement", type: "count" },
460
- active_devices: { displayName: "Active Devices", category: "Engagement", type: "count" },
484
+ proceeds: {
485
+ displayName: "Net Revenue (after store cut)",
486
+ category: "Revenue",
487
+ type: "currency"
488
+ },
489
+ total_revenue: {
490
+ displayName: "Gross Revenue",
491
+ category: "Revenue",
492
+ type: "currency"
493
+ },
494
+ total_downloads: {
495
+ displayName: "Total Downloads",
496
+ category: "Downloads",
497
+ type: "count"
498
+ },
499
+ units: {
500
+ displayName: "First-time Downloads",
501
+ category: "Downloads",
502
+ type: "count"
503
+ },
504
+ redownloads: {
505
+ displayName: "Re-downloads",
506
+ category: "Downloads",
507
+ type: "count"
508
+ },
509
+ page_views: {
510
+ displayName: "App Store Page Views",
511
+ category: "Downloads",
512
+ type: "count"
513
+ },
514
+ impressions: {
515
+ displayName: "App Store Impressions",
516
+ category: "Downloads",
517
+ type: "count"
518
+ },
519
+ sessions: {
520
+ displayName: "App Sessions",
521
+ category: "Engagement",
522
+ type: "count"
523
+ },
524
+ active_devices: {
525
+ displayName: "Active Devices",
526
+ category: "Engagement",
527
+ type: "count"
528
+ },
461
529
  crashes: { displayName: "Crashes", category: "Engagement", type: "count" },
462
- paying_users: { displayName: "Paying Users", category: "Engagement", type: "count" },
463
- active_subs: { displayName: "Active Subscriptions", category: "Subscriptions", type: "count" },
464
- active_trials: { displayName: "Active Trials", category: "Subscriptions", type: "count" },
465
- new_trials: { displayName: "New Trials", category: "Subscriptions", type: "count" },
466
- trial_conversion_rate: { displayName: "Trial Conversion Rate", category: "Subscriptions", type: "percentage" },
467
- subscription_retention_rate: { displayName: "Subscription Retention Rate", category: "Subscriptions", type: "percentage" },
468
- products_sold: { displayName: "Products Sold (IAP)", category: "Revenue", type: "count" },
530
+ paying_users: {
531
+ displayName: "Paying Users",
532
+ category: "Engagement",
533
+ type: "count"
534
+ },
535
+ active_subs: {
536
+ displayName: "Active Subscriptions",
537
+ category: "Subscriptions",
538
+ type: "count"
539
+ },
540
+ active_trials: {
541
+ displayName: "Active Trials",
542
+ category: "Subscriptions",
543
+ type: "count"
544
+ },
545
+ new_trials: {
546
+ displayName: "New Trials",
547
+ category: "Subscriptions",
548
+ type: "count"
549
+ },
550
+ trial_conversion_rate: {
551
+ displayName: "Trial Conversion Rate",
552
+ category: "Subscriptions",
553
+ type: "percentage"
554
+ },
555
+ subscription_retention_rate: {
556
+ displayName: "Subscription Retention Rate",
557
+ category: "Subscriptions",
558
+ type: "percentage"
559
+ },
560
+ products_sold: {
561
+ displayName: "Products Sold (IAP)",
562
+ category: "Revenue",
563
+ type: "count"
564
+ },
469
565
  ad_spend: { displayName: "Ad Spend", category: "Ads", type: "currency" },
470
- ad_impressions: { displayName: "Ad Impressions", category: "Ads", type: "count" },
566
+ ad_impressions: {
567
+ displayName: "Ad Impressions",
568
+ category: "Ads",
569
+ type: "count"
570
+ },
471
571
  ad_taps: { displayName: "Ad Taps/Clicks", category: "Ads", type: "count" },
472
- ad_installs: { displayName: "Ad-attributed Installs", category: "Ads", type: "count" },
473
- ad_conversions: { displayName: "Ad Conversions", category: "Ads", type: "count" }
572
+ ad_installs: {
573
+ displayName: "Ad-attributed Installs",
574
+ category: "Ads",
575
+ type: "count"
576
+ },
577
+ ad_conversions: {
578
+ displayName: "Ad Conversions",
579
+ category: "Ads",
580
+ type: "count"
581
+ }
474
582
  };
475
583
  var DIMENSION_INFO = {
476
584
  storefront: "Country",
@@ -504,28 +612,32 @@ async function discoverMetrics(input, client) {
504
612
  });
505
613
  const byCategory = {};
506
614
  for (const m of enriched) {
507
- if (!byCategory[m.category])
508
- byCategory[m.category] = [];
509
- byCategory[m.category].push(m);
615
+ (byCategory[m.category] ??= []).push(m);
510
616
  }
511
617
  return {
512
- content: [{
513
- type: "text",
514
- text: formatAsJson({
515
- assetId: input.assetId,
516
- totalAvailable: availableMetrics.length,
517
- metricsByCategory: byCategory,
518
- dataGroups: metricGroups,
519
- tip: 'Use the metric "name" field in get_metrics. You can query multiple metrics at once.'
520
- })
521
- }]
618
+ content: [
619
+ {
620
+ type: "text",
621
+ text: formatAsJson({
622
+ assetId: input.assetId,
623
+ totalAvailable: availableMetrics.length,
624
+ metricsByCategory: byCategory,
625
+ dataGroups: metricGroups,
626
+ tip: 'Use the metric "name" field in get_metrics. You can query multiple metrics at once.'
627
+ })
628
+ }
629
+ ]
522
630
  };
523
631
  } catch (error) {
524
- return { content: [{ type: "text", text: formatError(error) }], isError: true };
632
+ return {
633
+ content: [{ type: "text", text: formatError(error) }],
634
+ isError: true
635
+ };
525
636
  }
526
637
  }
527
638
  async function getMetrics(input, client) {
528
639
  try {
640
+ const granularity = input.granularity ?? "daily";
529
641
  const endDate = input.endDate || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
530
642
  const startDate = input.startDate || (() => {
531
643
  const d = /* @__PURE__ */ new Date();
@@ -536,60 +648,53 @@ async function getMetrics(input, client) {
536
648
  metrics: input.metrics.join(","),
537
649
  fromDate: startDate,
538
650
  toDate: endDate,
539
- granularity: input.granularity
651
+ granularity
540
652
  };
541
- if (input.dimension)
542
- params.dimension = input.dimension;
653
+ if (input.dimension) params.dimension = input.dimension;
543
654
  if (input.dimensionFilter && input.dimension) {
544
655
  params[`filter.${input.dimension}`] = input.dimensionFilter;
545
656
  }
546
- const response = await client.get(
547
- `/api/assets/${input.assetId}/metrics/timeseries`,
548
- params
549
- );
657
+ const path = `/api/assets/${input.assetId}/metrics/timeseries`;
658
+ const response = await client.get(path, params);
659
+ const summaryResponse = input.granularity === "daily" ? response : await client.get(path, {
660
+ ...params,
661
+ granularity: "daily"
662
+ });
550
663
  const data = response.data ?? {};
551
- const changes = response.changes ?? {};
664
+ const changes = summaryResponse.changes ?? {};
552
665
  const meta = response.meta ?? {};
553
666
  const summaries = {};
554
- for (const [metricName, timeseries] of Object.entries(data)) {
555
- const points = timeseries;
556
- if (!Array.isArray(points) || points.length === 0) {
557
- summaries[metricName] = { total: 0, average: 0, min: 0, max: 0, dataPoints: 0 };
558
- continue;
559
- }
560
- const values = points.map((p) => p.value);
561
- const total = values.reduce((s, v) => s + v, 0);
562
- summaries[metricName] = {
563
- total: Math.round(total * 100) / 100,
564
- average: Math.round(total / values.length * 100) / 100,
565
- min: Math.min(...values),
566
- max: Math.max(...values),
567
- dataPoints: values.length
568
- };
667
+ for (const [metricName, points] of Object.entries(data)) {
668
+ summaries[metricName] = summarize(points, changes[metricName]);
569
669
  }
570
670
  const info = METRIC_INFO;
571
671
  return {
572
- content: [{
573
- type: "text",
574
- text: formatAsJson({
575
- assetId: input.assetId,
576
- dateRange: { start: startDate, end: endDate },
577
- granularity: input.granularity,
578
- dimension: input.dimension || null,
579
- metrics: Object.keys(data).map((name) => ({
580
- name,
581
- displayName: info[name]?.displayName || name,
582
- type: info[name]?.type || "count",
583
- summary: summaries[name],
584
- change: changes[name] || null
585
- })),
586
- timeseries: data,
587
- meta
588
- })
589
- }]
672
+ content: [
673
+ {
674
+ type: "text",
675
+ text: formatAsJson({
676
+ assetId: input.assetId,
677
+ dateRange: { start: startDate, end: endDate },
678
+ granularity,
679
+ dimension: input.dimension || null,
680
+ metrics: Object.keys(data).map((name) => ({
681
+ name,
682
+ displayName: info[name]?.displayName || name,
683
+ type: info[name]?.type || "count",
684
+ summary: summaries[name],
685
+ change: changes[name] || null
686
+ })),
687
+ timeseries: data,
688
+ meta
689
+ })
690
+ }
691
+ ]
590
692
  };
591
693
  } catch (error) {
592
- return { content: [{ type: "text", text: formatError(error) }], isError: true };
694
+ return {
695
+ content: [{ type: "text", text: formatError(error) }],
696
+ isError: true
697
+ };
593
698
  }
594
699
  }
595
700
  async function discoverDimensions(input, client) {
@@ -599,15 +704,17 @@ async function discoverDimensions(input, client) {
599
704
  `/api/assets/${input.assetId}/metrics/dimensions/${input.dimension}/values`
600
705
  );
601
706
  return {
602
- content: [{
603
- type: "text",
604
- text: formatAsJson({
605
- assetId: input.assetId,
606
- dimension: input.dimension,
607
- displayName: DIMENSION_INFO[input.dimension] || input.dimension,
608
- values: response2.data ?? response2
609
- })
610
- }]
707
+ content: [
708
+ {
709
+ type: "text",
710
+ text: formatAsJson({
711
+ assetId: input.assetId,
712
+ dimension: input.dimension,
713
+ displayName: DIMENSION_INFO[input.dimension] || input.dimension,
714
+ values: response2.data ?? response2
715
+ })
716
+ }
717
+ ]
611
718
  };
612
719
  }
613
720
  const response = await client.get(`/api/assets/${input.assetId}/metrics/dimensions`);
@@ -620,73 +727,65 @@ async function discoverDimensions(input, client) {
620
727
  return { name: id, displayName: dim.label ?? DIMENSION_INFO[id] ?? id };
621
728
  });
622
729
  return {
623
- content: [{
624
- type: "text",
625
- text: formatAsJson({
626
- assetId: input.assetId,
627
- dimensions: enriched,
628
- tip: 'Use dimension name in get_metrics "dimension" param. Use discover_dimensions with a specific dimension to see available values.'
629
- })
630
- }]
730
+ content: [
731
+ {
732
+ type: "text",
733
+ text: formatAsJson({
734
+ assetId: input.assetId,
735
+ dimensions: enriched,
736
+ tip: 'Use dimension name in get_metrics "dimension" param. Use discover_dimensions with a specific dimension to see available values.'
737
+ })
738
+ }
739
+ ]
631
740
  };
632
741
  } catch (error) {
633
- return { content: [{ type: "text", text: formatError(error) }], isError: true };
742
+ return {
743
+ content: [{ type: "text", text: formatError(error) }],
744
+ isError: true
745
+ };
634
746
  }
635
747
  }
636
748
 
637
749
  // src/tools/agents.ts
638
- import { z as z4 } from "zod";
750
+ import { z as z5 } from "zod";
639
751
  function asRecord(value) {
640
752
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
641
753
  }
642
- var AGENT_TYPES = [
643
- "review",
644
- "monitoring",
645
- "forecasting",
646
- "growth",
647
- "aso",
648
- "ads",
649
- "product",
650
- "submission_review"
651
- ];
754
+ var AGENT_TYPES = ["review", "aso"];
652
755
  var AGENT_DESCRIPTIONS = {
653
756
  review: "AI-powered review management \u2014 drafts and sends replies to app store reviews",
654
- monitoring: "Anomaly detection \u2014 monitors metrics for unusual changes in downloads, revenue, etc.",
655
- forecasting: "Revenue and metric forecasting \u2014 generates forward-looking projections",
656
- growth: "Growth audit \u2014 analyzes app performance and provides growth scoring",
657
- aso: "App Store Optimization \u2014 listing optimization suggestions for better visibility",
658
- ads: "Ad campaign analysis \u2014 performance tracking and optimization recommendations",
659
- product: "Product agent \u2014 automated app installation testing via BrowserStack",
660
- submission_review: "Submission review \u2014 GitHub-based review workflow for app submissions"
757
+ aso: "App Store Optimization \u2014 listing optimization suggestions for better visibility"
661
758
  };
662
- var listAgentsSchema = z4.object({});
663
- var getAgentDetailsSchema = z4.object({
664
- agentType: z4.enum(AGENT_TYPES).describe("The type of agent to get details for"),
665
- assetId: z4.string().uuid().optional().describe("App UUID to get agent config for (when agent is per-asset)")
759
+ var listAgentsSchema = z5.object({});
760
+ var getAgentDetailsSchema = z5.object({
761
+ agentType: z5.enum(AGENT_TYPES).describe("The type of agent to get details for"),
762
+ assetId: z5.string().uuid().optional().describe("App UUID to get agent config for (when agent is per-asset)")
666
763
  });
667
- var getAgentRunHistorySchema = z4.object({
668
- agentType: z4.enum(AGENT_TYPES).describe("The type of agent to get run history for"),
669
- assetId: z4.string().uuid().optional().describe("App UUID to filter runs"),
670
- limit: z4.number().int().min(1).max(100).default(20).describe("Maximum number of runs to return")
764
+ var getAgentRunHistorySchema = z5.object({
765
+ agentType: z5.enum(AGENT_TYPES).describe("The type of agent to get run history for"),
766
+ assetId: z5.string().uuid().optional().describe("App UUID to filter runs"),
767
+ limit: z5.number().int().min(1).max(100).default(20).describe("Maximum number of runs to return")
671
768
  });
672
- var triggerAgentRunSchema = z4.object({
673
- agentId: z4.string().describe("The agent ID to trigger a run for"),
674
- assetId: z4.string().uuid().optional().describe("Optional app UUID to run the agent against")
769
+ var triggerAgentRunSchema = z5.object({
770
+ agentId: z5.string().describe("The agent ID to trigger a run for (the `id` from list_agents)"),
771
+ assetId: z5.string().uuid().optional().describe("Optional app UUID to run the agent against")
675
772
  });
676
- var pauseAgentSchema = z4.object({
677
- agentId: z4.string().describe("The agent ID to pause")
773
+ var pauseAgentSchema = z5.object({
774
+ agentId: z5.string().describe("The agent ID to pause (the `id` from list_agents)")
678
775
  });
679
- var resumeAgentSchema = z4.object({
680
- agentId: z4.string().describe("The agent ID to resume")
776
+ var resumeAgentSchema = z5.object({
777
+ agentId: z5.string().describe("The agent ID to resume (the `id` from list_agents)")
681
778
  });
682
- var getAgentActivitySchema = z4.object({
683
- agentId: z4.string().describe("The agent ID to get activity for")
779
+ var getAgentActivitySchema = z5.object({
780
+ agentId: z5.string().describe("The agent ID to get activity for (the `id` from list_agents)")
684
781
  });
685
782
  async function listAgents(_input, client) {
686
783
  try {
687
784
  let apiAgents = null;
688
785
  try {
689
- const response = await client.get("/api/agents");
786
+ const response = await client.get(
787
+ "/api/agents"
788
+ );
690
789
  apiAgents = Array.isArray(response) ? response : response.data ?? response.agents ?? null;
691
790
  } catch {
692
791
  }
@@ -735,8 +834,7 @@ async function getAgentDetails(input, client) {
735
834
  try {
736
835
  try {
737
836
  const params = {};
738
- if (input.assetId)
739
- params.assetId = input.assetId;
837
+ if (input.assetId) params.assetId = input.assetId;
740
838
  const response2 = await client.get(`/api/agents/by-type/${input.agentType}`, params);
741
839
  if (response2.agent) {
742
840
  return {
@@ -783,8 +881,7 @@ async function getAgentRunHistory(input, client) {
783
881
  let agentId;
784
882
  try {
785
883
  const byTypeParams = {};
786
- if (input.assetId)
787
- byTypeParams.assetId = input.assetId;
884
+ if (input.assetId) byTypeParams.assetId = input.assetId;
788
885
  const byType = await client.get(
789
886
  `/api/agents/by-type/${input.agentType}`,
790
887
  byTypeParams
@@ -937,168 +1034,6 @@ async function getAgentActivity(input, client) {
937
1034
  }
938
1035
  }
939
1036
 
940
- // src/tools/anomalies.ts
941
- import { z as z5 } from "zod";
942
- var getAnomaliesSchema = z5.object({
943
- assetId: z5.string().uuid().optional().describe("Filter anomalies by app UUID"),
944
- severity: z5.enum(["low", "medium", "high", "critical"]).optional().describe("Filter by severity level"),
945
- type: z5.enum(["surge", "decline"]).optional().describe("Filter by anomaly type"),
946
- status: z5.enum(["new", "viewed", "acknowledged", "dismissed"]).optional().describe("Filter by status"),
947
- metricName: z5.string().optional().describe('Filter by metric name (e.g., "proceeds", "units")'),
948
- fromDate: z5.string().optional().describe("Filter anomalies from this date (YYYY-MM-DD)"),
949
- toDate: z5.string().optional().describe("Filter anomalies until this date (YYYY-MM-DD)"),
950
- excludeDismissed: z5.boolean().default(true).describe("Exclude dismissed anomalies (default: true)"),
951
- limit: z5.number().int().min(1).max(100).default(50).describe("Maximum number of anomalies to return")
952
- });
953
- var getAnomalyDetailSchema = z5.object({
954
- id: z5.string().uuid().describe("The anomaly UUID to get details for")
955
- });
956
- var acknowledgeAnomalySchema = z5.object({
957
- id: z5.string().uuid().describe("The anomaly UUID to acknowledge")
958
- });
959
- var dismissAnomalySchema = z5.object({
960
- id: z5.string().uuid().describe("The anomaly UUID to dismiss")
961
- });
962
- async function getAnomalies(input, client) {
963
- try {
964
- const params = {
965
- limit: input.limit
966
- };
967
- if (input.assetId)
968
- params.assetId = input.assetId;
969
- if (input.severity)
970
- params.severity = input.severity;
971
- if (input.type)
972
- params.type = input.type;
973
- if (input.status)
974
- params.status = input.status;
975
- if (input.metricName)
976
- params.metricName = input.metricName;
977
- if (input.fromDate)
978
- params.fromDate = input.fromDate;
979
- if (input.toDate)
980
- params.toDate = input.toDate;
981
- const response = await client.get(
982
- "/api/anomalies",
983
- params
984
- );
985
- let anomalies = response.data ?? response.anomalies ?? [];
986
- if (input.excludeDismissed && !input.status) {
987
- anomalies = anomalies.filter((a) => a.status !== "dismissed");
988
- }
989
- return {
990
- content: [
991
- {
992
- type: "text",
993
- text: formatAsJson({
994
- total: anomalies.length,
995
- anomalies: anomalies.map((anomaly) => ({
996
- id: anomaly.id,
997
- assetId: anomaly.assetId,
998
- assetName: anomaly.assetName,
999
- assetIcon: anomaly.assetIcon,
1000
- anomalyDate: anomaly.anomalyDate,
1001
- metricName: anomaly.metricName,
1002
- sourceType: anomaly.sourceType,
1003
- type: anomaly.type,
1004
- severity: anomaly.severity,
1005
- actualValue: parseFloat(String(anomaly.actualValue || "0")),
1006
- expectedValue: parseFloat(String(anomaly.expectedValue || "0")),
1007
- deviationPercent: parseFloat(
1008
- String(anomaly.deviationPercent || "0")
1009
- ),
1010
- confidence: parseFloat(String(anomaly.confidence || "0")),
1011
- explanation: anomaly.explanation,
1012
- suggestedActions: anomaly.suggestedActions,
1013
- status: anomaly.status,
1014
- detectedAt: anomaly.detectedAt
1015
- }))
1016
- })
1017
- }
1018
- ]
1019
- };
1020
- } catch (error) {
1021
- return {
1022
- content: [
1023
- {
1024
- type: "text",
1025
- text: formatError(error)
1026
- }
1027
- ],
1028
- isError: true
1029
- };
1030
- }
1031
- }
1032
- async function getAnomalyDetail(input, client) {
1033
- try {
1034
- const response = await client.get(`/api/anomalies/${input.id}`);
1035
- return {
1036
- content: [
1037
- {
1038
- type: "text",
1039
- text: formatAsJson(response)
1040
- }
1041
- ]
1042
- };
1043
- } catch (error) {
1044
- return {
1045
- content: [
1046
- {
1047
- type: "text",
1048
- text: formatError(error)
1049
- }
1050
- ],
1051
- isError: true
1052
- };
1053
- }
1054
- }
1055
- async function acknowledgeAnomaly(input, client) {
1056
- try {
1057
- const response = await client.patch(`/api/anomalies/${input.id}/acknowledge`);
1058
- return {
1059
- content: [
1060
- {
1061
- type: "text",
1062
- text: formatAsJson(response)
1063
- }
1064
- ]
1065
- };
1066
- } catch (error) {
1067
- return {
1068
- content: [
1069
- {
1070
- type: "text",
1071
- text: formatError(error)
1072
- }
1073
- ],
1074
- isError: true
1075
- };
1076
- }
1077
- }
1078
- async function dismissAnomaly(input, client) {
1079
- try {
1080
- const response = await client.patch(`/api/anomalies/${input.id}/dismiss`);
1081
- return {
1082
- content: [
1083
- {
1084
- type: "text",
1085
- text: formatAsJson(response)
1086
- }
1087
- ]
1088
- };
1089
- } catch (error) {
1090
- return {
1091
- content: [
1092
- {
1093
- type: "text",
1094
- text: formatError(error)
1095
- }
1096
- ],
1097
- isError: true
1098
- };
1099
- }
1100
- }
1101
-
1102
1037
  // src/tools/ads.ts
1103
1038
  import { z as z6 } from "zod";
1104
1039
  var getAdsPerformanceSchema = z6.object({
@@ -1111,14 +1046,11 @@ var getAdsPerformanceSchema = z6.object({
1111
1046
  async function getAdsPerformance(input, client) {
1112
1047
  try {
1113
1048
  const params = {};
1114
- if (input.assetId)
1115
- params.assetId = input.assetId;
1116
- if (input.fromDate)
1117
- params.from = input.fromDate;
1118
- if (input.toDate)
1119
- params.to = input.toDate;
1049
+ if (input.assetId) params.assetId = input.assetId;
1050
+ if (input.fromDate) params.from = input.fromDate;
1051
+ if (input.toDate) params.to = input.toDate;
1120
1052
  const response = await client.get(
1121
- "/api/ads-agent/campaigns",
1053
+ "/api/ads/campaigns",
1122
1054
  params
1123
1055
  );
1124
1056
  let campaigns = response.data ?? response.campaigns ?? [];
@@ -1132,6 +1064,12 @@ async function getAdsPerformance(input, client) {
1132
1064
  type: "text",
1133
1065
  text: formatAsJson({
1134
1066
  total: campaigns.length,
1067
+ // The server couldn't read the metrics: null spend is unknown,
1068
+ // never "no spend".
1069
+ ...response.metricsUnavailable ? {
1070
+ metricsUnavailable: true,
1071
+ note: "The ads metrics could not be read right now, so spend, impressions, taps and installs are unknown (null), not zero. Try again later."
1072
+ } : {},
1135
1073
  campaigns: campaigns.map((campaign) => ({
1136
1074
  id: campaign.id,
1137
1075
  assetId: campaign.assetId,
@@ -1168,114 +1106,19 @@ async function getAdsPerformance(input, client) {
1168
1106
  }
1169
1107
  }
1170
1108
 
1171
- // src/tools/growth.ts
1172
- import { z as z7 } from "zod";
1173
- var getGrowthAuditSchema = z7.object({
1174
- assetId: z7.string().uuid().describe("App UUID to audit")
1175
- });
1176
- var getGrowthScoreSchema = z7.object({
1177
- assetId: z7.string().uuid().describe("App UUID to score")
1178
- });
1179
- async function getGrowthAudit(input, client) {
1180
- try {
1181
- const response = await client.get(`/api/growth/audit/${input.assetId}`);
1182
- return {
1183
- content: [
1184
- {
1185
- type: "text",
1186
- text: formatAsJson(response.data || response)
1187
- }
1188
- ]
1189
- };
1190
- } catch (error) {
1191
- return {
1192
- content: [
1193
- {
1194
- type: "text",
1195
- text: formatError(error)
1196
- }
1197
- ],
1198
- isError: true
1199
- };
1200
- }
1201
- }
1202
- async function getGrowthScore(input, client) {
1203
- try {
1204
- const response = await client.get(`/api/growth/score/${input.assetId}`);
1205
- return {
1206
- content: [
1207
- {
1208
- type: "text",
1209
- text: formatAsJson(response.data || response)
1210
- }
1211
- ]
1212
- };
1213
- } catch (error) {
1214
- return {
1215
- content: [
1216
- {
1217
- type: "text",
1218
- text: formatError(error)
1219
- }
1220
- ],
1221
- isError: true
1222
- };
1223
- }
1224
- }
1225
-
1226
- // src/tools/forecasting.ts
1227
- import { z as z8 } from "zod";
1228
- var getForecastsSchema = z8.object({
1229
- assetId: z8.string().uuid().describe("App UUID to get forecasts for"),
1230
- metric: z8.enum(["proceeds", "total_revenue", "total_downloads", "active_subs", "new_trials"]).describe("The metric to forecast"),
1231
- forecastWeeks: z8.number().int().min(4).max(156).optional().describe("Weeks to forecast forward (default 104)"),
1232
- historicalWeeks: z8.number().int().min(12).max(156).optional().describe("Weeks of history to base the forecast on (default 104)")
1233
- });
1234
- async function getForecasts(input, client) {
1235
- try {
1236
- const response = await client.get("/api/forecasting/forecast", {
1237
- assetId: input.assetId,
1238
- metricName: input.metric,
1239
- forecastWeeks: input.forecastWeeks,
1240
- historicalWeeks: input.historicalWeeks
1241
- });
1242
- return {
1243
- content: [
1244
- {
1245
- type: "text",
1246
- text: formatAsJson(response.data || response)
1247
- }
1248
- ]
1249
- };
1250
- } catch (error) {
1251
- return {
1252
- content: [
1253
- {
1254
- type: "text",
1255
- text: formatError(error)
1256
- }
1257
- ],
1258
- isError: true
1259
- };
1260
- }
1261
- }
1262
-
1263
1109
  // src/tools/dashboard.ts
1264
- import { z as z9 } from "zod";
1110
+ import { z as z7 } from "zod";
1265
1111
  function parseDashboardNumber(value) {
1266
- if (value === null || value === void 0 || value === "")
1267
- return null;
1112
+ if (value === null || value === void 0 || value === "") return null;
1268
1113
  const parsed = typeof value === "number" ? value : Number.parseFloat(value);
1269
1114
  return Number.isFinite(parsed) ? parsed : null;
1270
1115
  }
1271
1116
  function getSidebarAssets(response) {
1272
- if (!response)
1273
- return [];
1274
- if (Array.isArray(response))
1275
- return response;
1117
+ if (!response) return [];
1118
+ if (Array.isArray(response)) return response;
1276
1119
  return response.data ?? [];
1277
1120
  }
1278
- var getDashboardOverviewSchema = z9.object({});
1121
+ var getDashboardOverviewSchema = z7.object({});
1279
1122
  async function getDashboardOverview(_input, client) {
1280
1123
  try {
1281
1124
  const overviewPromise = client.get("/api/dashboard/overview-metrics").catch(() => null);
@@ -1330,152 +1173,249 @@ async function getDashboardOverview(_input, client) {
1330
1173
  }
1331
1174
 
1332
1175
  // src/tools/actions.ts
1333
- import { z as z10 } from "zod";
1334
- function asRecord2(value) {
1335
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1176
+ import { randomUUID } from "node:crypto";
1177
+ import { z as z8 } from "zod";
1178
+
1179
+ // src/public-errors.ts
1180
+ var INTERNAL_ERROR_PATTERNS = [
1181
+ /\b(stack|trace|at\s+[\w.$<>]+\s*\()/i,
1182
+ /\b(sql|postgres|drizzle|database|constraint|duplicate key|violates|relation)\b/i,
1183
+ /\b(fetch|undici|socket|ECONNRESET|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|HTTP\s+\d{3})\b/i,
1184
+ /\b(token|secret|api[_-]?key|authorization|bearer|cookie|password)\b/i,
1185
+ /\b[a-z0-9]+_(secret|token|key)\b/i,
1186
+ /\b(secret|token|key)[_-][a-z0-9]+\b/i,
1187
+ /\b(scrap|browser|patchright|playwright|chromium|page\.|locator|selector)\b/i,
1188
+ /\b(redis|bullmq|queue|job id|worker)\b/i
1189
+ ];
1190
+ function looksInternal(message) {
1191
+ return INTERNAL_ERROR_PATTERNS.some((pattern) => pattern.test(message));
1192
+ }
1193
+ function publicMcpErrorMessage(message, fallbackMessage = "Fload could not complete the request. Please try again.") {
1194
+ const raw = message instanceof Error ? message.message : typeof message === "string" ? message : "";
1195
+ const normalized = raw.replace(/\s+/g, " ").trim();
1196
+ if (!normalized || normalized.length > 180 || looksInternal(normalized)) {
1197
+ return fallbackMessage;
1198
+ }
1199
+ return normalized;
1336
1200
  }
1337
- var listPendingActionsSchema = z10.object({
1338
- assetId: z10.string().uuid().optional().describe("Filter by app UUID"),
1339
- limit: z10.number().int().min(1).max(100).default(50).describe("Maximum number of actions to return")
1201
+
1202
+ // src/tools/actions.ts
1203
+ var listPendingActionsSchema = z8.object({
1204
+ assetId: z8.string().uuid().optional().describe("Filter by app UUID"),
1205
+ view: z8.enum(["open", "queued"]).default("open").describe(
1206
+ "open (default): items waiting on the user. queued: approved work Fload is sending or checking in the store (an item being checked offers check_now)."
1207
+ ),
1208
+ limit: z8.number().int().min(1).max(100).default(50).describe("Maximum number of actions to return")
1340
1209
  });
1341
- var approveActionSchema = z10.object({
1342
- actionId: z10.string().describe("The pending action ID to approve")
1210
+ var approveActionSchema = z8.object({
1211
+ actionId: z8.string().describe("The inbox item ID to approve (from list_pending_actions)")
1343
1212
  });
1344
- var rejectActionSchema = z10.object({
1345
- actionId: z10.string().describe("The draft reply ID to reject/delete")
1213
+ var rejectActionSchema = z8.object({
1214
+ actionId: z8.string().describe("The inbox item ID to reject (from list_pending_actions)"),
1215
+ reason: z8.string().trim().min(1).max(1e3).optional().describe(
1216
+ "Why, in the user's words. Kept with the rejection so the agents do not propose the same thing again."
1217
+ )
1346
1218
  });
1219
+ var checkActionNowSchema = z8.object({
1220
+ actionId: z8.string().describe(
1221
+ 'The inbox item ID to check now (from list_pending_actions with view "queued", or an approve_action result; its commands include check_now)'
1222
+ )
1223
+ });
1224
+ function commandFor(kind, intent) {
1225
+ if (kind === "notice")
1226
+ return intent === "approve" ? "acknowledge" : "dismiss";
1227
+ return intent;
1228
+ }
1229
+ function toolText(payload, isError = false) {
1230
+ return {
1231
+ content: [{ type: "text", text: formatAsJson(payload) }],
1232
+ ...isError ? { isError: true } : {}
1233
+ };
1234
+ }
1235
+ function toolError(error) {
1236
+ return {
1237
+ content: [{ type: "text", text: formatError(error) }],
1238
+ isError: true
1239
+ };
1240
+ }
1347
1241
  async function listPendingActions(input, client) {
1348
1242
  try {
1349
- const params = {
1350
- limit: input.limit
1351
- };
1352
1243
  const response = await client.get(
1353
- "/api/pending-actions",
1354
- params
1244
+ "/api/actions/items",
1245
+ { view: input.view ?? "open", assetId: input.assetId, limit: input.limit }
1355
1246
  );
1356
- let actions = response.data ?? response.actions ?? [];
1357
- if (input.assetId) {
1358
- actions = actions.filter(
1359
- (action) => action.assetId === input.assetId
1360
- );
1361
- }
1362
- return {
1363
- content: [
1364
- {
1365
- type: "text",
1366
- text: formatAsJson({
1367
- total: actions.length,
1368
- actions
1369
- })
1370
- }
1371
- ]
1372
- };
1247
+ const actions = response.items ?? [];
1248
+ return toolText({
1249
+ total: actions.length,
1250
+ actions,
1251
+ hasMore: Boolean(response.nextCursor)
1252
+ });
1373
1253
  } catch (error) {
1374
- return {
1375
- content: [
1376
- {
1377
- type: "text",
1378
- text: formatError(error)
1254
+ return toolError(error);
1255
+ }
1256
+ }
1257
+ async function commandItem(client, itemId, intent, reason) {
1258
+ const detail = await client.get(
1259
+ `/api/actions/items/${encodeURIComponent(itemId)}`
1260
+ );
1261
+ const item = detail.item;
1262
+ if (!item) throw new Error("Action not found");
1263
+ const command = commandFor(item.kind, intent);
1264
+ const answer = await client.postForAnswer(
1265
+ "/api/actions/commands",
1266
+ {
1267
+ command,
1268
+ idempotencyKey: `mcp:${command}:${item.id}:${randomUUID()}`,
1269
+ targets: [
1270
+ {
1271
+ itemId: item.id,
1272
+ ...command === "approve" && item.currentRevisionId ? { revisionId: item.currentRevisionId } : {}
1379
1273
  }
1380
1274
  ],
1381
- isError: true
1382
- };
1383
- }
1275
+ ...command === "reject" && reason ? { reason } : {}
1276
+ }
1277
+ );
1278
+ const result = answer.body?.results?.[0];
1279
+ if (!result)
1280
+ throw new Error(
1281
+ answer.ok ? "Fload returned no result for the command." : "Fload rejected the request. Please check access and try again."
1282
+ );
1283
+ return {
1284
+ command,
1285
+ result: {
1286
+ ...result,
1287
+ error: result.error ? publicMcpErrorMessage(
1288
+ result.error,
1289
+ "Fload could not apply this change."
1290
+ ) : void 0
1291
+ }
1292
+ };
1384
1293
  }
1385
1294
  async function approveAction(input, client) {
1386
1295
  try {
1387
- const response = await client.post(
1388
- `/api/pending-actions/${input.actionId}/approve`,
1389
- {}
1296
+ const { command, result } = await commandItem(
1297
+ client,
1298
+ input.actionId,
1299
+ "approve"
1300
+ );
1301
+ const applied = result?.result === "applied" || result?.result === "replayed";
1302
+ return toolText(
1303
+ {
1304
+ success: applied,
1305
+ actionId: input.actionId,
1306
+ command,
1307
+ result: result?.result ?? "unknown",
1308
+ ...result?.error ? { error: result.error } : {},
1309
+ message: applied ? command === "acknowledge" ? "Acknowledged." : "Approved. Fload delivers it after a short undo window; the inbox shows where it is." : result?.error ?? "The approval could not be recorded.",
1310
+ item: result?.item
1311
+ },
1312
+ !applied
1390
1313
  );
1391
- return {
1392
- content: [
1393
- {
1394
- type: "text",
1395
- text: formatAsJson({
1396
- success: true,
1397
- actionId: input.actionId,
1398
- status: "approved",
1399
- message: "Reply has been approved and queued for sending",
1400
- ...asRecord2(response.data)
1401
- })
1402
- }
1403
- ]
1404
- };
1405
1314
  } catch (error) {
1406
- return {
1407
- content: [
1408
- {
1409
- type: "text",
1410
- text: formatError(error)
1411
- }
1412
- ],
1413
- isError: true
1414
- };
1315
+ return toolError(error);
1415
1316
  }
1416
1317
  }
1417
1318
  async function rejectAction(input, client) {
1418
1319
  try {
1419
- const response = await client.post(
1420
- `/api/pending-actions/${input.actionId}/reject`
1320
+ const { command, result } = await commandItem(
1321
+ client,
1322
+ input.actionId,
1323
+ "reject",
1324
+ input.reason
1325
+ );
1326
+ const applied = result?.result === "applied" || result?.result === "replayed";
1327
+ return toolText(
1328
+ {
1329
+ success: applied,
1330
+ actionId: input.actionId,
1331
+ command,
1332
+ result: result?.result ?? "unknown",
1333
+ ...result?.error ? { error: result.error } : {},
1334
+ message: applied ? command === "dismiss" ? "Dismissed." : "Rejected. Nothing was sent." : result?.error ?? "The rejection could not be recorded.",
1335
+ item: result?.item
1336
+ },
1337
+ !applied
1421
1338
  );
1422
- return {
1423
- content: [
1424
- {
1425
- type: "text",
1426
- text: formatAsJson({
1427
- success: true,
1428
- actionId: input.actionId,
1429
- status: "rejected",
1430
- message: "Draft reply has been rejected and removed",
1431
- ...asRecord2(response.data)
1432
- })
1433
- }
1434
- ]
1435
- };
1436
1339
  } catch (error) {
1437
- return {
1438
- content: [
1439
- {
1440
- type: "text",
1441
- text: formatError(error)
1442
- }
1443
- ],
1444
- isError: true
1445
- };
1340
+ return toolError(error);
1341
+ }
1342
+ }
1343
+ async function checkActionNow(input, client) {
1344
+ try {
1345
+ const answer = await client.postForAnswer(
1346
+ "/api/actions/commands",
1347
+ {
1348
+ command: "check_now",
1349
+ idempotencyKey: `mcp:check_now:${input.actionId}:${randomUUID()}`,
1350
+ targets: [{ itemId: input.actionId }]
1351
+ }
1352
+ );
1353
+ const result = answer.body?.results?.[0];
1354
+ const applied = result?.result === "applied" || result?.result === "replayed";
1355
+ const error = result?.error ? publicMcpErrorMessage(result.error, "Fload could not check it now.") : void 0;
1356
+ return toolText(
1357
+ {
1358
+ success: applied,
1359
+ actionId: input.actionId,
1360
+ command: "check_now",
1361
+ result: result?.result ?? "unknown",
1362
+ ...error ? { error } : {},
1363
+ message: applied ? "Fload is checking the store now; the item updates as soon as the store shows the change." : error ?? (answer.ok ? "Fload returned no result for the command." : "Fload rejected the request. Please check access and try again."),
1364
+ item: result?.item
1365
+ },
1366
+ !applied
1367
+ );
1368
+ } catch (error) {
1369
+ return toolError(error);
1446
1370
  }
1447
1371
  }
1448
1372
 
1449
1373
  // src/tools/aso.ts
1450
- import { z as z11 } from "zod";
1451
- var getAsoSummarySchema = z11.object({
1452
- assetId: z11.string().uuid().describe("App UUID to get ASO summary for")
1374
+ import { z as z9 } from "zod";
1375
+ var getAsoSummarySchema = z9.object({
1376
+ assetId: z9.string().uuid().describe("App UUID to get ASO summary for")
1453
1377
  });
1454
- var getAsoRecommendationsSchema = z11.object({
1455
- assetId: z11.string().uuid().describe("App UUID to get ASO recommendations for")
1378
+ var getAsoRecommendationsSchema = z9.object({
1379
+ assetId: z9.string().uuid().describe("App UUID to get ASO recommendations for")
1456
1380
  });
1457
- var getAsoKeywordsSchema = z11.object({
1458
- assetId: z11.string().uuid().describe("App UUID to get keyword intelligence for"),
1459
- locale: z11.string().optional().describe('Locale code to filter keywords (e.g., "en-US", "de-DE"). Returns all locales if omitted.')
1381
+ var getAsoKeywordsSchema = z9.object({
1382
+ assetId: z9.string().uuid().describe("App UUID to get keyword intelligence for"),
1383
+ locale: z9.string().optional().describe(
1384
+ 'Locale code to filter keywords (e.g., "en-US", "de-DE"). Returns all locales if omitted.'
1385
+ )
1460
1386
  });
1461
- var getAsoExperimentsSchema = z11.object({
1462
- assetId: z11.string().uuid().describe("App UUID to list ASO experiments for"),
1463
- status: z11.enum(["proposed", "approved", "applied", "measuring", "completed", "reverted"]).optional().describe("Filter experiments by status"),
1464
- limit: z11.number().int().min(1).max(100).default(20).describe("Maximum number of experiments to return"),
1465
- cursor: z11.string().optional().describe("Pagination cursor from a previous response (meta.nextCursor)")
1387
+ var getAsoExperimentsSchema = z9.object({
1388
+ assetId: z9.string().uuid().describe("App UUID to list ASO experiments for"),
1389
+ status: z9.enum([
1390
+ "proposed",
1391
+ "approved",
1392
+ "applied",
1393
+ "measuring",
1394
+ "completed",
1395
+ "reverted"
1396
+ ]).optional().describe("Filter experiments by status"),
1397
+ limit: z9.number().int().min(1).max(100).default(20).describe("Maximum number of experiments to return"),
1398
+ cursor: z9.string().optional().describe("Pagination cursor from a previous response (meta.nextCursor)")
1466
1399
  });
1467
- var getAsoLocaleSnapshotsSchema = z11.object({
1468
- assetId: z11.string().uuid().describe("App UUID to get locale snapshots for"),
1469
- store: z11.enum(["ios", "android"]).default("ios").describe("Which store listing to read"),
1470
- locale: z11.string().optional().describe('Filter to a single locale (e.g. "en-US"). Returns all locales if omitted.'),
1471
- limit: z11.number().int().min(1).max(500).optional().describe("Maximum snapshot rows to return (newest first)")
1400
+ var getAsoLocaleSnapshotsSchema = z9.object({
1401
+ assetId: z9.string().uuid().describe("App UUID to get locale snapshots for"),
1402
+ store: z9.enum(["ios", "android"]).default("ios").describe("Which store listing to read"),
1403
+ locale: z9.string().optional().describe(
1404
+ 'Filter to a single locale (e.g. "en-US"). Returns all locales if omitted.'
1405
+ ),
1406
+ view: z9.enum(["latest", "history"]).default("latest").describe(
1407
+ '"latest" (default) = newest snapshot per (locale, type); "history" = raw revisions newest first'
1408
+ ),
1409
+ limit: z9.number().int().min(1).max(500).optional().describe("Maximum snapshot rows to return (newest first)")
1472
1410
  });
1473
- var triggerAsoAnalysisSchema = z11.object({
1474
- assetId: z11.string().uuid().describe("App UUID to trigger ASO analysis for")
1411
+ var triggerAsoAnalysisSchema = z9.object({
1412
+ assetId: z9.string().uuid().describe("App UUID to trigger ASO analysis for")
1475
1413
  });
1476
1414
  async function getAsoSummary(input, client) {
1477
1415
  try {
1478
- const response = await client.get(`/api/assets/${input.assetId}/aso/summary`);
1416
+ const response = await client.get(
1417
+ `/api/assets/${input.assetId}/aso/summary`
1418
+ );
1479
1419
  return {
1480
1420
  content: [
1481
1421
  {
@@ -1498,7 +1438,9 @@ async function getAsoSummary(input, client) {
1498
1438
  }
1499
1439
  async function getAsoRecommendations(input, client) {
1500
1440
  try {
1501
- const response = await client.get(`/api/assets/${input.assetId}/aso/recommendations`);
1441
+ const response = await client.get(
1442
+ `/api/assets/${input.assetId}/aso/recommendations`
1443
+ );
1502
1444
  return {
1503
1445
  content: [
1504
1446
  {
@@ -1522,9 +1464,11 @@ async function getAsoRecommendations(input, client) {
1522
1464
  async function getAsoKeywords(input, client) {
1523
1465
  try {
1524
1466
  const params = {};
1525
- if (input.locale)
1526
- params.locale = input.locale;
1527
- const response = await client.get(`/api/assets/${input.assetId}/aso/keyword-intelligence`, params);
1467
+ if (input.locale) params.locale = input.locale;
1468
+ const response = await client.get(
1469
+ `/api/assets/${input.assetId}/aso/keyword-intelligence`,
1470
+ params
1471
+ );
1528
1472
  return {
1529
1473
  content: [
1530
1474
  {
@@ -1551,9 +1495,11 @@ async function getAsoExperiments(input, client) {
1551
1495
  limit: input.limit,
1552
1496
  cursor: input.cursor
1553
1497
  };
1554
- if (input.status)
1555
- params.status = input.status;
1556
- const response = await client.get(`/api/assets/${input.assetId}/aso/experiments`, params);
1498
+ if (input.status) params.status = input.status;
1499
+ const response = await client.get(
1500
+ `/api/assets/${input.assetId}/aso/experiments`,
1501
+ params
1502
+ );
1557
1503
  return {
1558
1504
  content: [
1559
1505
  {
@@ -1581,6 +1527,7 @@ async function getAsoLocaleSnapshots(input, client) {
1581
1527
  {
1582
1528
  store: input.store,
1583
1529
  locale: input.locale,
1530
+ view: input.view,
1584
1531
  limit: input.limit
1585
1532
  }
1586
1533
  );
@@ -1630,20 +1577,40 @@ async function triggerAsoAnalysis(input, client) {
1630
1577
  };
1631
1578
  }
1632
1579
  }
1580
+ var getAsoEvidenceSchema = z9.object({ assetId: z9.string().uuid() });
1581
+ async function getAsoEvidence(input, client) {
1582
+ try {
1583
+ const response = await client.get(
1584
+ `/api/assets/${input.assetId}/aso/methodology`
1585
+ );
1586
+ return {
1587
+ content: [{ type: "text", text: formatAsJson(response) }]
1588
+ };
1589
+ } catch (error) {
1590
+ return {
1591
+ content: [{ type: "text", text: formatError(error) }],
1592
+ isError: true
1593
+ };
1594
+ }
1595
+ }
1633
1596
 
1634
1597
  // src/tools/chat.ts
1635
- import { randomUUID } from "node:crypto";
1636
- import { z as z12 } from "zod";
1637
- var listConversationsSchema = z12.object({
1638
- limit: z12.number().int().min(1).max(100).default(20).describe("Maximum number of conversations to return")
1598
+ import { randomUUID as randomUUID2 } from "node:crypto";
1599
+ import { z as z10 } from "zod";
1600
+ var listConversationsSchema = z10.object({
1601
+ limit: z10.number().int().min(1).max(100).default(20).describe("Maximum number of conversations to return")
1639
1602
  });
1640
- var getConversationMessagesSchema = z12.object({
1641
- conversationId: z12.string().uuid().describe("The conversation UUID to get messages for")
1603
+ var getConversationMessagesSchema = z10.object({
1604
+ conversationId: z10.string().uuid().describe("The conversation UUID to get messages for")
1642
1605
  });
1643
- var sendChatMessageSchema = z12.object({
1644
- message: z12.string().describe("The message to send to the AI chat"),
1645
- conversationId: z12.string().uuid().optional().describe("Existing conversation UUID to continue. Starts a new conversation if omitted."),
1646
- agentType: z12.string().optional().describe("Agent type to use for the conversation (e.g., review, monitoring, forecasting)")
1606
+ var sendChatMessageSchema = z10.object({
1607
+ message: z10.string().describe("The message to send to the AI chat"),
1608
+ conversationId: z10.string().uuid().optional().describe(
1609
+ "Existing conversation UUID to continue. Starts a new conversation if omitted."
1610
+ ),
1611
+ agentType: z10.string().optional().describe(
1612
+ "Agent type to use for the conversation (e.g., review, monitoring)"
1613
+ )
1647
1614
  });
1648
1615
  async function listConversations(input, client) {
1649
1616
  try {
@@ -1676,7 +1643,9 @@ async function listConversations(input, client) {
1676
1643
  }
1677
1644
  async function getConversationMessages(input, client) {
1678
1645
  try {
1679
- const response = await client.get(`/api/chat/messages/${input.conversationId}`);
1646
+ const response = await client.get(
1647
+ `/api/chat/messages/${input.conversationId}`
1648
+ );
1680
1649
  const messages = response.data || response.messages || response;
1681
1650
  return {
1682
1651
  content: [
@@ -1706,11 +1675,9 @@ function parseUiMessageStream(raw) {
1706
1675
  let reply = "";
1707
1676
  const toolsUsed = [];
1708
1677
  for (const line of raw.split("\n")) {
1709
- if (!line.startsWith("data:"))
1710
- continue;
1678
+ if (!line.startsWith("data:")) continue;
1711
1679
  const payload = line.slice(5).trim();
1712
- if (!payload || payload === "[DONE]")
1713
- continue;
1680
+ if (!payload || payload === "[DONE]") continue;
1714
1681
  try {
1715
1682
  const event = JSON.parse(payload);
1716
1683
  if (event.type === "text-delta") {
@@ -1725,7 +1692,7 @@ function parseUiMessageStream(raw) {
1725
1692
  }
1726
1693
  async function sendChatMessage(input, client) {
1727
1694
  try {
1728
- const conversationId = input.conversationId ?? randomUUID();
1695
+ const conversationId = input.conversationId ?? randomUUID2();
1729
1696
  let priorMessages = [];
1730
1697
  if (input.conversationId) {
1731
1698
  const history = await client.get(`/api/chat/messages/${input.conversationId}`, { limit: 1e3 });
@@ -1733,8 +1700,7 @@ async function sendChatMessage(input, client) {
1733
1700
  const textParts = (message.parts ?? []).filter(
1734
1701
  (part) => part.type === "text" && typeof part.text === "string"
1735
1702
  );
1736
- if (textParts.length === 0)
1737
- continue;
1703
+ if (textParts.length === 0) continue;
1738
1704
  priorMessages.push({
1739
1705
  id: message.id,
1740
1706
  role: message.role,
@@ -1748,7 +1714,7 @@ async function sendChatMessage(input, client) {
1748
1714
  messages: [
1749
1715
  ...priorMessages,
1750
1716
  {
1751
- id: randomUUID(),
1717
+ id: randomUUID2(),
1752
1718
  role: "user",
1753
1719
  parts: [{ type: "text", text: input.message }]
1754
1720
  }
@@ -1820,7 +1786,7 @@ function registerTools(server, client, options = {}) {
1820
1786
  {
1821
1787
  title,
1822
1788
  description,
1823
- inputSchema: schema.shape,
1789
+ inputSchema: schema,
1824
1790
  annotations: { title, ...annotations }
1825
1791
  },
1826
1792
  wrapTool(handler)
@@ -1877,7 +1843,7 @@ function registerTools(server, client, options = {}) {
1877
1843
  tool(
1878
1844
  "discover_metrics",
1879
1845
  "Discover available metrics",
1880
- "Discover what metrics are available for an app. Returns all available metrics organized by category (revenue, downloads, subscriptions, engagement, ads). Always call this first before querying metrics to know what data exists.",
1846
+ "Discover what metrics are available for an app. Returns all available metrics organized by category (revenue, downloads, subscriptions, engagement, ads). Use it before get_metrics when you don't yet know which metric names this app has data for.",
1881
1847
  discoverMetricsSchema,
1882
1848
  discoverMetrics,
1883
1849
  { readOnlyHint: true, openWorldHint: false }
@@ -1885,7 +1851,7 @@ function registerTools(server, client, options = {}) {
1885
1851
  tool(
1886
1852
  "get_metrics",
1887
1853
  "Get metrics",
1888
- "Query metric timeseries data for an app. Supports 30+ metrics (proceeds, totalDownloads, activeSubs, sessions, crashes, adSpend, etc.). Can query multiple metrics at once. Supports dimensional breakdowns (by country, platform, campaign). Use discover_metrics first to see available metrics.",
1854
+ "Query metric timeseries data for an app. Supports 30+ metrics (proceeds, totalDownloads, activeSubs, sessions, crashes, adSpend, adAvgCPA, etc.). Can query multiple metrics at once. Supports dimensional breakdowns (by country, platform, campaign). Each metric's summary.value is its value over the period, aggregated the right way for that metric: summed for flows like downloads, the latest value for levels like active subscriptions, and total over total for ratios like CPA. It covers summary.effectiveFromDate to summary.effectiveToDate: the requested days, less recent days whose data is not complete yet. Quote summary.value with that range rather than adding up the points. Use discover_metrics first to see available metrics.",
1889
1855
  getMetricsSchema,
1890
1856
  getMetrics,
1891
1857
  { readOnlyHint: true, openWorldHint: false }
@@ -1901,7 +1867,7 @@ function registerTools(server, client, options = {}) {
1901
1867
  tool(
1902
1868
  "list_agents",
1903
1869
  "List agents",
1904
- "List all available AI agents in the Fload platform with their current status. Returns agent types (review, monitoring, forecasting, growth, aso, ads, product, submission_review) and configuration status.",
1870
+ "List the AI agents activated in the user's organization, with their status. Each entry's `id` is the agentId that trigger_agent_run, pause_agent, resume_agent and get_agent_activity take. Only activated agents are listed; if an agent type is missing, it has not been activated for this organization (the user activates it from the Agents page in Fload). Entries without an `id` mean the live list could not be loaded.",
1905
1871
  listAgentsSchema,
1906
1872
  listAgents,
1907
1873
  { readOnlyHint: true, openWorldHint: false }
@@ -1909,7 +1875,7 @@ function registerTools(server, client, options = {}) {
1909
1875
  tool(
1910
1876
  "get_agent_details",
1911
1877
  "Get agent details",
1912
- "Get detailed configuration and status for a specific agent type. For the review agent, returns per-asset settings (mode, tone, custom instructions). For the product agent, returns latest run details.",
1878
+ "Get detailed configuration and status for a specific agent type. For the review agent, returns per-asset settings (mode, tone, custom instructions).",
1913
1879
  getAgentDetailsSchema,
1914
1880
  getAgentDetails,
1915
1881
  { readOnlyHint: true, openWorldHint: false }
@@ -1917,7 +1883,7 @@ function registerTools(server, client, options = {}) {
1917
1883
  tool(
1918
1884
  "get_agent_run_history",
1919
1885
  "Get agent run history",
1920
- "Get run history for a specific agent type. Currently available for the product agent (BrowserStack app installation runs). Returns run status, timing, and error details.",
1886
+ "Get run history for a specific agent type. Returns run status, timing, and error details.",
1921
1887
  getAgentRunHistorySchema,
1922
1888
  getAgentRunHistory,
1923
1889
  { readOnlyHint: true, openWorldHint: false }
@@ -1925,7 +1891,7 @@ function registerTools(server, client, options = {}) {
1925
1891
  tool(
1926
1892
  "trigger_agent_run",
1927
1893
  "Trigger agent run",
1928
- "Trigger a manual run for an agent. Optionally specify an asset (app) to run the agent against. Returns the triggered run details. Reversible in the sense that agent runs can be paused or dismissed.",
1894
+ "Trigger a manual run for an agent. Take the agentId from list_agents (the `id` of an activated agent). Optionally specify an asset (app) to run the agent against. Returns the triggered run details. Reversible in the sense that agent runs can be paused or dismissed.",
1929
1895
  triggerAgentRunSchema,
1930
1896
  triggerAgentRun,
1931
1897
  { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
@@ -1933,59 +1899,37 @@ function registerTools(server, client, options = {}) {
1933
1899
  tool(
1934
1900
  "pause_agent",
1935
1901
  "Pause agent",
1936
- "Pause a running agent. The agent will stop processing until resumed. Reversible via resume_agent.",
1902
+ "Pause a running agent. Take the agentId from list_agents (the `id` of an activated agent). The agent will stop processing until resumed. Reversible via resume_agent.",
1937
1903
  pauseAgentSchema,
1938
1904
  pauseAgent,
1939
- { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
1905
+ {
1906
+ readOnlyHint: false,
1907
+ destructiveHint: false,
1908
+ idempotentHint: true,
1909
+ openWorldHint: false
1910
+ }
1940
1911
  );
1941
1912
  tool(
1942
1913
  "resume_agent",
1943
1914
  "Resume agent",
1944
- "Resume a paused agent. The agent will continue processing from where it left off. Reversible via pause_agent.",
1915
+ "Resume a paused agent. Take the agentId from list_agents (the `id` of an activated agent). The agent will continue processing from where it left off. Reversible via pause_agent.",
1945
1916
  resumeAgentSchema,
1946
1917
  resumeAgent,
1947
- { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
1918
+ {
1919
+ readOnlyHint: false,
1920
+ destructiveHint: false,
1921
+ idempotentHint: true,
1922
+ openWorldHint: false
1923
+ }
1948
1924
  );
1949
1925
  tool(
1950
1926
  "get_agent_activity",
1951
1927
  "Get agent activity",
1952
- "Get the recent activity log for an agent. Returns a chronological list of actions the agent has taken, including timestamps, event types, and details.",
1928
+ "Get the recent activity log for an agent. Take the agentId from list_agents (the `id` of an activated agent). Returns a chronological list of actions the agent has taken, including timestamps, event types, and details.",
1953
1929
  getAgentActivitySchema,
1954
1930
  getAgentActivity,
1955
1931
  { readOnlyHint: true, openWorldHint: false }
1956
1932
  );
1957
- tool(
1958
- "get_anomalies",
1959
- "Get anomalies",
1960
- "Get detected anomalies (unusual metric changes) for your apps. Filter by app, severity (low/medium/high/critical), type (surge/decline), status, metric name, and date range. Returns actual vs expected values, deviation percentage, confidence, and suggested actions.",
1961
- getAnomaliesSchema,
1962
- getAnomalies,
1963
- { readOnlyHint: true, openWorldHint: false }
1964
- );
1965
- tool(
1966
- "get_anomaly_detail",
1967
- "Get anomaly detail",
1968
- "Get full detail for a single anomaly including chart data. Returns the anomaly metadata, actual vs expected values, and historical metric data points for visualization.",
1969
- getAnomalyDetailSchema,
1970
- getAnomalyDetail,
1971
- { readOnlyHint: true, openWorldHint: false }
1972
- );
1973
- tool(
1974
- "acknowledge_anomaly",
1975
- "Acknowledge anomaly",
1976
- 'Mark an anomaly as acknowledged. This updates the anomaly status from "new" to "acknowledged", indicating it has been reviewed but not dismissed. Reversible \u2014 anomaly can be reset or dismissed later.',
1977
- acknowledgeAnomalySchema,
1978
- acknowledgeAnomaly,
1979
- { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
1980
- );
1981
- tool(
1982
- "dismiss_anomaly",
1983
- "Dismiss anomaly",
1984
- 'Dismiss an anomaly. This updates the anomaly status to "dismissed", removing it from active alerts. Dismissed anomalies are excluded from queries by default. Soft state change \u2014 the anomaly row is preserved and can be un-dismissed later.',
1985
- dismissAnomalySchema,
1986
- dismissAnomaly,
1987
- { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
1988
- );
1989
1933
  tool(
1990
1934
  "get_ads_performance",
1991
1935
  "Get ads performance",
@@ -1994,34 +1938,10 @@ function registerTools(server, client, options = {}) {
1994
1938
  getAdsPerformance,
1995
1939
  { readOnlyHint: true, openWorldHint: false }
1996
1940
  );
1997
- tool(
1998
- "get_growth_audit",
1999
- "Get growth audit",
2000
- "Get a comprehensive growth audit for an app. Synthesizes data from review sentiment analysis, recent anomalies, valuation trends, and connector health into an actionable growth assessment.",
2001
- getGrowthAuditSchema,
2002
- getGrowthAudit,
2003
- { readOnlyHint: true, openWorldHint: false }
2004
- );
2005
- tool(
2006
- "get_growth_score",
2007
- "Get growth score",
2008
- "Get a calculated growth score (0-100) and grade (A-F) for an app. The score is based on app store rating, valuation trend, recent anomalies, review sentiment, and data connector health. Includes a breakdown of scoring factors.",
2009
- getGrowthScoreSchema,
2010
- getGrowthScore,
2011
- { readOnlyHint: true, openWorldHint: false }
2012
- );
2013
- tool(
2014
- "get_forecasts",
2015
- "Get forecasts",
2016
- "Get a statistical forecast for an app metric (proceeds, total_revenue, total_downloads, active_subs, or new_trials). Returns weekly historical values plus a forward projection with confidence bounds.",
2017
- getForecastsSchema,
2018
- getForecasts,
2019
- { readOnlyHint: true, openWorldHint: false }
2020
- );
2021
1941
  tool(
2022
1942
  "get_dashboard_overview",
2023
1943
  "Get dashboard overview",
2024
- "Get an aggregated dashboard overview for the organization. Returns portfolio summary (apps, valuations, ratings), data connector health status, and alerts (recent anomalies, pending review drafts).",
1944
+ "Get an aggregated dashboard overview for the organization. Returns portfolio summary (apps, valuations, ratings), data connector health status, and alerts (pending review drafts).",
2025
1945
  getDashboardOverviewSchema,
2026
1946
  getDashboardOverview,
2027
1947
  { readOnlyHint: true, openWorldHint: false }
@@ -2029,7 +1949,7 @@ function registerTools(server, client, options = {}) {
2029
1949
  tool(
2030
1950
  "list_pending_actions",
2031
1951
  "List pending actions",
2032
- "List pending actions awaiting approval. Currently shows AI-generated review draft replies that have not been sent yet. Includes the original review context and the drafted reply. Filter by app.",
1952
+ 'List the inbox items waiting on the user: agent proposals to approve (review replies, listing changes, Apple Search Ads changes, plans) and notices to act on. Each item carries its kind, title, status, inbox bucket, the app, and the commands it accepts. Filter by app. view "queued" lists approved work Fload is sending or checking in the store instead.',
2033
1953
  listPendingActionsSchema,
2034
1954
  listPendingActions,
2035
1955
  { readOnlyHint: true, openWorldHint: false }
@@ -2037,7 +1957,7 @@ function registerTools(server, client, options = {}) {
2037
1957
  tool(
2038
1958
  "approve_action",
2039
1959
  "Approve pending action",
2040
- "Approve a pending action (e.g., a review draft reply). Approving a review reply publishes it to the store \u2014 treat as destructive (publicly visible, cannot be silently undone). Optionally edit the reply text before approving.",
1960
+ "Approve an inbox item (actionId from list_pending_actions); a notice is acknowledged instead. Approving a review reply or a listing change publishes it to the store after a short undo window \u2014 treat as destructive (publicly visible, cannot be silently undone).",
2041
1961
  approveActionSchema,
2042
1962
  approveAction,
2043
1963
  { readOnlyHint: false, destructiveHint: true, openWorldHint: true }
@@ -2045,11 +1965,19 @@ function registerTools(server, client, options = {}) {
2045
1965
  tool(
2046
1966
  "reject_action",
2047
1967
  "Reject pending action",
2048
- "Reject a pending action (e.g., delete a review draft reply). The draft will be permanently removed. Destructive \u2014 not recoverable without regenerating the draft.",
1968
+ "Reject an inbox item (actionId from list_pending_actions); a notice is dismissed instead. Nothing is sent to the store. Pass the user's reason when they gave one: it is kept with the rejection so the agents do not propose the same thing again.",
2049
1969
  rejectActionSchema,
2050
1970
  rejectAction,
2051
1971
  { readOnlyHint: false, destructiveHint: true, openWorldHint: false }
2052
1972
  );
1973
+ tool(
1974
+ "check_action_now",
1975
+ "Check a change in the store now",
1976
+ 'For an inbox item Fload is reading back from the store (status verifying, its commands include check_now; list them with list_pending_actions view "queued"): read the store again now instead of at the next scheduled check. The item concludes as soon as the store shows the change. Nothing is written to the store. At most once every 30 seconds per item.',
1977
+ checkActionNowSchema,
1978
+ checkActionNow,
1979
+ { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
1980
+ );
2053
1981
  tool(
2054
1982
  "get_aso_summary",
2055
1983
  "Get ASO summary",
@@ -2066,6 +1994,14 @@ function registerTools(server, client, options = {}) {
2066
1994
  getAsoRecommendations,
2067
1995
  { readOnlyHint: true, openWorldHint: false }
2068
1996
  );
1997
+ tool(
1998
+ "get_aso_evidence",
1999
+ "Get ASO decisions and evidence",
2000
+ "Read ASO methodology assessments, per-object decisions, source evidence, limitations, ranking power, localization readiness and test plans. Records are newest first; historical approvals are not current execution permission. A priority score never overrides a blocked decision or the prohibition on competitor names in all metadata.",
2001
+ getAsoEvidenceSchema,
2002
+ getAsoEvidence,
2003
+ { readOnlyHint: true, openWorldHint: false }
2004
+ );
2069
2005
  tool(
2070
2006
  "get_aso_keywords",
2071
2007
  "Get ASO keywords",
@@ -2085,7 +2021,7 @@ function registerTools(server, client, options = {}) {
2085
2021
  tool(
2086
2022
  "get_aso_locale_snapshots",
2087
2023
  "Get ASO locale snapshots",
2088
- "Get current App Store and Google Play listing snapshots across all locales for an app. Returns the live title, subtitle, keywords, description, and promotional text for each locale. Useful for auditing localized metadata consistency.",
2024
+ 'Get current App Store and Google Play listing snapshots across all locales for an app. Returns the live title, subtitle, keywords, description, and promotional text for each locale \u2014 by default the latest snapshot per locale and type; pass view "history" for raw revisions newest first. Useful for auditing localized metadata consistency.',
2089
2025
  getAsoLocaleSnapshotsSchema,
2090
2026
  getAsoLocaleSnapshots,
2091
2027
  { readOnlyHint: true, openWorldHint: false }
@@ -2117,7 +2053,7 @@ function registerTools(server, client, options = {}) {
2117
2053
  tool(
2118
2054
  "send_chat_message",
2119
2055
  "Send chat message",
2120
- "Send a message to the Fload AI chat assistant. Starts a new conversation if no conversationId is provided, or continues an existing one. Optionally specify an agentType to route to a specialized agent (review, monitoring, forecasting, etc.). Adds a message to your chat history \u2014 not publicly visible.",
2056
+ "Send a message to the Fload AI chat assistant. Starts a new conversation if no conversationId is provided, or continues an existing one. Optionally specify an agentType to route to a specialized agent (review, aso). Adds a message to your chat history \u2014 not publicly visible.",
2121
2057
  sendChatMessageSchema,
2122
2058
  sendChatMessage,
2123
2059
  { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
@@ -2136,35 +2072,14 @@ async function createMcpServer(_config, client) {
2136
2072
  return server;
2137
2073
  }
2138
2074
 
2139
- // src/public-errors.ts
2140
- var INTERNAL_ERROR_PATTERNS = [
2141
- /\b(stack|trace|at\s+[\w.$<>]+\s*\()/i,
2142
- /\b(sql|postgres|drizzle|database|constraint|duplicate key|violates|relation)\b/i,
2143
- /\b(fetch|undici|socket|ECONNRESET|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|HTTP\s+\d{3})\b/i,
2144
- /\b(token|secret|api[_-]?key|authorization|bearer|cookie|password)\b/i,
2145
- /\b[a-z0-9]+_(secret|token|key)\b/i,
2146
- /\b(secret|token|key)[_-][a-z0-9]+\b/i,
2147
- /\b(scrap|browser|patchright|playwright|chromium|page\.|locator|selector)\b/i,
2148
- /\b(redis|bullmq|queue|job id|worker)\b/i
2149
- ];
2150
- function looksInternal(message) {
2151
- return INTERNAL_ERROR_PATTERNS.some((pattern) => pattern.test(message));
2152
- }
2153
- function publicMcpErrorMessage(message, fallbackMessage = "Fload could not complete the request. Please try again.") {
2154
- const raw = message instanceof Error ? message.message : typeof message === "string" ? message : "";
2155
- const normalized = raw.replace(/\s+/g, " ").trim();
2156
- if (!normalized || normalized.length > 180 || looksInternal(normalized)) {
2157
- return fallbackMessage;
2158
- }
2159
- return normalized;
2160
- }
2161
-
2162
2075
  // src/api-client.ts
2163
2076
  var FloadApiClient = class {
2164
2077
  constructor(baseUrl, apiKey) {
2165
2078
  this.baseUrl = baseUrl;
2166
2079
  this.apiKey = apiKey;
2167
2080
  }
2081
+ baseUrl;
2082
+ apiKey;
2168
2083
  async request(path, options = {}) {
2169
2084
  const url = `${this.baseUrl}${path}`;
2170
2085
  const headers = {
@@ -2190,8 +2105,7 @@ var FloadApiClient = class {
2190
2105
  const searchParams = new URLSearchParams();
2191
2106
  if (params) {
2192
2107
  for (const [key, value] of Object.entries(params)) {
2193
- if (value !== void 0)
2194
- searchParams.set(key, String(value));
2108
+ if (value !== void 0) searchParams.set(key, String(value));
2195
2109
  }
2196
2110
  }
2197
2111
  const query = searchParams.toString();
@@ -2203,6 +2117,24 @@ var FloadApiClient = class {
2203
2117
  body: body ? JSON.stringify(body) : void 0
2204
2118
  });
2205
2119
  }
2120
+ /**
2121
+ * POST that hands back the answer instead of throwing on a non-2xx status:
2122
+ * for endpoints whose refusals carry a structured body (FLO-1595: the
2123
+ * Actions commands answer one target with that target's own status and
2124
+ * reason). `body` is null when the response is not JSON.
2125
+ */
2126
+ async postForAnswer(path, body) {
2127
+ const response = await fetch(`${this.baseUrl}${path}`, {
2128
+ method: "POST",
2129
+ headers: {
2130
+ Authorization: `Bearer ${this.apiKey}`,
2131
+ ...body ? { "Content-Type": "application/json" } : {}
2132
+ },
2133
+ body: body ? JSON.stringify(body) : void 0
2134
+ });
2135
+ const parsed = await response.json().catch(() => null);
2136
+ return { ok: response.ok, status: response.status, body: parsed };
2137
+ }
2206
2138
  async patch(path, body) {
2207
2139
  return this.request(path, {
2208
2140
  method: "PATCH",
@@ -2251,7 +2183,10 @@ async function main() {
2251
2183
  await client.get("/api/assets", { limit: 1, offset: 0 });
2252
2184
  console.error("[Fload MCP] API connection verified");
2253
2185
  } catch (error) {
2254
- console.error("[Fload MCP] Warning: API connection test failed:", error instanceof Error ? error.message : error);
2186
+ console.error(
2187
+ "[Fload MCP] Warning: API connection test failed:",
2188
+ error instanceof Error ? error.message : error
2189
+ );
2255
2190
  console.error("[Fload MCP] Continuing anyway \u2014 API may become available");
2256
2191
  }
2257
2192
  const server = await createMcpServer(config, client);