@fload-ai/mcp 0.12.4 → 0.13.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 (49) hide show
  1. package/README.md +37 -33
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/bin.d.ts.map +1 -1
  4. package/dist/bin.js +144 -2492
  5. package/dist/bin.js.map +4 -4
  6. package/dist/index.d.ts +2 -4
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +162 -2486
  9. package/dist/index.js.map +4 -4
  10. package/dist/proxy.d.ts +7 -0
  11. package/dist/proxy.d.ts.map +1 -0
  12. package/package.json +4 -11
  13. package/skill/SKILL.md +69 -0
  14. package/dist/api-client.d.ts +0 -17
  15. package/dist/api-client.d.ts.map +0 -1
  16. package/dist/api-client.js +0 -152
  17. package/dist/api-client.js.map +0 -7
  18. package/dist/lib/format.d.ts +0 -5
  19. package/dist/lib/format.d.ts.map +0 -1
  20. package/dist/public-errors.d.ts +0 -4
  21. package/dist/public-errors.d.ts.map +0 -1
  22. package/dist/rate-limiter.d.ts +0 -12
  23. package/dist/rate-limiter.d.ts.map +0 -1
  24. package/dist/server.d.ts +0 -5
  25. package/dist/server.d.ts.map +0 -1
  26. package/dist/tools/actions.d.ts +0 -61
  27. package/dist/tools/actions.d.ts.map +0 -1
  28. package/dist/tools/ads.d.ts +0 -28
  29. package/dist/tools/ads.d.ts.map +0 -1
  30. package/dist/tools/agents.d.ts +0 -123
  31. package/dist/tools/agents.d.ts.map +0 -1
  32. package/dist/tools/analytics.d.ts +0 -63
  33. package/dist/tools/analytics.d.ts.map +0 -1
  34. package/dist/tools/apps.d.ts +0 -40
  35. package/dist/tools/apps.d.ts.map +0 -1
  36. package/dist/tools/aso.d.ts +0 -136
  37. package/dist/tools/aso.d.ts.map +0 -1
  38. package/dist/tools/chat.d.ts +0 -63
  39. package/dist/tools/chat.d.ts.map +0 -1
  40. package/dist/tools/dashboard.d.ts +0 -17
  41. package/dist/tools/dashboard.d.ts.map +0 -1
  42. package/dist/tools/download-impact.d.ts +0 -27
  43. package/dist/tools/download-impact.d.ts.map +0 -1
  44. package/dist/tools/index.d.ts +0 -18
  45. package/dist/tools/index.d.ts.map +0 -1
  46. package/dist/tools/index.js +0 -2416
  47. package/dist/tools/index.js.map +0 -7
  48. package/dist/tools/reviews.d.ts +0 -91
  49. package/dist/tools/reviews.d.ts.map +0 -1
