@fload-ai/mcp 0.6.0 → 0.8.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 +747 -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 +668 -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 +27 -33
  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 +666 -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,342 @@ 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")
1209
+ });
1210
+ var approveActionSchema = z8.object({
1211
+ actionId: z8.string().describe("The inbox item ID to approve (from list_pending_actions)")
1340
1212
  });
1341
- var approveActionSchema = z10.object({
1342
- actionId: z10.string().describe("The pending action ID to approve")
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
+ )
1343
1218
  });
1344
- var rejectActionSchema = z10.object({
1345
- actionId: z10.string().describe("The draft reply ID to reject/delete")
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
+ )
1346
1223
  });
1224
+ var renameCustomPageActionSchema = z8.object({
1225
+ actionId: z8.string().describe(
1226
+ 'The inbox item ID of the "Create custom product page" request (from list_pending_actions; it failed because App Store Connect already has a page of that name, or it waits for approval)'
1227
+ ),
1228
+ name: z8.string().trim().min(1).max(100).describe(
1229
+ "The new page name: at most 100 characters (UTF-16 units), not its current name, not a page the app already has"
1230
+ )
1231
+ });
1232
+ function commandFor(kind, intent) {
1233
+ if (kind === "notice")
1234
+ return intent === "approve" ? "acknowledge" : "dismiss";
1235
+ return intent;
1236
+ }
1237
+ function toolText(payload, isError = false) {
1238
+ return {
1239
+ content: [{ type: "text", text: formatAsJson(payload) }],
1240
+ ...isError ? { isError: true } : {}
1241
+ };
1242
+ }
1243
+ function toolError(error) {
1244
+ return {
1245
+ content: [{ type: "text", text: formatError(error) }],
1246
+ isError: true
1247
+ };
1248
+ }
1347
1249
  async function listPendingActions(input, client) {
1348
1250
  try {
1349
- const params = {
1350
- limit: input.limit
1351
- };
1352
1251
  const response = await client.get(
1353
- "/api/pending-actions",
1354
- params
1252
+ "/api/actions/items",
1253
+ { view: input.view ?? "open", assetId: input.assetId, limit: input.limit }
1355
1254
  );
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
- };
1255
+ const actions = response.items ?? [];
1256
+ return toolText({
1257
+ total: actions.length,
1258
+ actions,
1259
+ hasMore: Boolean(response.nextCursor)
1260
+ });
1373
1261
  } catch (error) {
1374
- return {
1375
- content: [
1376
- {
1377
- type: "text",
1378
- text: formatError(error)
1262
+ return toolError(error);
1263
+ }
1264
+ }
1265
+ async function commandItem(client, itemId, intent, reason) {
1266
+ const detail = await client.get(
1267
+ `/api/actions/items/${encodeURIComponent(itemId)}`
1268
+ );
1269
+ const item = detail.item;
1270
+ if (!item) throw new Error("Action not found");
1271
+ const command = commandFor(item.kind, intent);
1272
+ const answer = await client.postForAnswer(
1273
+ "/api/actions/commands",
1274
+ {
1275
+ command,
1276
+ idempotencyKey: `mcp:${command}:${item.id}:${randomUUID()}`,
1277
+ targets: [
1278
+ {
1279
+ itemId: item.id,
1280
+ ...command === "approve" && item.currentRevisionId ? { revisionId: item.currentRevisionId } : {}
1379
1281
  }
1380
1282
  ],
1381
- isError: true
1382
- };
1383
- }
1283
+ ...command === "reject" && reason ? { reason } : {}
1284
+ }
1285
+ );
1286
+ const result = answer.body?.results?.[0];
1287
+ if (!result)
1288
+ throw new Error(
1289
+ answer.ok ? "Fload returned no result for the command." : "Fload rejected the request. Please check access and try again."
1290
+ );
1291
+ return {
1292
+ command,
1293
+ result: {
1294
+ ...result,
1295
+ error: result.error ? publicMcpErrorMessage(
1296
+ result.error,
1297
+ "Fload could not apply this change."
1298
+ ) : void 0
1299
+ }
1300
+ };
1384
1301
  }