@@ -1,2416 +0,0 @@
1
- // src/rate-limiter.ts
2
- var RateLimiter = class {
3
- constructor(maxCalls = 100, windowMs = 6e4) {
4
- this.maxCalls = maxCalls;
5
- this.windowMs = windowMs;
6
- }
7
- maxCalls;
8
- windowMs;
9
- calls = /* @__PURE__ */ new Map();
10
- check(key) {
11
- const now = Date.now();
12
- const windowStart = now - this.windowMs;
13
- let timestamps = this.calls.get(key) || [];
14
- timestamps = timestamps.filter((t) => t > windowStart);
15
- if (timestamps.length >= this.maxCalls) {
16
- const [oldestInWindow] = timestamps;
17
- const retryAfterMs = oldestInWindow === void 0 ? Number.NaN : oldestInWindow + this.windowMs - now;
18
- this.calls.set(key, timestamps);
19
- return { allowed: false, remaining: 0, retryAfterMs };
20
- }
21
- timestamps.push(now);
22
- this.calls.set(key, timestamps);
23
- return {
24
- allowed: true,
25
- remaining: this.maxCalls - timestamps.length,
26
- retryAfterMs: 0
27
- };
28
- }
29
- };
30
-
31
- // src/tools/apps.ts
32
- import { z } from "zod";
33
-
34
- // src/lib/format.ts
35
- function formatAsJson(data) {
36
- return JSON.stringify(data, null, 2);
37
- }
38
- function formatError(error) {
39
- if (error instanceof Error) {
40
- return `Error: ${error.message}`;
41
- }
42
- return `Unknown error: ${String(error)}`;
43
- }
44
-
45
- // src/tools/apps.ts
46
- var listAppsSchema = z.object({
47
- platform: z.enum(["ios", "android"]).optional().describe("Filter by platform (ios or android)"),
48
- limit: z.number().int().min(1).max(100).default(50).describe("Maximum number of apps to return")
49
- });
50
- var getAppDetailsSchema = z.object({
51
- assetId: z.string().uuid().optional().describe("App UUID from Fload database"),
52
- bundleId: z.string().optional().describe("App bundle ID (e.g., com.example.app)")
53
- });
54
- async function listApps(input, client) {
55
- try {
56
- const response = await client.get("/api/assets", {
57
- limit: input.limit,
58
- offset: 0,
59
- // The listing hides assets without a valuation by default; "list all
60
- // apps" must include apps that haven't been valued yet (FLO-734).
61
- includeUnvalued: "true"
62
- });
63
- const apps = response.data ?? [];
64
- const filtered = input.platform ? apps.filter((app) => {
65
- if (input.platform === "ios") return !!app.appleAppId;
66
- if (input.platform === "android") return !!app.googleAppId;
67
- return true;
68
- }) : apps;
69
- return {
70
- content: [
71
- {
72
- type: "text",
73
- text: formatAsJson({
74
- total: filtered.length,
75
- apps: filtered.map((app) => ({
76
- id: app.id,
77
- name: app.name,
78
- bundleId: app.bundleId,
79
- platform: app.appleAppId ? "ios" : app.googleAppId ? "android" : "unknown",
80
- addedAt: app.updatedAt || app.createdAt
81
- }))
82
- })
83
- }
84
- ]
85
- };
86
- } catch (error) {
87
- return {
88
- content: [
89
- {
90
- type: "text",
91
- text: formatError(error)
92
- }
93
- ],
94
- isError: true
95
- };
96
- }
97
- }
98
- async function getAppDetails(input, client) {
99
- try {
100
- if (!input.assetId && !input.bundleId) {
101
- throw new Error("Either assetId or bundleId must be provided");
102
- }
103
- let assetId = input.assetId;
104
- if (!assetId && input.bundleId) {
105
- const allApps = await client.get("/api/assets", {
106
- limit: 100,
107
- offset: 0,
108
- includeUnvalued: "true"
109
- });
110
- const match = (allApps.data ?? []).find(
111
- (app2) => app2.bundleId === input.bundleId
112
- );
113
- if (!match) {
114
- return {
115
- content: [
116
- {
117
- type: "text",
118
- text: "App not found with that bundle ID"
119
- }
120
- ],
121
- isError: true
122
- };
123
- }
124
- assetId = match.id;
125
- }
126
- const response = await client.get(
127
- `/api/assets/${assetId}`
128
- );
129
- const app = response.data;
130
- if (!app) {
131
- throw new Error("App details response did not include app data");
132
- }
133
- return {
134
- content: [
135
- {
136
- type: "text",
137
- text: formatAsJson({
138
- id: app.id,
139
- name: app.name,
140
- bundleId: app.bundleId,
141
- appleAppId: app.appleAppId,
142
- googleAppId: app.googleAppId,
143
- platform: app.appleAppId ? "ios" : app.googleAppId ? "android" : "unknown",
144
- currentValuation: app.currentValuation,
145
- metadata: app.metadata,
146
- addedAt: app.createdAt,
147
- updatedAt: app.updatedAt
148
- })
149
- }
150
- ]
151
- };
152
- } catch (error) {
153
- return {
154
- content: [
155
- {
156
- type: "text",
157
- text: formatError(error)
158
- }
159
- ],
160
- isError: true
161
- };
162
- }
163
- }
164
-
165
- // src/tools/reviews.ts
166
- import { z as z2 } from "zod";
167
- var getReviewsSchema = z2.object({
168
- assetId: z2.string().uuid().optional().describe("App UUID to filter reviews"),
169
- bundleId: z2.string().optional().describe("App bundle ID to filter reviews"),
170
- platform: z2.enum(["ios", "android"]).optional().describe("Filter by platform"),
171
- rating: z2.number().int().min(1).max(5).optional().describe("Filter by star rating (1-5)"),
172
- replied: z2.boolean().optional().describe("Filter by replied status (true = has reply, false = no reply)"),
173
- startDate: z2.string().optional().describe("Filter reviews from this date (ISO format: YYYY-MM-DD)"),
174
- endDate: z2.string().optional().describe("Filter reviews until this date (ISO format: YYYY-MM-DD)"),
175
- limit: z2.number().int().min(1).max(200).default(50).describe("Maximum number of reviews to return"),
176
- cursor: z2.string().optional().describe(
177
- "nextCursor from the previous get_reviews call, to fetch the next page with the same app and filters"
178
- ),
179
- sortBy: z2.enum(["date", "rating"]).default("date").describe("Sort reviews by date or rating")
180
- });
181
- var generateReviewReplySchema = z2.object({
182
- reviewId: z2.string().describe("The review UUID to generate a reply for"),
183
- assetId: z2.string().uuid().describe("The app UUID the review belongs to")
184
- });
185
- var sendReviewReplySchema = z2.object({
186
- reviewId: z2.string().describe("The review UUID to reply to"),
187
- assetId: z2.string().uuid().describe("The app UUID the review belongs to"),
188
- response: z2.string().describe("The reply text to send")
189
- });
190
- var translateReviewSchema = z2.object({
191
- reviewId: z2.string().describe("The review UUID to translate"),
192
- assetId: z2.string().uuid().describe("The app UUID the review belongs to"),
193
- // The translate endpoint receives the review content in the request body
194
- // (it does not re-fetch it). Pass the fields from a get_reviews result.
195
- rating: z2.number().int().min(1).max(5).describe("The review star rating, from get_reviews"),
196
- title: z2.string().default("").describe("The review title, from get_reviews"),
197
- body: z2.string().describe("The review text to translate, from get_reviews"),
198
- storeFront: z2.string().default("").describe('The review storefront (e.g. "SE"), from get_reviews'),
199
- appVersionString: z2.string().default("").describe("The app version the review was left on, from get_reviews")
200
- });
201
- async function getReviews(input, client) {
202
- try {
203
- let assetId = input.assetId;
204
- if (!assetId && input.bundleId) {
205
- const allApps = await client.get("/api/assets", {
206
- limit: 100,
207
- offset: 0,
208
- includeUnvalued: "true"
209
- });
210
- const match = (allApps.data ?? []).find(
211
- (app) => app.bundleId === input.bundleId
212
- );
213
- if (!match) {
214
- return {
215
- content: [
216
- {
217
- type: "text",
218
- text: `No app found with bundle ID: ${input.bundleId}`
219
- }
220
- ],
221
- isError: true
222
- };
223
- }
224
- assetId = match.id;
225
- }
226
- if (!assetId) {
227
- return {
228
- content: [
229
- {
230
- type: "text",
231
- text: "Provide an assetId (or bundleId) to fetch reviews for. Use list_apps to find app IDs."
232
- }
233
- ],
234
- isError: true
235
- };
236
- }
237
- const params = reviewQueryParameters(input);
238
- const response = await client.get(
239
- `/api/assets/${assetId}/reviews`,
240
- params
241
- );
242
- let reviews = response.data?.reviews ?? [];
243
- if (input.sortBy === "rating") {
244
- reviews = [...reviews].sort(
245
- (a, b) => Number(b.rating ?? 0) - Number(a.rating ?? 0)
246
- );
247
- }
248
- const hasReply = (review) => !!(review.developerResponse || review.replySource || review.hasReply);
249
- const summary = {
250
- totalReviews: reviews.length,
251
- averageRating: reviews.length > 0 ? (reviews.reduce((sum, review) => {
252
- const rating = Number(review.rating ?? 0);
253
- return sum + (Number.isFinite(rating) ? rating : 0);
254
- }, 0) / reviews.length).toFixed(2) : 0,
255
- repliedCount: reviews.filter((review) => hasReply(review)).length,
256
- unrepliedCount: reviews.filter((review) => !hasReply(review)).length
257
- };
258
- return {
259
- content: [
260
- {
261
- type: "text",
262
- text: formatAsJson({
263
- summary,
264
- // Pass back as `cursor` to get the next page; null = last page.
265
- nextCursor: response.data?.nextCursor ?? null,
266
- reviews: reviews.map((review) => ({
267
- id: review.id,
268
- appId: review.appId,
269
- platform: review.platform,
270
- rating: review.rating,
271
- title: review.title,
272
- // The handler exposes the review text as `review`.
273
- body: review.review ?? review.body,
274
- author: review.nickname || review.author,
275
- // Epoch ms from the handler.
276
- date: review.lastModified || review.date,
277
- version: review.appVersionString || review.version,
278
- storeFront: review.storeFront,
279
- hasReply: hasReply(review),
280
- replySource: review.replySource ?? null,
281
- hasDraft: review.hasDraft ?? false,
282
- reply: review.developerResponse ? typeof review.developerResponse === "object" ? review.developerResponse.response : review.developerResponse : review.reply || null,
283
- // FLO-2571: where an App Store reply stands at Apple.
284
- replyPublication: typeof review.developerResponse === "object" ? review.developerResponse?.publication ?? null : null
285
- }))
286
- })
287
- }
288
- ]
289
- };
290
- } catch (error) {
291
- return {
292
- content: [
293
- {
294
- type: "text",
295
- text: formatError(error)
296
- }
297
- ],
298
- isError: true
299
- };
300
- }
301
- }
302
- function reviewQueryParameters(input) {
303
- const params = {
304
- limit: input.limit
305
- };
306
- if (input.cursor) params.cursor = input.cursor;
307
- if (input.platform) params.platform = input.platform;
308
- if (input.rating !== void 0) params.rating = input.rating;
309
- if (input.replied !== void 0)
310
- params.responseStatus = input.replied ? "replied" : "unreplied";
311
- if (input.startDate) params.startDate = input.startDate;
312
- if (input.endDate) params.endDate = input.endDate;
313
- return params;
314
- }
315
- async function generateReviewReply(input, client) {
316
- try {
317
- const response = await client.post(
318
- `/api/assets/${input.assetId}/reviews/${input.reviewId}/generate-reply`,
319
- void 0
320
- );
321
- return {
322
- content: [
323
- {
324
- type: "text",
325
- text: formatAsJson(response)
326
- }
327
- ]
328
- };
329
- } catch (error) {
330
- return {
331
- content: [
332
- {
333
- type: "text",
334
- text: formatError(error)
335
- }
336
- ],
337
- isError: true
338
- };
339
- }
340
- }
341
- async function sendReviewReply(input, client) {
342
- try {
343
- const response = await client.post(
344
- `/api/assets/${input.assetId}/reviews/${input.reviewId}/respond`,
345
- // The API handler reads `responseText` from the body.
346
- { responseText: input.response }
347
- );
348
- return {
349
- content: [
350
- {
351
- type: "text",
352
- text: formatAsJson(response)
353
- }
354
- ]
355
- };
356
- } catch (error) {
357
- return {
358
- content: [
359
- {
360
- type: "text",
361
- text: formatError(error)
362
- }
363
- ],
364
- isError: true
365
- };
366
- }
367
- }
368
- async function translateReview(input, client) {
369
- try {
370
- const response = await client.post(
371
- `/api/assets/${input.assetId}/reviews/${input.reviewId}/translate`,
372
- // The translate endpoint expects the review content in the body.
373
- {
374
- rating: input.rating,
375
- title: input.title,
376
- review: input.body,
377
- storeFront: input.storeFront,
378
- appVersionString: input.appVersionString,
379
- lastModified: Date.now()
380
- }
381
- );
382
- return {
383
- content: [
384
- {
385
- type: "text",
386
- text: formatAsJson(response)
387
- }
388
- ]
389
- };
390
- } catch (error) {
391
- return {
392
- content: [
393
- {
394
- type: "text",
395
- text: formatError(error)
396
- }
397
- ],
398
- isError: true
399
- };
400
- }
401
- }
402
-
403
- // src/tools/analytics.ts
404
- import { z as z3 } from "zod";
405
- var UNAVAILABLE_REASONS = [
406
- "not_reported",
407
- "no_data",
408
- "source_filter"
409
- ];
410
- function unavailableReasonValue(reason) {
411
- if (reason.cause === "not_reported") return "not_reported";
412
- const hiddenByCause = reason.cause === "filtered_out" || reason.cause === "not_by_dimension";
413
- if (reason.reason === "source_filter" || hiddenByCause) {
414
- return "source_filter";
415
- }
416
- return "no_data";
417
- }
418
- function unavailableReason(name, meta) {
419
- if (!(meta.unavailableMetrics ?? []).includes(name)) return void 0;
420
- const reason = meta.unavailableMetricReasons?.[name];
421
- return {
422
- reason: reason ? unavailableReasonValue(reason) : "no_data",
423
- message: reason?.message ?? "Unavailable for this query."
424
- };
425
- }
426
- function unavailableEntries(requested, data, meta) {
427
- return requested.flatMap((name) => {
428
- const unavailable = unavailableReason(name, meta);
429
- if (!unavailable || name in data) return [];
430
- return [
431
- {
432
- name,
433
- displayName: METRIC_INFO[name]?.displayName || name,
434
- type: METRIC_INFO[name]?.type || "count",
435
- summary: null,
436
- change: null,
437
- unavailable
438
- }
439
- ];
440
- });
441
- }
442
- function summarize(points, change) {
443
- const values = (Array.isArray(points) ? points : []).map((point) => point.value ?? point.total).filter((value) => typeof value === "number");
444
- return {
445
- value: change?.currentValue ?? null,
446
- effectiveFromDate: change?.effectiveFromDate ?? null,
447
- effectiveToDate: change?.effectiveToDate ?? null,
448
- min: values.length > 0 ? Math.min(...values) : null,
449
- max: values.length > 0 ? Math.max(...values) : null,
450
- dataPoints: values.length
451
- };
452
- }
453
- var discoverMetricsSchema = z3.object({
454
- assetId: z3.string().uuid().describe("App UUID to check available metrics for")
455
- });
456
- var getMetricsSchema = z3.object({
457
- assetId: z3.string().uuid().describe("App UUID"),
458
- metrics: z3.array(z3.string()).min(1).describe(
459
- 'Metric names to query (e.g., ["proceeds", "totalDownloads"]). Use discover_metrics first to see available metrics.'
460
- ),
461
- startDate: z3.string().optional().describe("Start date (YYYY-MM-DD). Defaults to 30 days ago."),
462
- endDate: z3.string().optional().describe("End date (YYYY-MM-DD). Defaults to today."),
463
- granularity: z3.enum(["daily", "weekly", "monthly"]).default("daily").describe("Data granularity"),
464
- dimension: z3.string().optional().describe(
465
- 'Optional dimension to break down by (e.g., "storefront" for country, "platform" for device). Use discover_dimensions to see options. Each metric then carries `breakdown`: the period value, share and change of every value, aggregated for the metric type (read its `basis`: "latest" is the last day, never a sum; "daily_average" is an average a day, never a period total). Answer per-country questions from `breakdown`, never by adding up `timeseries`, which keeps only the top values each day.'
466
- ),
467
- dimensionFilter: z3.string().optional().describe(
468
- 'Filter to a specific dimension value (e.g., "US" when dimension is "storefront")'
469
- )
470
- });
471
- var discoverDimensionsSchema = z3.object({
472
- assetId: z3.string().uuid().describe("App UUID"),
473
- dimension: z3.string().optional().describe(
474
- 'If provided, returns the available values for this dimension (e.g., countries for "storefront")'
475
- )
476
- });
477
- var METRIC_INFO = {
478
- proceeds: {
479
- displayName: "Net Revenue (after store cut)",
480
- category: "Revenue",
481
- type: "currency"
482
- },
483
- total_revenue: {
484
- displayName: "Gross Revenue",
485
- category: "Revenue",
486
- type: "currency"
487
- },
488
- total_downloads: {
489
- displayName: "Total Downloads",
490
- category: "Downloads",
491
- type: "count"
492
- },
493
- units: {
494
- displayName: "First-time Downloads",
495
- category: "Downloads",
496
- type: "count"
497
- },
498
- redownloads: {
499
- displayName: "Re-downloads",
500
- category: "Downloads",
501
- type: "count"
502
- },
503
- page_views: {
504
- displayName: "App Store Page Views",
505
- category: "Downloads",
506
- type: "count"
507
- },
508
- impressions: {
509
- displayName: "App Store Impressions",
510
- category: "Downloads",
511
- type: "count"
512
- },
513
- sessions: {
514
- displayName: "App Sessions",
515
- category: "Engagement",
516
- type: "count"
517
- },
518
- active_devices: {
519
- displayName: "Active Devices",
520
- category: "Engagement",
521
- type: "count"
522
- },
523
- crashes: { displayName: "Crashes", category: "Engagement", type: "count" },
524
- paying_users: {
525
- displayName: "Paying Users",
526
- category: "Engagement",
527
- type: "count"
528
- },
529
- active_subs: {
530
- displayName: "Active Subscriptions",
531
- category: "Subscriptions",
532
- type: "count"
533
- },
534
- active_trials: {
535
- displayName: "Active Trials",
536
- category: "Subscriptions",
537
- type: "count"
538
- },
539
- new_trials: {
540
- displayName: "New Trials",
541
- category: "Subscriptions",
542
- type: "count"
543
- },
544
- trial_conversion_rate: {
545
- displayName: "Trial Conversion Rate",
546
- category: "Subscriptions",
547
- type: "percentage"
548
- },
549
- subscription_retention_rate: {
550
- displayName: "Subscription Retention Rate",
551
- category: "Subscriptions",
552
- type: "percentage"
553
- },
554
- products_sold: {
555
- displayName: "Products Sold (IAP)",
556
- category: "Revenue",
557
- type: "count"
558
- },
559
- ad_spend: { displayName: "Ad Spend", category: "Ads", type: "currency" },
560
- ad_impressions: {
561
- displayName: "Ad Impressions",
562
- category: "Ads",
563
- type: "count"
564
- },
565
- ad_taps: { displayName: "Ad Taps/Clicks", category: "Ads", type: "count" },
566
- ad_installs: {
567
- displayName: "Ad-attributed Installs",
568
- category: "Ads",
569
- type: "count"
570
- },
571
- ad_conversions: {
572
- displayName: "Ad Conversions",
573
- category: "Ads",
574
- type: "count"
575
- }
576
- };
577
- var DIMENSION_INFO = {
578
- storefront: "Country",
579
- region: "Region",
580
- platform: "Platform (device type)",
581
- source: "Source",
582
- appVersion: "App Version",
583
- purchase: "Product",
584
- appReferrer: "App Referrer",
585
- domainReferrer: "Domain Referrer",
586
- subscription_state: "Subscription Type",
587
- duration: "Duration",
588
- revenueShare: "Revenue Share",
589
- campaign: "Campaign"
590
- };
591
- async function discoverMetrics(input, client) {
592
- try {
593
- const response = await client.get(
594
- `/api/assets/${input.assetId}/metrics/availability`
595
- );
596
- const availableMetrics = response.data?.availableMetrics ?? [];
597
- const metricGroups = response.data?.metricGroups ?? {};
598
- const enriched = availableMetrics.map((metricName) => {
599
- const info = METRIC_INFO[metricName];
600
- return {
601
- name: metricName,
602
- displayName: info?.displayName || metricName,
603
- category: info?.category || "Other",
604
- type: info?.type || "count"
605
- };
606
- });
607
- const byCategory = {};
608
- for (const m of enriched) {
609
- (byCategory[m.category] ??= []).push(m);
610
- }
611
- return {
612
- content: [
613
- {
614
- type: "text",
615
- text: formatAsJson({
616
- assetId: input.assetId,
617
- totalAvailable: availableMetrics.length,
618
- metricsByCategory: byCategory,
619
- dataGroups: metricGroups,
620
- tip: 'Use the metric "name" field in get_metrics. You can query multiple metrics at once.'
621
- })
622
- }
623
- ]
624
- };
625
- } catch (error) {
626
- return {
627
- content: [{ type: "text", text: formatError(error) }],
628
- isError: true
629
- };
630
- }
631
- }
632
- async function getMetrics(input, client) {
633
- try {
634
- const granularity = input.granularity ?? "daily";
635
- const endDate = input.endDate || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
636
- const startDate = input.startDate || (() => {
637
- const d = /* @__PURE__ */ new Date();
638
- d.setDate(d.getDate() - 30);
639
- return d.toISOString().split("T")[0];
640
- })();
641
- const params = {
642
- metrics: input.metrics.join(","),
643
- fromDate: startDate,
644
- toDate: endDate,
645
- granularity
646
- };
647
- if (input.dimension) params.dimension = input.dimension;
648
- if (input.dimensionFilter && input.dimension) {
649
- params[`filter.${input.dimension}`] = input.dimensionFilter;
650
- }
651
- const path = `/api/assets/${input.assetId}/metrics/timeseries`;
652
- const response = await client.get(path, params);
653
- const summaryResponse = input.granularity === "daily" ? response : await client.get(path, {
654
- ...params,
655
- granularity: "daily"
656
- });
657
- const data = response.data ?? {};
658
- const changes = summaryResponse.changes ?? {};
659
- const meta = response.meta ?? {};
660
- const summaries = {};
661
- for (const [metricName, points] of Object.entries(data)) {
662
- summaries[metricName] = summarize(points, changes[metricName]);
663
- }
664
- const info = METRIC_INFO;
665
- return {
666
- content: [
667
- {
668
- type: "text",
669
- text: formatAsJson({
670
- assetId: input.assetId,
671
- dateRange: { start: startDate, end: endDate },
672
- granularity,
673
- dimension: input.dimension || null,
674
- metrics: [
675
- ...Object.keys(data).map((name) => ({
676
- name,
677
- displayName: info[name]?.displayName || name,
678
- type: info[name]?.type || "count",
679
- summary: summaries[name],
680
- change: changes[name] || null,
681
- ...input.dimension && {
682
- breakdown: summaryResponse.breakdownTotals?.[name] ?? null
683
- },
684
- // A computed metric the API marks unavailable comes back as an
685
- // empty series: it carries its reason too.
686
- ...unavailableReason(name, meta) && {
687
- unavailable: unavailableReason(name, meta)
688
- }
689
- })),
690
- // FLO-2840: listed with the reason, never dropped or 0.
691
- ...unavailableEntries(input.metrics, data, meta)
692
- ],
693
- timeseries: data,
694
- meta
695
- })
696
- }
697
- ]
698
- };
699
- } catch (error) {
700
- return {
701
- content: [{ type: "text", text: formatError(error) }],
702
- isError: true
703
- };
704
- }
705
- }
706
- async function discoverDimensions(input, client) {
707
- try {
708
- if (input.dimension) {
709
- const response2 = await client.get(
710
- `/api/assets/${input.assetId}/metrics/dimensions/${input.dimension}/values`
711
- );
712
- return {
713
- content: [
714
- {
715
- type: "text",
716
- text: formatAsJson({
717
- assetId: input.assetId,
718
- dimension: input.dimension,
719
- displayName: DIMENSION_INFO[input.dimension] || input.dimension,
720
- values: response2.data ?? response2
721
- })
722
- }
723
- ]
724
- };
725
- }
726
- const response = await client.get(`/api/assets/${input.assetId}/metrics/dimensions`);
727
- const dimensions = Array.isArray(response.data) ? response.data : [];
728
- const enriched = dimensions.map((dim) => {
729
- if (typeof dim === "string") {
730
- return { name: dim, displayName: DIMENSION_INFO[dim] || dim };
731
- }
732
- const id = dim.id ?? "";
733
- return { name: id, displayName: dim.label ?? DIMENSION_INFO[id] ?? id };
734
- });
735
- return {
736
- content: [
737
- {
738
- type: "text",
739
- text: formatAsJson({
740
- assetId: input.assetId,
741
- dimensions: enriched,
742
- tip: 'Use dimension name in get_metrics "dimension" param. Use discover_dimensions with a specific dimension to see available values.'
743
- })
744
- }
745
- ]
746
- };
747
- } catch (error) {
748
- return {
749
- content: [{ type: "text", text: formatError(error) }],
750
- isError: true
751
- };
752
- }
753
- }
754
-
755
- // src/tools/download-impact.ts
756
- import { z as z4 } from "zod";
757
- var Day = z4.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional();
758
- var getDownloadImpactSchema = z4.object({
759
- assetId: z4.string().uuid().describe("App UUID (App Store apps)"),
760
- from: Day.describe(
761
- "First day drawn (YYYY-MM-DD); default 20 weeks before `to`"
762
- ),
763
- to: Day.describe(
764
- "Last day drawn (YYYY-MM-DD); default the newest day with data"
765
- ),
766
- beforeFrom: Day.describe(
767
- 'Start of the "before" window compared (needs beforeTo; all windows within 400 days of each other)'
768
- ),
769
- beforeTo: Day.describe('End of the "before" window compared'),
770
- afterFrom: Day.describe(
771
- 'Start of the "after" window compared (needs afterTo)'
772
- ),
773
- afterTo: Day.describe('End of the "after" window compared'),
774
- country: z4.string().regex(/^[a-zA-Z]{2}$/).optional().describe(
775
- 'One storefront, two-letter code (e.g. "us"): narrows countries and keywords'
776
- ),
777
- includeDays: z4.boolean().optional().describe("Also return every day (long). Weeks carry the same downloads.")
778
- });
779
- async function getDownloadImpact(input, client) {
780
- try {
781
- const { assetId, includeDays, ...query } = input;
782
- const impact = await client.get(
783
- `/api/assets/${assetId}/metrics/download-impact`,
784
- query
785
- );
786
- const { days, lastYearDays, ...rest } = impact;
787
- return {
788
- content: [
789
- {
790
- type: "text",
791
- text: formatAsJson(
792
- includeDays ? { ...rest, days, lastYearDays } : rest
793
- )
794
- }
795
- ]
796
- };
797
- } catch (error) {
798
- return {
799
- content: [{ type: "text", text: formatError(error) }],
800
- isError: true
801
- };
802
- }
803
- }
804
-
805
- // src/tools/agents.ts
806
- import { z as z5 } from "zod";
807
- function asRecord(value) {
808
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
809
- }
810
- var AGENT_TYPES = ["review", "aso"];
811
- var AGENT_DESCRIPTIONS = {
812
- review: "AI-powered review management \u2014 drafts and sends replies to app store reviews",
813
- aso: "App Store Optimization \u2014 listing optimization suggestions for better visibility"
814
- };
815
- var listAgentsSchema = z5.object({});
816
- var getAgentDetailsSchema = z5.object({
817
- agentType: z5.enum(AGENT_TYPES).describe("The type of agent to get details for"),
818
- assetId: z5.string().uuid().optional().describe("App UUID to get agent config for (when agent is per-asset)")
819
- });
820
- var getAgentRunHistorySchema = z5.object({
821
- agentType: z5.enum(AGENT_TYPES).describe("The type of agent to get run history for"),
822
- assetId: z5.string().uuid().optional().describe("App UUID to filter runs"),
823
- limit: z5.number().int().min(1).max(100).default(20).describe("Maximum number of runs to return")
824
- });
825
- var triggerAgentRunSchema = z5.object({
826
- agentId: z5.string().describe("The agent ID to trigger a run for (the `id` from list_agents)"),
827
- assetId: z5.string().uuid().optional().describe("Optional app UUID to run the agent against")
828
- });
829
- var pauseAgentSchema = z5.object({
830
- agentId: z5.string().describe("The agent ID to pause (the `id` from list_agents)")
831
- });
832
- var resumeAgentSchema = z5.object({
833
- agentId: z5.string().describe("The agent ID to resume (the `id` from list_agents)")
834
- });
835
- var getAgentActivitySchema = z5.object({
836
- agentId: z5.string().describe("The agent ID to get activity for (the `id` from list_agents)")
837
- });
838
- async function listAgents(_input, client) {
839
- try {
840
- let apiAgents = null;
841
- try {
842
- const response = await client.get(
843
- "/api/agents"
844
- );
845
- apiAgents = Array.isArray(response) ? response : response.data ?? response.agents ?? null;
846
- } catch {
847
- }
848
- if (apiAgents && Array.isArray(apiAgents)) {
849
- return {
850
- content: [
851
- {
852
- type: "text",
853
- text: formatAsJson({
854
- totalAgents: apiAgents.length,
855
- agents: apiAgents
856
- })
857
- }
858
- ]
859
- };
860
- }
861
- const agents = AGENT_TYPES.map((type) => ({
862
- type,
863
- description: AGENT_DESCRIPTIONS[type],
864
- available: true
865
- }));
866
- return {
867
- content: [
868
- {
869
- type: "text",
870
- text: formatAsJson({
871
- totalAgents: agents.length,
872
- agents
873
- })
874
- }
875
- ]
876
- };
877
- } catch (error) {
878
- return {
879
- content: [
880
- {
881
- type: "text",
882
- text: formatError(error)
883
- }
884
- ],
885
- isError: true
886
- };
887
- }
888
- }
889
- async function getAgentDetails(input, client) {
890
- try {
891
- try {
892
- const params = {};
893
- if (input.assetId) params.assetId = input.assetId;
894
- const response2 = await client.get(`/api/agents/by-type/${input.agentType}`, params);
895
- if (response2.agent) {
896
- return {
897
- content: [
898
- {
899
- type: "text",
900
- text: formatAsJson({
901
- agent: response2.agent,
902
- recentRuns: response2.recentRuns ?? []
903
- })
904
- }
905
- ]
906
- };
907
- }
908
- } catch {
909
- }
910
- const response = {
911
- type: input.agentType,
912
- description: AGENT_DESCRIPTIONS[input.agentType],
913
- message: `No ${input.agentType} agent is provisioned for this organization yet. Activate it from the Agents page or with trigger_agent_run once created.`
914
- };
915
- return {
916
- content: [
917
- {
918
- type: "text",
919
- text: formatAsJson(response)
920
- }
921
- ]
922
- };
923
- } catch (error) {
924
- return {
925
- content: [
926
- {
927
- type: "text",
928
- text: formatError(error)
929
- }
930
- ],
931
- isError: true
932
- };
933
- }
934
- }
935
- async function getAgentRunHistory(input, client) {
936
- try {
937
- let agentId;
938
- try {
939
- const byTypeParams = {};
940
- if (input.assetId) byTypeParams.assetId = input.assetId;
941
- const byType = await client.get(
942
- `/api/agents/by-type/${input.agentType}`,
943
- byTypeParams
944
- );
945
- agentId = byType.agent?.id;
946
- } catch {
947
- }
948
- if (!agentId) {
949
- return {
950
- content: [
951
- {
952
- type: "text",
953
- text: formatAsJson({
954
- agentType: input.agentType,
955
- runs: [],
956
- message: `No ${input.agentType} agent is provisioned for this organization yet, so there is no run history.`
957
- })
958
- }
959
- ]
960
- };
961
- }
962
- const response = await client.get(
963
- `/api/agents/${agentId}/runs`,
964
- { limit: input.limit }
965
- );
966
- return {
967
- content: [
968
- {
969
- type: "text",
970
- text: formatAsJson({
971
- agentType: input.agentType,
972
- agentId,
973
- ...asRecord(response.data ?? response)
974
- })
975
- }
976
- ]
977
- };
978
- } catch (error) {
979
- return {
980
- content: [
981
- {
982
- type: "text",
983
- text: formatError(error)
984
- }
985
- ],
986
- isError: true
987
- };
988
- }
989
- }
990
- async function triggerAgentRun(input, client) {
991
- try {
992
- const body = input.assetId ? { triggerContext: { assetId: input.assetId } } : {};
993
- const response = await client.post(
994
- `/api/agents/${input.agentId}/run`,
995
- body
996
- );
997
- return {
998
- content: [
999
- {
1000
- type: "text",
1001
- text: formatAsJson(response.data ?? response)
1002
- }
1003
- ]
1004
- };
1005
- } catch (error) {
1006
- return {
1007
- content: [
1008
- {
1009
- type: "text",
1010
- text: formatError(error)
1011
- }
1012
- ],
1013
- isError: true
1014
- };
1015
- }
1016
- }
1017
- async function pauseAgent(input, client) {
1018
- try {
1019
- const response = await client.post(
1020
- `/api/agents/${input.agentId}/pause`
1021
- );
1022
- return {
1023
- content: [
1024
- {
1025
- type: "text",
1026
- text: formatAsJson(response.data ?? response)
1027
- }
1028
- ]
1029
- };
1030
- } catch (error) {
1031
- return {
1032
- content: [
1033
- {
1034
- type: "text",
1035
- text: formatError(error)
1036
- }
1037
- ],
1038
- isError: true
1039
- };
1040
- }
1041
- }
1042
- async function resumeAgent(input, client) {
1043
- try {
1044
- const response = await client.post(
1045
- `/api/agents/${input.agentId}/resume`
1046
- );
1047
- return {
1048
- content: [
1049
- {
1050
- type: "text",
1051
- text: formatAsJson(response.data ?? response)
1052
- }
1053
- ]
1054
- };
1055
- } catch (error) {
1056
- return {
1057
- content: [
1058
- {
1059
- type: "text",
1060
- text: formatError(error)
1061
- }
1062
- ],
1063
- isError: true
1064
- };
1065
- }
1066
- }
1067
- async function getAgentActivity(input, client) {
1068
- try {
1069
- const response = await client.get(
1070
- `/api/agents/${input.agentId}/activity`
1071
- );
1072
- return {
1073
- content: [
1074
- {
1075
- type: "text",
1076
- text: formatAsJson(response.data ?? response)
1077
- }
1078
- ]
1079
- };
1080
- } catch (error) {
1081
- return {
1082
- content: [
1083
- {
1084
- type: "text",
1085
- text: formatError(error)
1086
- }
1087
- ],
1088
- isError: true
1089
- };
1090
- }
1091
- }
1092
-
1093
- // src/tools/ads.ts
1094
- import { z as z6 } from "zod";
1095
- var getAdsPerformanceSchema = z6.object({
1096
- assetId: z6.string().uuid().optional().describe("Filter by app UUID"),
1097
- platform: z6.enum(["apple_search_ads", "google_ads", "meta_ads", "tiktok_ads"]).optional().describe("Filter by ad platform"),
1098
- fromDate: z6.string().optional().describe("Start date for performance data (YYYY-MM-DD)"),
1099
- toDate: z6.string().optional().describe("End date for performance data (YYYY-MM-DD)"),
1100
- limit: z6.number().int().min(1).max(100).default(50).describe("Maximum number of campaigns to return")
1101
- });
1102
- async function getAdsPerformance(input, client) {
1103
- try {
1104
- const params = {};
1105
- if (input.assetId) params.assetId = input.assetId;
1106
- if (input.fromDate) params.from = input.fromDate;
1107
- if (input.toDate) params.to = input.toDate;
1108
- const response = await client.get(
1109
- "/api/ads/campaigns",
1110
- params
1111
- );
1112
- let campaigns = response.data ?? response.campaigns ?? [];
1113
- if (input.platform) {
1114
- campaigns = campaigns.filter((c) => c.platform === input.platform);
1115
- }
1116
- campaigns = campaigns.slice(0, input.limit);
1117
- return {
1118
- content: [
1119
- {
1120
- type: "text",
1121
- text: formatAsJson({
1122
- total: campaigns.length,
1123
- // The server couldn't read the metrics: null spend is unknown,
1124
- // never "no spend".
1125
- ...response.metricsUnavailable ? {
1126
- metricsUnavailable: true,
1127
- note: "The ads metrics could not be read right now, so spend, impressions, taps and installs are unknown (null), not zero. Try again later."
1128
- } : {},
1129
- campaigns: campaigns.map((campaign) => ({
1130
- id: campaign.id,
1131
- assetId: campaign.assetId,
1132
- assetName: campaign.assetName,
1133
- platformCampaignId: campaign.platformCampaignId,
1134
- name: campaign.name,
1135
- status: campaign.status,
1136
- objective: campaign.objective,
1137
- platform: campaign.platform,
1138
- linkSource: campaign.linkSource,
1139
- linkedAt: campaign.linkedAt,
1140
- totalSpend: campaign.totalSpend ?? null,
1141
- totalImpressions: campaign.totalImpressions ?? null,
1142
- totalTaps: campaign.totalTaps ?? null,
1143
- totalInstalls: campaign.totalInstalls ?? null,
1144
- avgCPI: campaign.avgCPI ?? null,
1145
- avgTTR: campaign.avgTTR ?? null,
1146
- avgCVR: campaign.avgCVR ?? null
1147
- }))
1148
- })
1149
- }
1150
- ]
1151
- };
1152
- } catch (error) {
1153
- return {
1154
- content: [
1155
- {
1156
- type: "text",
1157
- text: formatError(error)
1158
- }
1159
- ],
1160
- isError: true
1161
- };
1162
- }
1163
- }
1164
-
1165
- // src/tools/dashboard.ts
1166
- import { z as z7 } from "zod";
1167
- function parseDashboardNumber(value) {
1168
- if (value === null || value === void 0 || value === "") return null;
1169
- const parsed = typeof value === "number" ? value : Number.parseFloat(value);
1170
- return Number.isFinite(parsed) ? parsed : null;
1171
- }
1172
- function getSidebarAssets(response) {
1173
- if (!response) return [];
1174
- if (Array.isArray(response)) return response;
1175
- return response.data ?? [];
1176
- }
1177
- var getDashboardOverviewSchema = z7.object({});
1178
- async function getDashboardOverview(_input, client) {
1179
- try {
1180
- const overviewPromise = client.get("/api/dashboard/overview-metrics").catch(() => null);
1181
- const sidebarPromise = client.get(
1182
- "/api/dashboard/sidebar-assets"
1183
- ).catch(() => null);
1184
- const [overviewResponse, sidebarResponse] = await Promise.all([
1185
- overviewPromise,
1186
- sidebarPromise
1187
- ]);
1188
- const overview = overviewResponse?.data ?? overviewResponse ?? {};
1189
- const apps = getSidebarAssets(sidebarResponse);
1190
- const totalValuation = apps.reduce((sum, app) => {
1191
- return sum + (parseDashboardNumber(app.currentValuation) ?? 0);
1192
- }, 0);
1193
- return {
1194
- content: [
1195
- {
1196
- type: "text",
1197
- text: formatAsJson({
1198
- portfolio: {
1199
- totalApps: apps.length,
1200
- totalValuation: totalValuation > 0 ? totalValuation : null,
1201
- apps: apps.map((app) => ({
1202
- id: app.id,
1203
- name: app.name,
1204
- bundleId: app.bundleId,
1205
- platform: app.appleAppId ? "ios" : app.googleAppId ? "android" : "unknown",
1206
- currentValuation: parseDashboardNumber(app.currentValuation),
1207
- rating: parseDashboardNumber(app.rating),
1208
- ratingCount: app.ratingCount ?? null,
1209
- category: app.category ?? null,
1210
- iconUrl: app.iconUrl ?? null
1211
- }))
1212
- },
1213
- overview
1214
- })
1215
- }
1216
- ]
1217
- };
1218
- } catch (error) {
1219
- return {
1220
- content: [
1221
- {
1222
- type: "text",
1223
- text: formatError(error)
1224
- }
1225
- ],
1226
- isError: true
1227
- };
1228
- }
1229
- }
1230
-
1231
- // src/tools/actions.ts
1232
- import { randomUUID } from "node:crypto";
1233
- import { z as z8 } from "zod";
1234
-
1235
- // src/public-errors.ts
1236
- var INTERNAL_ERROR_PATTERNS = [
1237
- /\b(stack|trace|at\s+[\w.$<>]+\s*\()/i,
1238
- /\b(sql|postgres|drizzle|database|constraint|duplicate key|violates|relation)\b/i,
1239
- /\b(fetch|undici|socket|ECONNRESET|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|HTTP\s+\d{3})\b/i,
1240
- /\b(token|secret|api[_-]?key|authorization|bearer|cookie|password)\b/i,
1241
- /\b[a-z0-9]+_(secret|token|key)\b/i,
1242
- /\b(secret|token|key)[_-][a-z0-9]+\b/i,
1243
- /\b(scrap|browser|patchright|playwright|chromium|page\.|locator|selector)\b/i,
1244
- /\b(redis|bullmq|queue|job id|worker)\b/i
1245
- ];
1246
- function looksInternal(message) {
1247
- return INTERNAL_ERROR_PATTERNS.some((pattern) => pattern.test(message));
1248
- }
1249
- function publicMcpErrorMessage(message, fallbackMessage = "Fload could not complete the request. Please try again.") {
1250
- const raw = message instanceof Error ? message.message : typeof message === "string" ? message : "";
1251
- const normalized = raw.replace(/\s+/g, " ").trim();
1252
- if (!normalized || normalized.length > 180 || looksInternal(normalized)) {
1253
- return fallbackMessage;
1254
- }
1255
- return normalized;
1256
- }
1257
-
1258
- // src/tools/actions.ts
1259
- var listPendingActionsSchema = z8.object({
1260
- assetId: z8.string().uuid().optional().describe("Filter by app UUID"),
1261
- view: z8.enum(["open", "queued"]).default("open").describe(
1262
- "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)."
1263
- ),
1264
- limit: z8.number().int().min(1).max(100).default(50).describe("Maximum number of actions to return")
1265
- });
1266
- var approveActionSchema = z8.object({
1267
- actionId: z8.string().describe("The inbox item ID to approve (from list_pending_actions)"),
1268
- wholeGroup: z8.boolean().optional().describe(
1269
- "Approve every language of this item's card at once: the items still waiting for approval that share its proposalBatch (one listing change across locales, as the inbox shows it as one card with one Approve). Languages that cannot be approved now are left as they are and listed."
1270
- )
1271
- });
1272
- var rejectActionSchema = z8.object({
1273
- actionId: z8.string().describe("The inbox item ID to reject (from list_pending_actions)"),
1274
- reason: z8.string().trim().min(1).max(1e3).optional().describe(
1275
- "Why, in the user's words. Kept with the rejection so the agents do not propose the same thing again."
1276
- )
1277
- });
1278
- var checkActionNowSchema = z8.object({
1279
- actionId: z8.string().describe(
1280
- 'The inbox item ID to check now (from list_pending_actions with view "queued", or an approve_action result; its commands include check_now)'
1281
- )
1282
- });
1283
- var renameCustomPageActionSchema = z8.object({
1284
- actionId: z8.string().describe(
1285
- '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)'
1286
- ),
1287
- name: z8.string().trim().min(1).max(100).describe(
1288
- "The new page name: at most 100 characters (UTF-16 units), not its current name, not a page the app already has"
1289
- )
1290
- });
1291
- function commandFor(kind, intent) {
1292
- if (kind === "notice")
1293
- return intent === "approve" ? "acknowledge" : "dismiss";
1294
- return intent;
1295
- }
1296
- function toolText(payload, isError = false) {
1297
- return {
1298
- content: [{ type: "text", text: formatAsJson(payload) }],
1299
- ...isError ? { isError: true } : {}
1300
- };
1301
- }
1302
- function toolError(error) {
1303
- return {
1304
- content: [{ type: "text", text: formatError(error) }],
1305
- isError: true
1306
- };
1307
- }
1308
- async function listPendingActions(input, client) {
1309
- try {
1310
- const response = await client.get(
1311
- "/api/actions/items",
1312
- { view: input.view ?? "open", assetId: input.assetId, limit: input.limit }
1313
- );
1314
- const actions = response.items ?? [];
1315
- return toolText({
1316
- total: actions.length,
1317
- actions,
1318
- hasMore: Boolean(response.nextCursor)
1319
- });
1320
- } catch (error) {
1321
- return toolError(error);
1322
- }
1323
- }
1324
- async function commandItem(client, itemId, intent, reason) {
1325
- const detail = await client.get(
1326
- `/api/actions/items/${encodeURIComponent(itemId)}`
1327
- );
1328
- const item = detail.item;
1329
- if (!item) throw new Error("Action not found");
1330
- const command = commandFor(item.kind, intent);
1331
- const answer = await client.postForAnswer(
1332
- "/api/actions/commands",
1333
- {
1334
- command,
1335
- idempotencyKey: `mcp:${command}:${item.id}:${randomUUID()}`,
1336
- targets: [
1337
- {
1338
- itemId: item.id,
1339
- ...command === "approve" && item.currentRevisionId ? { revisionId: item.currentRevisionId } : {}
1340
- }
1341
- ],
1342
- ...command === "reject" && reason ? { reason } : {}
1343
- }
1344
- );
1345
- const result = answer.body?.results?.[0];
1346
- if (!result)
1347
- throw new Error(
1348
- answer.ok ? "Fload returned no result for the command." : "Fload rejected the request. Please check access and try again."
1349
- );
1350
- return {
1351
- command,
1352
- result: {
1353
- ...result,
1354
- error: result.error ? publicMcpErrorMessage(
1355
- result.error,
1356
- "Fload could not apply this change."
1357
- ) : void 0
1358
- }
1359
- };
1360
- }
1361
- function approveMessage(command, applied2, result) {
1362
- if (!applied2) return refusedMessage(result);
1363
- if (command === "acknowledge") return "Acknowledged.";
1364
- if (result?.alreadyLive)
1365
- return "Already live: the store already shows this change, so nothing was sent. The item is done.";
1366
- return "Approved. Fload delivers it after a short undo window; the inbox shows where it is.";
1367
- }
1368
- function refusedMessage(result) {
1369
- const said = result?.error ?? "The approval could not be recorded.";
1370
- const check = result?.policyRefusal?.check;
1371
- return check ? `Stopped by the ${check}: ${said}` : said;
1372
- }
1373
- async function approveAction(input, client) {
1374
- try {
1375
- if (input.wholeGroup) {
1376
- const grouped = await approveGroup(client, input.actionId);
1377
- if (grouped) return grouped;
1378
- }
1379
- const { command, result } = await commandItem(
1380
- client,
1381
- input.actionId,
1382
- "approve"
1383
- );
1384
- const applied2 = result?.result === "applied" || result?.result === "replayed";
1385
- return toolText(
1386
- {
1387
- success: applied2,
1388
- actionId: input.actionId,
1389
- command,
1390
- result: result?.result ?? "unknown",
1391
- ...result?.error ? { error: result.error } : {},
1392
- message: approveMessage(command, applied2, result),
1393
- item: result?.item
1394
- },
1395
- !applied2
1396
- );
1397
- } catch (error) {
1398
- return toolError(error);
1399
- }
1400
- }
1401
- async function groupOf(client, item) {
1402
- if (!item.proposalBatch || item.status !== "needs_approval") return [item];
1403
- const isSibling = (other) => typeof other === "object" && other !== null && other.status === "needs_approval" && other.proposalBatch === item.proposalBatch && other.assetId === item.assetId && other.id !== item.id;
1404
- const siblings = [];
1405
- let cursor;
1406
- do {
1407
- const response = await client.get("/api/actions/items", {
1408
- view: "open",
1409
- limit: 100,
1410
- ...item.assetId ? { assetId: item.assetId } : {},
1411
- ...cursor ? { cursor } : {}
1412
- });
1413
- siblings.push(...(response.items ?? []).filter(isSibling));
1414
- cursor = response.nextCursor;
1415
- } while (cursor);
1416
- return [item, ...siblings];
1417
- }
1418
- async function approveGroup(client, actionId) {
1419
- const detail = await client.get(
1420
- `/api/actions/items/${encodeURIComponent(actionId)}`
1421
- );
1422
- if (!detail.item) throw new Error("Action not found");
1423
- const group = await groupOf(client, detail.item);
1424
- if (group.length <= 1) return null;
1425
- const approvable = group.filter(
1426
- (item) => item.allowedCommands?.includes("approve")
1427
- );
1428
- const skipped = group.filter((item) => !approvable.includes(item)).map((item) => item.id);
1429
- if (approvable.length === 0)
1430
- return toolText(
1431
- {
1432
- success: false,
1433
- actionId,
1434
- skipped,
1435
- message: "Nothing in this card can be approved right now."
1436
- },
1437
- true
1438
- );
1439
- const answer = await client.postForAnswer(
1440
- "/api/actions/commands",
1441
- {
1442
- command: "approve",
1443
- idempotencyKey: `mcp:approve-group:${actionId}:${randomUUID()}`,
1444
- targets: approvable.map((item) => ({
1445
- itemId: item.id,
1446
- ...item.currentRevisionId ? { revisionId: item.currentRevisionId } : {}
1447
- }))
1448
- }
1449
- );
1450
- const results = (answer.body?.results ?? []).map((result) => ({
1451
- itemId: result.itemId,
1452
- result: result.result,
1453
- ...result.error ? {
1454
- error: publicMcpErrorMessage(
1455
- result.error,
1456
- "Fload could not apply this change."
1457
- )
1458
- } : {}
1459
- }));
1460
- const approved = results.filter(
1461
- (r) => r.result === "applied" || r.result === "replayed"
1462
- ).length;
1463
- return toolText(
1464
- {
1465
- success: approved > 0,
1466
- actionId,
1467
- approved,
1468
- results,
1469
- ...skipped.length ? { skipped } : {},
1470
- message: approved > 0 ? `Approved ${approved} of ${group.length}. Fload delivers them after a short undo window; the inbox shows where each is.` : "The approval could not be recorded."
1471
- },
1472
- approved === 0
1473
- );
1474
- }
1475
- async function rejectAction(input, client) {
1476
- try {
1477
- const { command, result } = await commandItem(
1478
- client,
1479
- input.actionId,
1480
- "reject",
1481
- input.reason
1482
- );
1483
- const applied2 = result?.result === "applied" || result?.result === "replayed";
1484
- return toolText(
1485
- {
1486
- success: applied2,
1487
- actionId: input.actionId,
1488
- command,
1489
- result: result?.result ?? "unknown",
1490
- ...result?.error ? { error: result.error } : {},
1491
- message: applied2 ? command === "dismiss" ? "Dismissed." : "Rejected. Nothing was sent." : result?.error ?? "The rejection could not be recorded.",
1492
- item: result?.item
1493
- },
1494
- !applied2
1495
- );
1496
- } catch (error) {
1497
- return toolError(error);
1498
- }
1499
- }
1500
- async function checkActionNow(input, client) {
1501
- try {
1502
- const answer = await client.postForAnswer(
1503
- "/api/actions/commands",
1504
- {
1505
- command: "check_now",
1506
- idempotencyKey: `mcp:check_now:${input.actionId}:${randomUUID()}`,
1507
- targets: [{ itemId: input.actionId }]
1508
- }
1509
- );
1510
- const result = answer.body?.results?.[0];
1511
- const applied2 = result?.result === "applied" || result?.result === "replayed";
1512
- const error = result?.error ? publicMcpErrorMessage(result.error, "Fload could not check it now.") : void 0;
1513
- return toolText(
1514
- {
1515
- success: applied2,
1516
- actionId: input.actionId,
1517
- command: "check_now",
1518
- result: result?.result ?? "unknown",
1519
- ...error ? { error } : {},
1520
- 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."),
1521
- item: result?.item
1522
- },
1523
- !applied2
1524
- );
1525
- } catch (error) {
1526
- return toolError(error);
1527
- }
1528
- }
1529
- var applied = (result) => result?.result === "applied" || result?.result === "replayed";
1530
- async function sendItemCommand(client, body) {
1531
- const { command, itemId, revisionId, ...extra } = body;
1532
- const answer = await client.postForAnswer(
1533
- "/api/actions/commands",
1534
- {
1535
- command,
1536
- idempotencyKey: `mcp:${command}:${itemId}:${randomUUID()}`,
1537
- targets: [{ itemId, ...revisionId ? { revisionId } : {} }],
1538
- ...extra
1539
- }
1540
- );
1541
- const result = answer.body?.results?.[0];
1542
- if (applied(result)) return { result, refusal: null };
1543
- const said = result?.error ?? answer.body?.message;
1544
- return {
1545
- result,
1546
- refusal: publicMcpErrorMessage(
1547
- said,
1548
- answer.ok ? "Fload returned no result for the command." : "Fload rejected the request. Please check access and try again."
1549
- )
1550
- };
1551
- }
1552
- function renameAnswer(input, outcome, item) {
1553
- const success = outcome.renamed && outcome.approved;
1554
- return toolText(
1555
- {
1556
- success,
1557
- actionId: input.actionId,
1558
- ...outcome,
1559
- ...item === void 0 ? {} : { item }
1560
- },
1561
- !success
1562
- );
1563
- }
1564
- async function renameCustomPageAction(input, client) {
1565
- try {
1566
- const name = input.name.trim();
1567
- const detail = await client.get(
1568
- `/api/actions/items/${encodeURIComponent(input.actionId)}`
1569
- );
1570
- const item = detail.item;
1571
- if (!item || item.kind !== "asc_custom_product_page" || !item.subjectKey?.startsWith("asc-cpp:"))
1572
- return renameAnswer(input, {
1573
- renamed: false,
1574
- approved: false,
1575
- message: "This item is not a request to create a custom product page."
1576
- });
1577
- const edit = await sendItemCommand(client, {
1578
- command: "edit",
1579
- itemId: item.id,
1580
- revisionId: item.currentRevisionId,
1581
- pageName: name
1582
- });
1583
- if (edit.refusal)
1584
- return renameAnswer(input, {
1585
- renamed: false,
1586
- approved: false,
1587
- message: edit.refusal
1588
- });
1589
- const renamed = edit.result?.item;
1590
- const approve = await sendItemCommand(client, {
1591
- command: "approve",
1592
- itemId: item.id,
1593
- revisionId: renamed?.currentRevisionId ?? null
1594
- });
1595
- return renameAnswer(
1596
- input,
1597
- approve.refusal ? {
1598
- renamed: true,
1599
- approved: false,
1600
- // The server's own refusal, as it said it.
1601
- message: approve.refusal,
1602
- next: `The page is renamed to \u201C${name}\u201D and waits for approval (approve_action).`
1603
- } : {
1604
- renamed: true,
1605
- approved: true,
1606
- message: `Renamed to \u201C${name}\u201D and approved. Fload creates the page after a short undo window; the inbox shows where it is.`
1607
- },
1608
- approve.result?.item ?? renamed
1609
- );
1610
- } catch (error) {
1611
- return toolError(error);
1612
- }
1613
- }
1614
-
1615
- // src/tools/aso.ts
1616
- import { z as z9 } from "zod";
1617
- var getAsoSummarySchema = z9.object({
1618
- assetId: z9.string().uuid().describe("App UUID to get ASO summary for")
1619
- });
1620
- var getAsoRecommendationsSchema = z9.object({
1621
- assetId: z9.string().uuid().describe("App UUID to get ASO recommendations for")
1622
- });
1623
- var getAsoKeywordsSchema = z9.object({
1624
- assetId: z9.string().uuid().describe("App UUID to get keyword intelligence for"),
1625
- locale: z9.string().optional().describe(
1626
- 'Locale code to filter keywords (e.g., "en-US", "de-DE"). Returns all locales if omitted.'
1627
- )
1628
- });
1629
- var getAsoExperimentsSchema = z9.object({
1630
- assetId: z9.string().uuid().describe("App UUID to list ASO experiments for"),
1631
- status: z9.enum([
1632
- "proposed",
1633
- "approved",
1634
- "applied",
1635
- "measuring",
1636
- "completed",
1637
- "reverted"
1638
- ]).optional().describe("Filter experiments by status"),
1639
- limit: z9.number().int().min(1).max(100).default(20).describe("Maximum number of experiments to return"),
1640
- cursor: z9.string().optional().describe("Pagination cursor from a previous response (meta.nextCursor)")
1641
- });
1642
- var getAsoLocaleSnapshotsSchema = z9.object({
1643
- assetId: z9.string().uuid().describe("App UUID to get locale snapshots for"),
1644
- store: z9.enum(["ios", "android"]).default("ios").describe("Which store listing to read"),
1645
- locale: z9.string().optional().describe(
1646
- 'Filter to a single locale (e.g. "en-US"). Returns all locales if omitted.'
1647
- ),
1648
- view: z9.enum(["latest", "history"]).default("latest").describe(
1649
- '"latest" (default) = newest snapshot per (locale, type); "history" = raw revisions newest first'
1650
- ),
1651
- limit: z9.number().int().min(1).max(500).optional().describe("Maximum snapshot rows to return (newest first)")
1652
- });
1653
- var triggerAsoAnalysisSchema = z9.object({
1654
- assetId: z9.string().uuid().describe("App UUID to trigger ASO analysis for")
1655
- });
1656
- async function getAsoSummary(input, client) {
1657
- try {
1658
- const response = await client.get(
1659
- `/api/assets/${input.assetId}/aso/summary`
1660
- );
1661
- return {
1662
- content: [
1663
- {
1664
- type: "text",
1665
- text: formatAsJson(response)
1666
- }
1667
- ]
1668
- };
1669
- } catch (error) {
1670
- return {
1671
- content: [
1672
- {
1673
- type: "text",
1674
- text: formatError(error)
1675
- }
1676
- ],
1677
- isError: true
1678
- };
1679
- }
1680
- }
1681
- async function getAsoRecommendations(input, client) {
1682
- try {
1683
- const response = await client.get(
1684
- `/api/assets/${input.assetId}/aso/recommendations`
1685
- );
1686
- return {
1687
- content: [
1688
- {
1689
- type: "text",
1690
- text: formatAsJson(response)
1691
- }
1692
- ]
1693
- };
1694
- } catch (error) {
1695
- return {
1696
- content: [
1697
- {
1698
- type: "text",
1699
- text: formatError(error)
1700
- }
1701
- ],
1702
- isError: true
1703
- };
1704
- }
1705
- }
1706
- async function getAsoKeywords(input, client) {
1707
- try {
1708
- const params = {};
1709
- if (input.locale) params.locale = input.locale;
1710
- const response = await client.get(
1711
- `/api/assets/${input.assetId}/aso/keyword-intelligence`,
1712
- params
1713
- );
1714
- return {
1715
- content: [
1716
- {
1717
- type: "text",
1718
- text: formatAsJson(response)
1719
- }
1720
- ]
1721
- };
1722
- } catch (error) {
1723
- return {
1724
- content: [
1725
- {
1726
- type: "text",
1727
- text: formatError(error)
1728
- }
1729
- ],
1730
- isError: true
1731
- };
1732
- }
1733
- }
1734
- async function getAsoExperiments(input, client) {
1735
- try {
1736
- const params = {
1737
- limit: input.limit,
1738
- cursor: input.cursor
1739
- };
1740
- if (input.status) params.status = input.status;
1741
- const response = await client.get(
1742
- `/api/assets/${input.assetId}/aso/experiments`,
1743
- params
1744
- );
1745
- return {
1746
- content: [
1747
- {
1748
- type: "text",
1749
- text: formatAsJson(response)
1750
- }
1751
- ]
1752
- };
1753
- } catch (error) {
1754
- return {
1755
- content: [
1756
- {
1757
- type: "text",
1758
- text: formatError(error)
1759
- }
1760
- ],
1761
- isError: true
1762
- };
1763
- }
1764
- }
1765
- async function getAsoLocaleSnapshots(input, client) {
1766
- try {
1767
- const response = await client.get(
1768
- `/api/assets/${input.assetId}/aso/listing-snapshots`,
1769
- {
1770
- store: input.store,
1771
- locale: input.locale,
1772
- view: input.view,
1773
- limit: input.limit
1774
- }
1775
- );
1776
- return {
1777
- content: [
1778
- {
1779
- type: "text",
1780
- text: formatAsJson(response)
1781
- }
1782
- ]
1783
- };
1784
- } catch (error) {
1785
- return {
1786
- content: [
1787
- {
1788
- type: "text",
1789
- text: formatError(error)
1790
- }
1791
- ],
1792
- isError: true
1793
- };
1794
- }
1795
- }
1796
- async function triggerAsoAnalysis(input, client) {
1797
- try {
1798
- const response = await client.post(
1799
- `/api/assets/${input.assetId}/aso/refetch`,
1800
- { force: true }
1801
- );
1802
- return {
1803
- content: [
1804
- {
1805
- type: "text",
1806
- text: formatAsJson(response)
1807
- }
1808
- ]
1809
- };
1810
- } catch (error) {
1811
- return {
1812
- content: [
1813
- {
1814
- type: "text",
1815
- text: formatError(error)
1816
- }
1817
- ],
1818
- isError: true
1819
- };
1820
- }
1821
- }
1822
- var getAsoEvidenceSchema = z9.object({ assetId: z9.string().uuid() });
1823
- async function getAsoEvidence(input, client) {
1824
- try {
1825
- const response = await client.get(
1826
- `/api/assets/${input.assetId}/aso/methodology`
1827
- );
1828
- return {
1829
- content: [{ type: "text", text: formatAsJson(response) }]
1830
- };
1831
- } catch (error) {
1832
- return {
1833
- content: [{ type: "text", text: formatError(error) }],
1834
- isError: true
1835
- };
1836
- }
1837
- }
1838
-
1839
- // src/tools/chat.ts
1840
- import { randomUUID as randomUUID2 } from "node:crypto";
1841
- import { z as z10 } from "zod";
1842
- var listConversationsSchema = z10.object({
1843
- limit: z10.number().int().min(1).max(100).default(20).describe("Maximum number of conversations to return")
1844
- });
1845
- var getConversationMessagesSchema = z10.object({
1846
- conversationId: z10.string().uuid().describe("The conversation UUID to get messages for")
1847
- });
1848
- var sendChatMessageSchema = z10.object({
1849
- message: z10.string().describe("The message to send to the AI chat"),
1850
- conversationId: z10.string().uuid().optional().describe(
1851
- "Existing conversation UUID to continue. Starts a new conversation if omitted."
1852
- ),
1853
- agentType: z10.string().optional().describe(
1854
- "Agent type to use for the conversation (e.g., review, monitoring)"
1855
- )
1856
- });
1857
- async function listConversations(input, client) {
1858
- try {
1859
- const response = await client.get("/api/chat/conversations", {
1860
- limit: input.limit
1861
- });
1862
- const conversations = response.data || response.conversations || response;
1863
- return {
1864
- content: [
1865
- {
1866
- type: "text",
1867
- text: formatAsJson({
1868
- totalConversations: Array.isArray(conversations) ? conversations.length : 0,
1869
- conversations
1870
- })
1871
- }
1872
- ]
1873
- };
1874
- } catch (error) {
1875
- return {
1876
- content: [
1877
- {
1878
- type: "text",
1879
- text: formatError(error)
1880
- }
1881
- ],
1882
- isError: true
1883
- };
1884
- }
1885
- }
1886
- async function getConversationMessages(input, client) {
1887
- try {
1888
- const response = await client.get(
1889
- `/api/chat/messages/${input.conversationId}`
1890
- );
1891
- const messages = response.data || response.messages || response;
1892
- return {
1893
- content: [
1894
- {
1895
- type: "text",
1896
- text: formatAsJson({
1897
- conversationId: input.conversationId,
1898
- totalMessages: Array.isArray(messages) ? messages.length : 0,
1899
- messages
1900
- })
1901
- }
1902
- ]
1903
- };
1904
- } catch (error) {
1905
- return {
1906
- content: [
1907
- {
1908
- type: "text",
1909
- text: formatError(error)
1910
- }
1911
- ],
1912
- isError: true
1913
- };
1914
- }
1915
- }
1916
- var FREE_CONVERSATION_LABEL = "Free: your first conversation";
1917
- var FREE_CONVERSATION_ENDED_NOTICE = "Your free first conversation has ended; messages now use credits.";
1918
- function answerCostOf(data) {
1919
- if (!data || typeof data !== "object") return null;
1920
- const usage = data;
1921
- const free = usage.freeConversation;
1922
- if (free && typeof free.messagesLeft === "number") {
1923
- return {
1924
- free: true,
1925
- label: FREE_CONVERSATION_LABEL,
1926
- messagesLeft: free.messagesLeft,
1927
- ...free.ended === true ? { notice: FREE_CONVERSATION_ENDED_NOTICE } : {}
1928
- };
1929
- }
1930
- return typeof usage.credits === "number" ? { free: false, credits: usage.credits } : null;
1931
- }
1932
- function parseUiMessageStream(raw) {
1933
- let reply = "";
1934
- const toolsUsed = [];
1935
- let cost = null;
1936
- for (const line of raw.split("\n")) {
1937
- if (!line.startsWith("data:")) continue;
1938
- const payload = line.slice(5).trim();
1939
- if (!payload || payload === "[DONE]") continue;
1940
- try {
1941
- const event = JSON.parse(payload);
1942
- if (event.type === "text-delta") {
1943
- reply += String(event.delta ?? event.textDelta ?? "");
1944
- } else if (typeof event.type === "string" && event.type === "tool-input-start" && typeof event.toolName === "string") {
1945
- toolsUsed.push(event.toolName);
1946
- } else if (event.type === "data-usage") {
1947
- cost = answerCostOf(event.data) ?? cost;
1948
- }
1949
- } catch {
1950
- }
1951
- }
1952
- return { reply, toolsUsed, cost };
1953
- }
1954
- async function sendChatMessage(input, client) {
1955
- try {
1956
- const conversationId = input.conversationId ?? randomUUID2();
1957
- let priorMessages = [];
1958
- if (input.conversationId) {
1959
- const history = await client.get(`/api/chat/messages/${input.conversationId}`, { limit: 1e3 });
1960
- for (const message of history.data ?? []) {
1961
- const textParts = (message.parts ?? []).filter(
1962
- (part) => part.type === "text" && typeof part.text === "string"
1963
- );
1964
- if (textParts.length === 0) continue;
1965
- priorMessages.push({
1966
- id: message.id,
1967
- role: message.role,
1968
- parts: textParts
1969
- });
1970
- }
1971
- priorMessages = priorMessages.slice(-100);
1972
- }
1973
- const body = {
1974
- id: conversationId,
1975
- messages: [
1976
- ...priorMessages,
1977
- {
1978
- id: randomUUID2(),
1979
- role: "user",
1980
- parts: [{ type: "text", text: input.message }]
1981
- }
1982
- ]
1983
- };
1984
- if (input.agentType) {
1985
- body.agentContext = {
1986
- agentId: null,
1987
- agentType: input.agentType,
1988
- agentName: input.agentType,
1989
- surface: "mcp"
1990
- };
1991
- }
1992
- const raw = await client.postStream("/api/chat", body);
1993
- const { reply, toolsUsed, cost } = parseUiMessageStream(raw);
1994
- return {
1995
- content: [
1996
- {
1997
- type: "text",
1998
- text: formatAsJson({
1999
- conversationId,
2000
- reply: reply || "The assistant returned no text response.",
2001
- toolsUsed,
2002
- // FLO-2669: the credits the answer used, or that it was free.
2003
- ...cost ? { cost } : {},
2004
- tip: "Pass this conversationId to continue the conversation or to get_conversation_messages for the full transcript."
2005
- })
2006
- }
2007
- ],
2008
- ...reply ? {} : { isError: true }
2009
- };
2010
- } catch (error) {
2011
- return {
2012
- content: [
2013
- {
2014
- type: "text",
2015
- text: formatError(error)
2016
- }
2017
- ],
2018
- isError: true
2019
- };
2020
- }
2021
- }
2022
-
2023
- // src/tools/index.ts
2024
- function registerTools(server, client, options = {}) {
2025
- const rateLimiter = options.rateLimiter ?? new RateLimiter(100, 6e4);
2026
- function wrapTool(handler) {
2027
- const callback = async (input) => {
2028
- const rateCheck = rateLimiter.check("default");
2029
- if (!rateCheck.allowed) {
2030
- return {
2031
- content: [
2032
- {
2033
- type: "text",
2034
- text: `Rate limit exceeded. Try again in ${Math.ceil(
2035
- rateCheck.retryAfterMs / 1e3
2036
- )}s. Limit: 100 requests/minute.`
2037
- }
2038
- ],
2039
- isError: true
2040
- };
2041
- }
2042
- return handler(input, client);
2043
- };
2044
- return callback;
2045
- }
2046
- function tool(name, title, description, schema, handler, annotations) {
2047
- server.registerTool(
2048
- name,
2049
- {
2050
- title,
2051
- description,
2052
- inputSchema: schema,
2053
- annotations: { title, ...annotations }
2054
- },
2055
- wrapTool(handler)
2056
- );
2057
- }
2058
- tool(
2059
- "list_apps",
2060
- "List apps",
2061
- "List all mobile apps in your Fload organization. Returns app metadata including name, bundle ID, platform (iOS/Android), icon URL, and category.",
2062
- listAppsSchema,
2063
- listApps,
2064
- { readOnlyHint: true, openWorldHint: false }
2065
- );
2066
- tool(
2067
- "get_app_details",
2068
- "Get app details",
2069
- "Get detailed information about a specific app, including metadata, connected data sources (App Store Connect, Google Play Console), and sync status. Provide either assetId (UUID) or bundleId.",
2070
- getAppDetailsSchema,
2071
- getAppDetails,
2072
- { readOnlyHint: true, openWorldHint: false }
2073
- );
2074
- tool(
2075
- "get_reviews",
2076
- "Get reviews",
2077
- 'Get app reviews with flexible filtering. Filter by app (assetId or bundleId), platform, rating (1-5 stars), replied status, and date range. Returns reviews with metadata, author, body text, and reply status. For an App Store reply, replyPublication says where it stands at Apple: "publishing" (sent; Apple has not published it yet, usually within a day), "live" (live on the App Store), "removed" (Apple no longer shows it), or null (not known: never call it live). Useful for sentiment analysis, support workflows, and review management.',
2078
- getReviewsSchema,
2079
- getReviews,
2080
- { readOnlyHint: true, openWorldHint: false }
2081
- );
2082
- tool(
2083
- "generate_review_reply",
2084
- "Generate review reply (AI draft)",
2085
- "Generate an AI draft reply for an app review. The AI uses the review context and any configured agent settings (tone, custom instructions) to craft a response. Returns the generated draft text. Does not publish \u2014 call send_review_reply or approve_action to publish the draft.",
2086
- generateReviewReplySchema,
2087
- generateReviewReply,
2088
- { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
2089
- );
2090
- tool(
2091
- "send_review_reply",
2092
- "Send review reply",
2093
- "Send a reply to an app review on the App Store or Google Play. The response text will be submitted as the developer response. This is a write operation that publishes the reply publicly \u2014 treat as destructive (cannot be silently undone). Needs the write:reviews and write:agents (Approve and run) permissions, as approving a reply in the inbox does.",
2094
- sendReviewReplySchema,
2095
- sendReviewReply,
2096
- { readOnlyHint: false, destructiveHint: true, openWorldHint: true }
2097
- );
2098
- tool(
2099
- "translate_review",
2100
- "Translate review",
2101
- "Translate a review to English. Useful for reviews written in other languages. Pass the review content fields (rating, title, body, storeFront, appVersionString) from a get_reviews result. Returns the translated text. Does not modify the review in Fload.",
2102
- translateReviewSchema,
2103
- translateReview,
2104
- { readOnlyHint: true, openWorldHint: true }
2105
- );
2106
- tool(
2107
- "discover_metrics",
2108
- "Discover available metrics",
2109
- "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.",
2110
- discoverMetricsSchema,
2111
- discoverMetrics,
2112
- { readOnlyHint: true, openWorldHint: false }
2113
- );
2114
- tool(
2115
- "get_metrics",
2116
- "Get metrics",
2117
- "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. A requested metric the API could not report, on a total or a breakdown read, is listed with summary null and unavailable {reason, message}: reason not_reported means none of the app's connected sources has ever sent it (say it is not reported); no_data means nothing in this window; source_filter means a source filter, a dimension filter or the breakdown's dimension hides it (the metric has no rows split that way). Never quote it as 0. Use discover_metrics first to see available metrics.",
2118
- getMetricsSchema,
2119
- getMetrics,
2120
- { readOnlyHint: true, openWorldHint: false }
2121
- );
2122
- tool(
2123
- "discover_dimensions",
2124
- "Discover available dimensions",
2125
- "Discover available dimensions for breaking down metrics (e.g., country, platform, app version, campaign). Optionally get the available values for a specific dimension.",
2126
- discoverDimensionsSchema,
2127
- discoverDimensions,
2128
- { readOnlyHint: true, openWorldHint: false }
2129
- );
2130
- tool(
2131
- "get_download_impact",
2132
- "Get what Fload changed on downloads",
2133
- "Did Fload's listing changes move downloads, overall or in one country? For an App Store app: downloads by source a week (organicSearch = App Store search minus Apple Ads, appleAds, browse, appReferrer, webReferrer, other, total) with the same days last year (364 days back) and an index of each year to its own first four weeks; markers for releases, each Fload listing change on the day written and the day live (with the storefronts that read its locales) and the iOS launch week; the 21 days before Fload's first change against the latest 21 days; storefronts by role (changed: a changed localization is its own language; reads_changed: it also reads one, e.g. the US reads es-MX; control: reads nothing changed) with organic downloads a day before and after, this year and last; and each touched keyword's median rank before and after. Listing changes can only move organic App Store search: judge them on organicSearch against last year, never on total, paid or browse. Null means unknown, never 0.",
2134
- getDownloadImpactSchema,
2135
- getDownloadImpact,
2136
- { readOnlyHint: true, openWorldHint: false }
2137
- );
2138
- tool(
2139
- "list_agents",
2140
- "List agents",
2141
- "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.",
2142
- listAgentsSchema,
2143
- listAgents,
2144
- { readOnlyHint: true, openWorldHint: false }
2145
- );
2146
- tool(
2147
- "get_agent_details",
2148
- "Get agent details",
2149
- "Get detailed configuration and status for a specific agent type. For the review agent, returns per-asset settings (mode, tone, custom instructions).",
2150
- getAgentDetailsSchema,
2151
- getAgentDetails,
2152
- { readOnlyHint: true, openWorldHint: false }
2153
- );
2154
- tool(
2155
- "get_agent_run_history",
2156
- "Get agent run history",
2157
- "Get run history for a specific agent type. Returns run status, timing, and error details.",
2158
- getAgentRunHistorySchema,
2159
- getAgentRunHistory,
2160
- { readOnlyHint: true, openWorldHint: false }
2161
- );
2162
- tool(
2163
- "trigger_agent_run",
2164
- "Trigger agent run",
2165
- "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.",
2166
- triggerAgentRunSchema,
2167
- triggerAgentRun,
2168
- { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
2169
- );
2170
- tool(
2171
- "pause_agent",
2172
- "Pause agent",
2173
- "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.",
2174
- pauseAgentSchema,
2175
- pauseAgent,
2176
- {
2177
- readOnlyHint: false,
2178
- destructiveHint: false,
2179
- idempotentHint: true,
2180
- openWorldHint: false
2181
- }
2182
- );
2183
- tool(
2184
- "resume_agent",
2185
- "Resume agent",
2186
- "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.",
2187
- resumeAgentSchema,
2188
- resumeAgent,
2189
- {
2190
- readOnlyHint: false,
2191
- destructiveHint: false,
2192
- idempotentHint: true,
2193
- openWorldHint: false
2194
- }
2195
- );
2196
- tool(
2197
- "get_agent_activity",
2198
- "Get agent activity",
2199
- "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.",
2200
- getAgentActivitySchema,
2201
- getAgentActivity,
2202
- { readOnlyHint: true, openWorldHint: false }
2203
- );
2204
- tool(
2205
- "get_ads_performance",
2206
- "Get ads performance",
2207
- "Get ad campaign performance data across platforms (Apple Search Ads, Google Ads, Meta Ads, TikTok Ads). Returns campaign metadata, status, and for Apple Search Ads includes daily performance snapshots (spend, impressions, taps, installs, CPI, TTR, conversion rate).",
2208
- getAdsPerformanceSchema,
2209
- getAdsPerformance,
2210
- { readOnlyHint: true, openWorldHint: false }
2211
- );
2212
- tool(
2213
- "get_dashboard_overview",
2214
- "Get dashboard overview",
2215
- "Get an aggregated dashboard overview for the organization. Returns portfolio summary (apps, valuations, ratings), data connector health status, and alerts (pending review drafts).",
2216
- getDashboardOverviewSchema,
2217
- getDashboardOverview,
2218
- { readOnlyHint: true, openWorldHint: false }
2219
- );
2220
- tool(
2221
- "list_pending_actions",
2222
- "List pending actions",
2223
- '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.',
2224
- listPendingActionsSchema,
2225
- listPendingActions,
2226
- { readOnlyHint: true, openWorldHint: false }
2227
- );
2228
- tool(
2229
- "approve_action",
2230
- "Approve pending action",
2231
- "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).",
2232
- approveActionSchema,
2233
- approveAction,
2234
- { readOnlyHint: false, destructiveHint: true, openWorldHint: true }
2235
- );
2236
- tool(
2237
- "reject_action",
2238
- "Reject pending action",
2239
- "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.",
2240
- rejectActionSchema,
2241
- rejectAction,
2242
- { readOnlyHint: false, destructiveHint: true, openWorldHint: false }
2243
- );
2244
- tool(
2245
- "check_action_now",
2246
- "Check a change in the store now",
2247
- '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.',
2248
- checkActionNowSchema,
2249
- checkActionNow,
2250
- { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
2251
- );
2252
- tool(
2253
- "rename_custom_page_action",
2254
- "Rename a custom product page request and send it",
2255
- '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.',
2256
- renameCustomPageActionSchema,
2257
- renameCustomPageAction,
2258
- { readOnlyHint: false, destructiveHint: true, openWorldHint: true }
2259
- );
2260
- tool(
2261
- "get_aso_summary",
2262
- "Get ASO summary",
2263
- "Get the ASO (App Store Optimization) score, health status, and overview for an app. Returns an overall optimization score and key ASO health indicators. Use this for a quick snapshot of how well an app is optimized for store search and discovery.",
2264
- getAsoSummarySchema,
2265
- getAsoSummary,
2266
- { readOnlyHint: true, openWorldHint: false }
2267
- );
2268
- tool(
2269
- "get_aso_recommendations",
2270
- "Get ASO recommendations",
2271
- "Get actionable ASO recommendations for an app, including suggested improvements to the title, subtitle, keywords, and description. Each recommendation explains the rationale and expected impact on search visibility.",
2272
- getAsoRecommendationsSchema,
2273
- getAsoRecommendations,
2274
- { readOnlyHint: true, openWorldHint: false }
2275
- );
2276
- tool(
2277
- "get_aso_evidence",
2278
- "Get ASO decisions and evidence",
2279
- "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.",
2280
- getAsoEvidenceSchema,
2281
- getAsoEvidence,
2282
- { readOnlyHint: true, openWorldHint: false }
2283
- );
2284
- tool(
2285
- "get_aso_keywords",
2286
- "Get ASO keywords",
2287
- 'Get keyword intelligence for an app \u2014 current keyword rankings, search volume estimates, difficulty scores, and competitor keyword data. Optionally filter by locale (e.g., "en-US"). Useful for identifying keyword opportunities and tracking ranking changes.',
2288
- getAsoKeywordsSchema,
2289
- getAsoKeywords,
2290
- { readOnlyHint: true, openWorldHint: false }
2291
- );
2292
- tool(
2293
- "get_aso_experiments",
2294
- "Get ASO experiments",
2295
- "List ASO experiments (A/B tests and metadata changes) for an app. Filter by status: proposed, approved, applied, measuring, completed, or reverted. Returns experiment details, variants, and results when available. Supports pagination.",
2296
- getAsoExperimentsSchema,
2297
- getAsoExperiments,
2298
- { readOnlyHint: true, openWorldHint: false }
2299
- );
2300
- tool(
2301
- "get_aso_locale_snapshots",
2302
- "Get ASO locale snapshots",
2303
- '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.',
2304
- getAsoLocaleSnapshotsSchema,
2305
- getAsoLocaleSnapshots,
2306
- { readOnlyHint: true, openWorldHint: false }
2307
- );
2308
- tool(
2309
- "trigger_aso_analysis",
2310
- "Trigger ASO analysis",
2311
- "Trigger a new ASO analysis run for an app. This kicks off a fresh evaluation of the app's store listing metadata, keyword rankings, and competitive positioning. Results will be reflected in subsequent calls to get_aso_summary and get_aso_recommendations.",
2312
- triggerAsoAnalysisSchema,
2313
- triggerAsoAnalysis,
2314
- { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
2315
- );
2316
- tool(
2317
- "list_conversations",
2318
- "List conversations",
2319
- "List chat conversations in the Fload AI chat. Returns conversation metadata including title, creation date, and last message preview. Use limit to control how many are returned.",
2320
- listConversationsSchema,
2321
- listConversations,
2322
- { readOnlyHint: true, openWorldHint: false }
2323
- );
2324
- tool(
2325
- "get_conversation_messages",
2326
- "Get conversation messages",
2327
- "Get all messages in a specific chat conversation. Returns the full message history including user messages and AI responses with timestamps and roles.",
2328
- getConversationMessagesSchema,
2329
- getConversationMessages,
2330
- { readOnlyHint: true, openWorldHint: false }
2331
- );
2332
- tool(
2333
- "send_chat_message",
2334
- "Send chat message",
2335
- "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. The result's `cost` says what the answer used: `credits`, or `free: true` with the free answers left when a new organization's free first conversation carried it (and a `notice` on the answer that ended it).",
2336
- sendChatMessageSchema,
2337
- sendChatMessage,
2338
- { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
2339
- );
2340
- }
2341
- export {
2342
- FREE_CONVERSATION_ENDED_NOTICE,
2343
- FREE_CONVERSATION_LABEL,
2344
- UNAVAILABLE_REASONS,
2345
- approveAction,
2346
- approveActionSchema,
2347
- checkActionNow,
2348
- checkActionNowSchema,
2349
- discoverDimensions,
2350
- discoverDimensionsSchema,
2351
- discoverMetrics,
2352
- discoverMetricsSchema,
2353
- generateReviewReply,
2354
- generateReviewReplySchema,
2355
- getAdsPerformance,
2356
- getAdsPerformanceSchema,
2357
- getAgentActivity,
2358
- getAgentActivitySchema,
2359
- getAgentDetails,
2360
- getAgentDetailsSchema,
2361
- getAgentRunHistory,
2362
- getAgentRunHistorySchema,
2363
- getAppDetails,
2364
- getAppDetailsSchema,
2365
- getAsoEvidence,
2366
- getAsoEvidenceSchema,
2367
- getAsoExperiments,
2368
- getAsoExperimentsSchema,
2369
- getAsoKeywords,
2370
- getAsoKeywordsSchema,
2371
- getAsoLocaleSnapshots,
2372
- getAsoLocaleSnapshotsSchema,
2373
- getAsoRecommendations,
2374
- getAsoRecommendationsSchema,
2375
- getAsoSummary,
2376
- getAsoSummarySchema,
2377
- getConversationMessages,
2378
- getConversationMessagesSchema,
2379
- getDashboardOverview,
2380
- getDashboardOverviewSchema,
2381
- getDownloadImpact,
2382
- getDownloadImpactSchema,
2383
- getMetrics,
2384
- getMetricsSchema,
2385
- getReviews,
2386
- getReviewsSchema,
2387
- listAgents,
2388
- listAgentsSchema,
2389
- listApps,
2390
- listAppsSchema,
2391
- listConversations,
2392
- listConversationsSchema,
2393
- listPendingActions,
2394
- listPendingActionsSchema,
2395
- parseUiMessageStream,
2396
- pauseAgent,
2397
- pauseAgentSchema,
2398
- registerTools,
2399
- rejectAction,
2400
- rejectActionSchema,
2401
- renameCustomPageAction,
2402
- renameCustomPageActionSchema,
2403
- resumeAgent,
2404
- resumeAgentSchema,
2405
- sendChatMessage,
2406
- sendChatMessageSchema,
2407
- sendReviewReply,
2408
- sendReviewReplySchema,
2409
- translateReview,
2410
- translateReviewSchema,
2411
- triggerAgentRun,
2412
- triggerAgentRunSchema,
2413
- triggerAsoAnalysis,
2414
- triggerAsoAnalysisSchema
2415
- };
2416
- //# sourceMappingURL=index.js.map