1385
1302
  async function approveAction(input, client) {
1386
1303
  try {
1387
- const response = await client.post(
1388
- `/api/pending-actions/${input.actionId}/approve`,
1389
- {}
1304
+ const { command, result } = await commandItem(
1305
+ client,
1306
+ input.actionId,
1307
+ "approve"
1308
+ );
1309
+ const applied2 = result?.result === "applied" || result?.result === "replayed";
1310
+ return toolText(
1311
+ {
1312
+ success: applied2,
1313
+ actionId: input.actionId,
1314
+ command,
1315
+ result: result?.result ?? "unknown",
1316
+ ...result?.error ? { error: result.error } : {},
1317
+ message: applied2 ? 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.",
1318
+ item: result?.item
1319
+ },
1320
+ !applied2
1390
1321
  );
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
1322
  } catch (error) {
1406
- return {
1407
- content: [
1408
- {
1409
- type: "text",
1410
- text: formatError(error)
1411
- }
1412
- ],
1413
- isError: true
1414
- };
1323
+ return toolError(error);
1415
1324
  }
1416
1325
  }
1417
1326
  async function rejectAction(input, client) {
1418
1327
  try {
1419
- const response = await client.post(
1420
- `/api/pending-actions/${input.actionId}/reject`
1328
+ const { command, result } = await commandItem(
1329
+ client,
1330
+ input.actionId,
1331
+ "reject",
1332
+ input.reason
1333
+ );
1334
+ const applied2 = result?.result === "applied" || result?.result === "replayed";
1335
+ return toolText(
1336
+ {
1337
+ success: applied2,
1338
+ actionId: input.actionId,
1339
+ command,
1340
+ result: result?.result ?? "unknown",
1341
+ ...result?.error ? { error: result.error } : {},
1342
+ message: applied2 ? command === "dismiss" ? "Dismissed." : "Rejected. Nothing was sent." : result?.error ?? "The rejection could not be recorded.",
1343
+ item: result?.item
1344
+ },
1345
+ !applied2
1421
1346
  );
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
1347
  } catch (error) {
1437
- return {
1438
- content: [
1439
- {
1440
- type: "text",
1441
- text: formatError(error)
1442
- }
1443
- ],
1444
- isError: true
1445
- };
1348
+ return toolError(error);
1349
+ }
1350
+ }
1351
+ async function checkActionNow(input, client) {
1352
+ try {
1353
+ const answer = await client.postForAnswer(
1354
+ "/api/actions/commands",
1355
+ {
1356
+ command: "check_now",
1357
+ idempotencyKey: `mcp:check_now:${input.actionId}:${randomUUID()}`,
1358
+ targets: [{ itemId: input.actionId }]
1359
+ }
1360
+ );
1361
+ const result = answer.body?.results?.[0];
1362
+ const applied2 = result?.result === "applied" || result?.result === "replayed";
1363
+ const error = result?.error ? publicMcpErrorMessage(result.error, "Fload could not check it now.") : void 0;
1364
+ return toolText(
1365
+ {
1366
+ success: applied2,
1367
+ actionId: input.actionId,
1368
+ command: "check_now",
1369
+ result: result?.result ?? "unknown",
1370
+ ...error ? { error } : {},
1371
+ message: applied2 ? "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."),
1372
+ item: result?.item
1373
+ },
1374
+ !applied2
1375
+ );
1376
+ } catch (error) {
1377
+ return toolError(error);
1378
+ }
1379
+ }
1380
+ var applied = (result) => result?.result === "applied" || result?.result === "replayed";
1381
+ async function sendItemCommand(client, body) {
1382
+ const { command, itemId, revisionId, ...extra } = body;
1383
+ const answer = await client.postForAnswer(
1384
+ "/api/actions/commands",
1385
+ {
1386
+ command,
1387
+ idempotencyKey: `mcp:${command}:${itemId}:${randomUUID()}`,
1388
+ targets: [{ itemId, ...revisionId ? { revisionId } : {} }],
1389
+ ...extra
1390
+ }
1391
+ );
1392
+ const result = answer.body?.results?.[0];
1393
+ if (applied(result)) return { result, refusal: null };
1394
+ const said = result?.error ?? answer.body?.message;
1395
+ return {
1396
+ result,
1397
+ refusal: publicMcpErrorMessage(
1398
+ said,
1399
+ answer.ok ? "Fload returned no result for the command." : "Fload rejected the request. Please check access and try again."
1400
+ )
1401
+ };
1402
+ }
1403
+ function renameAnswer(input, outcome, item) {
1404
+ const success = outcome.renamed && outcome.approved;
1405
+ return toolText(
1406
+ {
1407
+ success,
1408
+ actionId: input.actionId,
1409
+ ...outcome,
1410
+ ...item === void 0 ? {} : { item }
1411
+ },
1412
+ !success
1413
+ );
1414
+ }
1415
+ async function renameCustomPageAction(input, client) {
1416
+ try {
1417
+ const name = input.name.trim();
1418
+ const detail = await client.get(
1419
+ `/api/actions/items/${encodeURIComponent(input.actionId)}`
1420
+ );
1421
+ const item = detail.item;
1422
+ if (!item || item.kind !== "asc_custom_product_page" || !item.subjectKey?.startsWith("asc-cpp:"))
1423
+ return renameAnswer(input, {
1424
+ renamed: false,
1425
+ approved: false,
1426
+ message: "This item is not a request to create a custom product page."
1427
+ });
1428
+ const edit = await sendItemCommand(client, {
1429
+ command: "edit",
1430
+ itemId: item.id,
1431
+ revisionId: item.currentRevisionId,
1432
+ pageName: name
1433
+ });
1434
+ if (edit.refusal)
1435
+ return renameAnswer(input, {
1436
+ renamed: false,
1437
+ approved: false,
1438
+ message: edit.refusal
1439
+ });
1440
+ const renamed = edit.result?.item;
1441
+ const approve = await sendItemCommand(client, {
1442
+ command: "approve",
1443
+ itemId: item.id,
1444
+ revisionId: renamed?.currentRevisionId ?? null
1445
+ });
1446
+ return renameAnswer(
1447
+ input,
1448
+ approve.refusal ? {
1449
+ renamed: true,
1450
+ approved: false,
1451
+ // The server's own refusal, as it said it.
1452
+ message: approve.refusal,
1453
+ next: `The page is renamed to \u201C${name}\u201D and waits for approval (approve_action).`
1454
+ } : {
1455
+ renamed: true,
1456
+ approved: true,
1457
+ message: `Renamed to \u201C${name}\u201D and approved. Fload creates the page after a short undo window; the inbox shows where it is.`
1458
+ },
1459
+ approve.result?.item ?? renamed
1460
+ );
1461
+ } catch (error) {
1462
+ return toolError(error);
1446
1463
  }
1447
1464
  }
1448
1465
 
1449
1466
  // 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")
1467
+ import { z as z9 } from "zod";
1468
+ var getAsoSummarySchema = z9.object({
1469
+ assetId: z9.string().uuid().describe("App UUID to get ASO summary for")
1453
1470
  });
1454
- var getAsoRecommendationsSchema = z11.object({
1455
- assetId: z11.string().uuid().describe("App UUID to get ASO recommendations for")
1471
+ var getAsoRecommendationsSchema = z9.object({
1472
+ assetId: z9.string().uuid().describe("App UUID to get ASO recommendations for")
1456
1473
  });
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.')
1474
+ var getAsoKeywordsSchema = z9.object({
1475
+ assetId: z9.string().uuid().describe("App UUID to get keyword intelligence for"),
1476
+ locale: z9.string().optional().describe(
1477
+ 'Locale code to filter keywords (e.g., "en-US", "de-DE"). Returns all locales if omitted.'
1478
+ )
1460
1479
  });
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)")
1480
+ var getAsoExperimentsSchema = z9.object({
1481
+ assetId: z9.string().uuid().describe("App UUID to list ASO experiments for"),
1482
+ status: z9.enum([
1483
+ "proposed",
1484
+ "approved",
1485
+ "applied",
1486
+ "measuring",
1487
+ "completed",
1488
+ "reverted"
1489
+ ]).optional().describe("Filter experiments by status"),
1490
+ limit: z9.number().int().min(1).max(100).default(20).describe("Maximum number of experiments to return"),
1491
+ cursor: z9.string().optional().describe("Pagination cursor from a previous response (meta.nextCursor)")
1466
1492
  });
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)")
1493
+ var getAsoLocaleSnapshotsSchema = z9.object({
1494
+ assetId: z9.string().uuid().describe("App UUID to get locale snapshots for"),
1495
+ store: z9.enum(["ios", "android"]).default("ios").describe("Which store listing to read"),
1496
+ locale: z9.string().optional().describe(
1497
+ 'Filter to a single locale (e.g. "en-US"). Returns all locales if omitted.'
1498
+ ),
1499
+ view: z9.enum(["latest", "history"]).default("latest").describe(
1500
+ '"latest" (default) = newest snapshot per (locale, type); "history" = raw revisions newest first'
1501
+ ),
1502
+ limit: z9.number().int().min(1).max(500).optional().describe("Maximum snapshot rows to return (newest first)")
1472
1503
  });
1473
- var triggerAsoAnalysisSchema = z11.object({
1474
- assetId: z11.string().uuid().describe("App UUID to trigger ASO analysis for")
1504
+ var triggerAsoAnalysisSchema = z9.object({
1505
+ assetId: z9.string().uuid().describe("App UUID to trigger ASO analysis for")
1475
1506
  });
1476
1507
  async function getAsoSummary(input, client) {
1477
1508
  try {
1478
- const response = await client.get(`/api/assets/${input.assetId}/aso/summary`);
1509
+ const response = await client.get(
1510
+ `/api/assets/${input.assetId}/aso/summary`
1511
+ );
1479
1512
  return {
1480
1513
  content: [
1481
1514
  {
@@ -1498,7 +1531,9 @@ async function getAsoSummary(input, client) {
1498
1531
  }
1499
1532
  async function getAsoRecommendations(input, client) {
1500
1533
  try {
1501
- const response = await client.get(`/api/assets/${input.assetId}/aso/recommendations`);
1534
+ const response = await client.get(
1535
+ `/api/assets/${input.assetId}/aso/recommendations`
1536
+ );
1502
1537
  return {
1503
1538
  content: [
1504
1539
  {
@@ -1522,9 +1557,11 @@ async function getAsoRecommendations(input, client) {
1522
1557
  async function getAsoKeywords(input, client) {
1523
1558
  try {
1524
1559
  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);
1560
+ if (input.locale) params.locale = input.locale;
1561
+ const response = await client.get(
1562
+ `/api/assets/${input.assetId}/aso/keyword-intelligence`,
1563
+ params
1564
+ );
1528
1565
  return {
1529
1566
  content: [
1530
1567
  {
@@ -1551,9 +1588,11 @@ async function getAsoExperiments(input, client) {
1551
1588
  limit: input.limit,
1552
1589
  cursor: input.cursor
1553
1590
  };
1554
- if (input.status)
1555
- params.status = input.status;
1556
- const response = await client.get(`/api/assets/${input.assetId}/aso/experiments`, params);
1591
+ if (input.status) params.status = input.status;
1592
+ const response = await client.get(
1593
+ `/api/assets/${input.assetId}/aso/experiments`,
1594
+ params
1595
+ );
1557
1596
  return {
1558
1597
  content: [
1559
1598
  {
@@ -1581,6 +1620,7 @@ async function getAsoLocaleSnapshots(input, client) {
1581
1620
  {
1582
1621
  store: input.store,
1583
1622
  locale: input.locale,
1623
+ view: input.view,
1584
1624
  limit: input.limit
1585
1625
  }
1586
1626
  );
@@ -1630,20 +1670,40 @@ async function triggerAsoAnalysis(input, client) {
1630
1670
  };
1631
1671
  }
1632
1672
  }
1673
+ var getAsoEvidenceSchema = z9.object({ assetId: z9.string().uuid() });
1674
+ async function getAsoEvidence(input, client) {
1675
+ try {
1676
+ const response = await client.get(
1677
+ `/api/assets/${input.assetId}/aso/methodology`
1678
+ );
1679
+ return {
1680
+ content: [{ type: "text", text: formatAsJson(response) }]
1681
+ };
1682
+ } catch (error) {
1683
+ return {
1684
+ content: [{ type: "text", text: formatError(error) }],
1685
+ isError: true
1686
+ };
1687
+ }
1688
+ }
1633
1689
 
1634
1690
  // 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")
1691
+ import { randomUUID as randomUUID2 } from "node:crypto";
1692
+ import { z as z10 } from "zod";
1693
+ var listConversationsSchema = z10.object({
1694
+ limit: z10.number().int().min(1).max(100).default(20).describe("Maximum number of conversations to return")
1639
1695
  });
1640
- var getConversationMessagesSchema = z12.object({
1641
- conversationId: z12.string().uuid().describe("The conversation UUID to get messages for")
1696
+ var getConversationMessagesSchema = z10.object({
1697
+ conversationId: z10.string().uuid().describe("The conversation UUID to get messages for")
1642
1698
  });
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)")
1699
+ var sendChatMessageSchema = z10.object({
1700
+ message: z10.string().describe("The message to send to the AI chat"),
1701
+ conversationId: z10.string().uuid().optional().describe(
1702
+ "Existing conversation UUID to continue. Starts a new conversation if omitted."
1703
+ ),
1704
+ agentType: z10.string().optional().describe(
1705
+ "Agent type to use for the conversation (e.g., review, monitoring)"
1706
+ )
1647
1707
  });
1648
1708
  async function listConversations(input, client) {
1649
1709
  try {
@@ -1676,7 +1736,9 @@ async function listConversations(input, client) {
1676
1736
  }
1677
1737
  async function getConversationMessages(input, client) {
1678
1738
  try {
1679
- const response = await client.get(`/api/chat/messages/${input.conversationId}`);
1739
+ const response = await client.get(
1740
+ `/api/chat/messages/${input.conversationId}`
1741
+ );
1680
1742
  const messages = response.data || response.messages || response;
1681
1743
  return {
1682
1744
  content: [
@@ -1706,11 +1768,9 @@ function parseUiMessageStream(raw) {
1706
1768
  let reply = "";
1707
1769
  const toolsUsed = [];
1708
1770
  for (const line of raw.split("\n")) {
1709
- if (!line.startsWith("data:"))
1710
- continue;
1771
+ if (!line.startsWith("data:")) continue;
1711
1772
  const payload = line.slice(5).trim();
1712
- if (!payload || payload === "[DONE]")
1713
- continue;
1773
+ if (!payload || payload === "[DONE]") continue;
1714
1774
  try {
1715
1775
  const event = JSON.parse(payload);
1716
1776
  if (event.type === "text-delta") {
@@ -1725,7 +1785,7 @@ function parseUiMessageStream(raw) {
1725
1785
  }
1726
1786
  async function sendChatMessage(input, client) {
1727
1787
  try {
1728
- const conversationId = input.conversationId ?? randomUUID();
1788
+ const conversationId = input.conversationId ?? randomUUID2();
1729
1789
  let priorMessages = [];
1730
1790
  if (input.conversationId) {
1731
1791
  const history = await client.get(`/api/chat/messages/${input.conversationId}`, { limit: 1e3 });
@@ -1733,8 +1793,7 @@ async function sendChatMessage(input, client) {
1733
1793
  const textParts = (message.parts ?? []).filter(
1734
1794
  (part) => part.type === "text" && typeof part.text === "string"
1735
1795
  );
1736
- if (textParts.length === 0)
1737
- continue;
1796
+ if (textParts.length === 0) continue;
1738
1797
  priorMessages.push({
1739
1798
  id: message.id,
1740
1799
  role: message.role,
@@ -1748,7 +1807,7 @@ async function sendChatMessage(input, client) {
1748
1807
  messages: [
1749
1808
  ...priorMessages,
1750
1809
  {
1751
- id: randomUUID(),
1810
+ id: randomUUID2(),
1752
1811
  role: "user",
1753
1812
  parts: [{ type: "text", text: input.message }]
1754
1813
  }
@@ -1820,7 +1879,7 @@ function registerTools(server, client, options = {}) {
1820
1879
  {
1821
1880
  title,
1822
1881
  description,
1823
- inputSchema: schema.shape,
1882
+ inputSchema: schema,
1824
1883
  annotations: { title, ...annotations }
1825
1884
  },
1826
1885
  wrapTool(handler)
@@ -1877,7 +1936,7 @@ function registerTools(server, client, options = {}) {
1877
1936
  tool(
1878
1937
  "discover_metrics",
1879
1938
  "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.",
1939
+ "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
1940
  discoverMetricsSchema,
1882
1941
  discoverMetrics,
1883
1942
  { readOnlyHint: true, openWorldHint: false }
@@ -1885,7 +1944,7 @@ function registerTools(server, client, options = {}) {
1885
1944
  tool(
1886
1945
  "get_metrics",
1887
1946
  "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.",
1947
+ "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
1948
  getMetricsSchema,
1890
1949
  getMetrics,
1891
1950
  { readOnlyHint: true, openWorldHint: false }
@@ -1901,7 +1960,7 @@ function registerTools(server, client, options = {}) {
1901
1960
  tool(
1902
1961
  "list_agents",
1903
1962
  "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.",
1963
+ "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
1964
  listAgentsSchema,
1906
1965
  listAgents,
1907
1966
  { readOnlyHint: true, openWorldHint: false }
@@ -1909,7 +1968,7 @@ function registerTools(server, client, options = {}) {
1909
1968
  tool(
1910
1969
  "get_agent_details",
1911
1970
  "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.",
1971
+ "Get detailed configuration and status for a specific agent type. For the review agent, returns per-asset settings (mode, tone, custom instructions).",
1913
1972
  getAgentDetailsSchema,
1914
1973
  getAgentDetails,
1915
1974
  { readOnlyHint: true, openWorldHint: false }
@@ -1917,7 +1976,7 @@ function registerTools(server, client, options = {}) {
1917
1976
  tool(
1918
1977
  "get_agent_run_history",
1919
1978
  "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.",
1979
+ "Get run history for a specific agent type. Returns run status, timing, and error details.",
1921
1980
  getAgentRunHistorySchema,
1922
1981
  getAgentRunHistory,
1923
1982
  { readOnlyHint: true, openWorldHint: false }
@@ -1925,7 +1984,7 @@ function registerTools(server, client, options = {}) {
1925
1984
  tool(
1926
1985
  "trigger_agent_run",
1927
1986
  "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.",
1987
+ "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
1988
  triggerAgentRunSchema,
1930
1989
  triggerAgentRun,
1931
1990
  { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
@@ -1933,59 +1992,37 @@ function registerTools(server, client, options = {}) {
1933
1992
  tool(
1934
1993
  "pause_agent",
1935
1994
  "Pause agent",
1936
- "Pause a running agent. The agent will stop processing until resumed. Reversible via resume_agent.",
1995
+ "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
1996
  pauseAgentSchema,
1938
1997
  pauseAgent,
1939
- { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
1998
+ {
1999
+ readOnlyHint: false,
2000
+ destructiveHint: false,
2001
+ idempotentHint: true,
2002
+ openWorldHint: false
2003
+ }
1940
2004
  );
1941
2005
  tool(
1942
2006
  "resume_agent",
1943
2007
  "Resume agent",
1944
- "Resume a paused agent. The agent will continue processing from where it left off. Reversible via pause_agent.",
2008
+ "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
2009
  resumeAgentSchema,
1946
2010
  resumeAgent,
1947
- { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
2011
+ {
2012
+ readOnlyHint: false,
2013
+ destructiveHint: false,
2014
+ idempotentHint: true,
2015
+ openWorldHint: false
2016
+ }
1948
2017
  );
1949
2018
  tool(
1950
2019
  "get_agent_activity",
1951
2020
  "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.",
2021
+ "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
2022
  getAgentActivitySchema,
1954
2023
  getAgentActivity,
1955
2024
  { readOnlyHint: true, openWorldHint: false }
1956
2025
  );
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
2026
  tool(
1990
2027
  "get_ads_performance",
1991
2028
  "Get ads performance",
@@ -1994,34 +2031,10 @@ function registerTools(server, client, options = {}) {
1994
2031
  getAdsPerformance,
1995
2032
  { readOnlyHint: true, openWorldHint: false }
1996
2033
  );
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
2034
  tool(
2022
2035
  "get_dashboard_overview",
2023
2036
  "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).",
2037
+ "Get an aggregated dashboard overview for the organization. Returns portfolio summary (apps, valuations, ratings), data connector health status, and alerts (pending review drafts).",
2025
2038
  getDashboardOverviewSchema,
2026
2039
  getDashboardOverview,
2027
2040
  { readOnlyHint: true, openWorldHint: false }
@@ -2029,7 +2042,7 @@ function registerTools(server, client, options = {}) {
2029
2042
  tool(
2030
2043
  "list_pending_actions",
2031
2044
  "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.",
2045
+ '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
2046
  listPendingActionsSchema,
2034
2047
  listPendingActions,
2035
2048
  { readOnlyHint: true, openWorldHint: false }
@@ -2037,7 +2050,7 @@ function registerTools(server, client, options = {}) {
2037
2050
  tool(
2038
2051
  "approve_action",
2039
2052
  "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.",
2053
+ "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
2054
  approveActionSchema,
2042
2055
  approveAction,
2043
2056
  { readOnlyHint: false, destructiveHint: true, openWorldHint: true }
@@ -2045,11 +2058,27 @@ function registerTools(server, client, options = {}) {
2045
2058
  tool(
2046
2059
  "reject_action",
2047
2060
  "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.",
2061
+ "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
2062
  rejectActionSchema,
2050
2063
  rejectAction,
2051
2064
  { readOnlyHint: false, destructiveHint: true, openWorldHint: false }
2052
2065
  );
2066
+ tool(
2067
+ "check_action_now",
2068
+ "Check a change in the store now",
2069
+ '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.',
2070
+ checkActionNowSchema,
2071
+ checkActionNow,
2072
+ { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
2073
+ );
2074
+ tool(
2075
+ "rename_custom_page_action",
2076
+ "Rename a custom product page request and send it",
2077
+ 'For a "Create custom product page" inbox item (actionId from list_pending_actions) that App Store Connect refused because the app already has a page of that name, or one still waiting for approval: rename it (name: at most 100 characters, not its current name, not a page the app already has) and approve it again on the same item. Fload then creates the page under the new name after a short undo window. Treat as destructive: it creates a page in App Store Connect. If the approve is refused, the item keeps its new name and waits for approval.',
2078
+ renameCustomPageActionSchema,
2079
+ renameCustomPageAction,
2080
+ { readOnlyHint: false, destructiveHint: true, openWorldHint: true }
2081
+ );
2053
2082
  tool(
2054
2083
  "get_aso_summary",
2055
2084
  "Get ASO summary",
@@ -2066,6 +2095,14 @@ function registerTools(server, client, options = {}) {
2066
2095
  getAsoRecommendations,
2067
2096
  { readOnlyHint: true, openWorldHint: false }
2068
2097
  );
2098
+ tool(
2099
+ "get_aso_evidence",
2100
+ "Get ASO decisions and evidence",
2101
+ "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.",
2102
+ getAsoEvidenceSchema,
2103
+ getAsoEvidence,
2104
+ { readOnlyHint: true, openWorldHint: false }
2105
+ );
2069
2106
  tool(
2070
2107
  "get_aso_keywords",
2071
2108
  "Get ASO keywords",
@@ -2085,7 +2122,7 @@ function registerTools(server, client, options = {}) {
2085
2122
  tool(
2086
2123
  "get_aso_locale_snapshots",
2087
2124
  "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.",
2125
+ '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
2126
  getAsoLocaleSnapshotsSchema,
2090
2127
  getAsoLocaleSnapshots,
2091
2128
  { readOnlyHint: true, openWorldHint: false }
@@ -2117,7 +2154,7 @@ function registerTools(server, client, options = {}) {
2117
2154
  tool(
2118
2155
  "send_chat_message",
2119
2156
  "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.",
2157
+ "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
2158
  sendChatMessageSchema,
2122
2159
  sendChatMessage,
2123
2160
  { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
@@ -2136,35 +2173,14 @@ async function createMcpServer(_config, client) {
2136
2173
  return server;
2137
2174
  }
2138
2175
 
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
2176
  // src/api-client.ts
2163
2177
  var FloadApiClient = class {
2164
2178
  constructor(baseUrl, apiKey) {
2165
2179
  this.baseUrl = baseUrl;
2166
2180
  this.apiKey = apiKey;
2167
2181
  }
2182
+ baseUrl;
2183
+ apiKey;
2168
2184
  async request(path, options = {}) {
2169
2185
  const url = `${this.baseUrl}${path}`;
2170
2186
  const headers = {
@@ -2190,8 +2206,7 @@ var FloadApiClient = class {
2190
2206
  const searchParams = new URLSearchParams();
2191
2207
  if (params) {
2192
2208
  for (const [key, value] of Object.entries(params)) {
2193
- if (value !== void 0)
2194
- searchParams.set(key, String(value));
2209
+ if (value !== void 0) searchParams.set(key, String(value));
2195
2210
  }
2196
2211
  }
2197
2212
  const query = searchParams.toString();
@@ -2203,6 +2218,24 @@ var FloadApiClient = class {
2203
2218
  body: body ? JSON.stringify(body) : void 0
2204
2219
  });
2205
2220
  }
2221
+ /**
2222
+ * POST that hands back the answer instead of throwing on a non-2xx status:
2223
+ * for endpoints whose refusals carry a structured body (FLO-1595: the
2224
+ * Actions commands answer one target with that target's own status and
2225
+ * reason). `body` is null when the response is not JSON.
2226
+ */
2227
+ async postForAnswer(path, body) {
2228
+ const response = await fetch(`${this.baseUrl}${path}`, {
2229
+ method: "POST",
2230
+ headers: {
2231
+ Authorization: `Bearer ${this.apiKey}`,
2232
+ ...body ? { "Content-Type": "application/json" } : {}
2233
+ },
2234
+ body: body ? JSON.stringify(body) : void 0
2235
+ });
2236
+ const parsed = await response.json().catch(() => null);
2237
+ return { ok: response.ok, status: response.status, body: parsed };
2238
+ }
2206
2239
  async patch(path, body) {
2207
2240
  return this.request(path, {
2208
2241
  method: "PATCH",
@@ -2251,7 +2284,10 @@ async function main() {
2251
2284
  await client.get("/api/assets", { limit: 1, offset: 0 });
2252
2285
  console.error("[Fload MCP] API connection verified");
2253
2286
  } catch (error) {
2254
- console.error("[Fload MCP] Warning: API connection test failed:", error instanceof Error ? error.message : error);
2287
+ console.error(
2288
+ "[Fload MCP] Warning: API connection test failed:",
2289
+ error instanceof Error ? error.message : error
2290
+ );
2255
2291
  console.error("[Fload MCP] Continuing anyway \u2014 API may become available");
2256
2292
  }
2257
2293
  const server = await createMcpServer(config, client);