@fload-ai/mcp 0.12.2 → 0.12.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/rate-limiter.ts", "../../src/tools/apps.ts", "../../src/lib/format.ts", "../../src/tools/reviews.ts", "../../src/tools/analytics.ts", "../../src/tools/download-impact.ts", "../../src/tools/agents.ts", "../../src/tools/ads.ts", "../../src/tools/dashboard.ts", "../../src/tools/actions.ts", "../../src/public-errors.ts", "../../src/tools/aso.ts", "../../src/tools/chat.ts", "../../src/tools/index.ts"],
4
- "sourcesContent": ["export class RateLimiter {\n private calls: Map<string, number[]> = new Map();\n\n constructor(\n private maxCalls: number = 100,\n private windowMs: number = 60_000\n ) {}\n\n check(key: string): {\n allowed: boolean;\n remaining: number;\n retryAfterMs: number;\n } {\n const now = Date.now();\n const windowStart = now - this.windowMs;\n\n // Get existing calls, prune expired\n let timestamps = this.calls.get(key) || [];\n timestamps = timestamps.filter(t => t > windowStart);\n\n if (timestamps.length >= this.maxCalls) {\n // With maxCalls 0 there is no call in the window to wait out.\n const [oldestInWindow] = timestamps;\n const retryAfterMs =\n oldestInWindow === undefined\n ? Number.NaN\n : oldestInWindow + this.windowMs - now;\n this.calls.set(key, timestamps);\n return { allowed: false, remaining: 0, retryAfterMs };\n }\n\n timestamps.push(now);\n this.calls.set(key, timestamps);\n return {\n allowed: true,\n remaining: this.maxCalls - timestamps.length,\n retryAfterMs: 0,\n };\n }\n}\n", "/**\n * App management tools for MCP\n * Tools: list_apps, get_app_details\n */\n\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\ninterface AppRecord {\n id: string;\n name: string;\n bundleId: string;\n appleAppId?: string | null;\n googleAppId?: string | null;\n currentValuation?: string | number | null;\n metadata?: unknown;\n createdAt?: string | null;\n updatedAt?: string | null;\n}\n\ninterface AppListResponse {\n data?: AppRecord[];\n}\n\ninterface AppDetailResponse {\n data?: AppRecord;\n}\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const listAppsSchema = z.object({\n platform: z\n .enum(['ios', 'android'])\n .optional()\n .describe('Filter by platform (ios or android)'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .default(50)\n .describe('Maximum number of apps to return'),\n});\n\nexport const getAppDetailsSchema = z.object({\n assetId: z\n .string()\n .uuid()\n .optional()\n .describe('App UUID from Fload database'),\n bundleId: z\n .string()\n .optional()\n .describe('App bundle ID (e.g., com.example.app)'),\n});\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * List all apps in the organization\n */\nexport async function listApps(\n input: z.input<typeof listAppsSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get<AppListResponse>('/api/assets', {\n limit: input.limit,\n offset: 0,\n // The listing hides assets without a valuation by default; \"list all\n // apps\" must include apps that haven't been valued yet (FLO-734).\n includeUnvalued: 'true',\n });\n const apps = response.data ?? [];\n\n // Filter by platform client-side if needed\n const filtered = input.platform\n ? apps.filter(app => {\n if (input.platform === 'ios') return !!app.appleAppId;\n if (input.platform === 'android') return !!app.googleAppId;\n return true;\n })\n : apps;\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n total: filtered.length,\n apps: filtered.map(app => ({\n id: app.id,\n name: app.name,\n bundleId: app.bundleId,\n platform: app.appleAppId\n ? 'ios'\n : app.googleAppId\n ? 'android'\n : 'unknown',\n addedAt: app.updatedAt || app.createdAt,\n })),\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Get detailed information about a specific app\n */\nexport async function getAppDetails(\n input: z.input<typeof getAppDetailsSchema>,\n client: FloadApiClient\n) {\n try {\n if (!input.assetId && !input.bundleId) {\n throw new Error('Either assetId or bundleId must be provided');\n }\n\n let assetId = input.assetId;\n\n // If bundleId provided, find the asset first\n if (!assetId && input.bundleId) {\n const allApps = await client.get<AppListResponse>('/api/assets', {\n limit: 100,\n offset: 0,\n includeUnvalued: 'true',\n });\n const match = (allApps.data ?? []).find(\n app => app.bundleId === input.bundleId\n );\n if (!match) {\n return {\n content: [\n {\n type: 'text' as const,\n text: 'App not found with that bundle ID',\n },\n ],\n isError: true,\n };\n }\n assetId = match.id;\n }\n\n const response = await client.get<AppDetailResponse>(\n `/api/assets/${assetId}`\n );\n const app = response.data;\n if (!app) {\n throw new Error('App details response did not include app data');\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n id: app.id,\n name: app.name,\n bundleId: app.bundleId,\n appleAppId: app.appleAppId,\n googleAppId: app.googleAppId,\n platform: app.appleAppId\n ? 'ios'\n : app.googleAppId\n ? 'android'\n : 'unknown',\n currentValuation: app.currentValuation,\n metadata: app.metadata,\n addedAt: app.createdAt,\n updatedAt: app.updatedAt,\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n", "/**\n * Data formatting utilities for MCP tool responses\n */\n\n/**\n * Format database results as JSON text for MCP response\n */\nexport function formatAsJson(data: unknown): string {\n return JSON.stringify(data, null, 2);\n}\n\n/**\n * Format error message for MCP error response\n */\nexport function formatError(error: unknown): string {\n if (error instanceof Error) {\n return `Error: ${error.message}`;\n }\n return `Unknown error: ${String(error)}`;\n}\n\n/**\n * Format date for display\n */\nexport function formatDate(date: Date): string {\n return date.toISOString().split('T')[0]!;\n}\n\n/**\n * Format large numbers with commas\n */\nexport function formatNumber(num: number): string {\n return num.toLocaleString();\n}\n", "/**\n * Review management tools for MCP\n * Tools: get_reviews, generate_review_reply, send_review_reply, translate_review\n */\n\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\ninterface AppRecord {\n id: string;\n bundleId: string;\n}\n\ninterface AppListResponse {\n data?: AppRecord[];\n}\n\ninterface ReviewRecord {\n id: string;\n appId?: string;\n platform?: string;\n rating?: number | string | null;\n title?: string | null;\n /** The handler maps DB `body` to API `review`. */\n review?: string | null;\n body?: string | null;\n nickname?: string | null;\n author?: string | null;\n lastModified?: number | string | null;\n date?: string | null;\n appVersionString?: string | null;\n version?: string | null;\n storeFront?: string | null;\n developerResponse?:\n | string\n | {\n response?: string | null;\n /** FLO-2571: live | publishing | removed | null, as the API reads it. */\n publication?: string | null;\n }\n | null;\n replySource?: 'agent' | 'user' | null;\n hasDraft?: boolean | null;\n hasReply?: boolean | null;\n reply?: string | null;\n}\n\n/**\n * GET /api/assets/:assetId/reviews returns\n * `{ data: { reviews, reviewCount, handledCount }, meta }` (FLO-734).\n */\ninterface ReviewsResponse {\n data?: {\n reviews?: ReviewRecord[];\n reviewCount?: number;\n /** Continuation for the next page; null/absent on the last page. */\n nextCursor?: string | null;\n handledCount?: number;\n };\n}\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const getReviewsSchema = z.object({\n assetId: z.string().uuid().optional().describe('App UUID to filter reviews'),\n bundleId: z.string().optional().describe('App bundle ID to filter reviews'),\n platform: z\n .enum(['ios', 'android'])\n .optional()\n .describe('Filter by platform'),\n rating: z\n .number()\n .int()\n .min(1)\n .max(5)\n .optional()\n .describe('Filter by star rating (1-5)'),\n replied: z\n .boolean()\n .optional()\n .describe('Filter by replied status (true = has reply, false = no reply)'),\n startDate: z\n .string()\n .optional()\n .describe('Filter reviews from this date (ISO format: YYYY-MM-DD)'),\n endDate: z\n .string()\n .optional()\n .describe('Filter reviews until this date (ISO format: YYYY-MM-DD)'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(200)\n .default(50)\n .describe('Maximum number of reviews to return'),\n cursor: z\n .string()\n .optional()\n .describe(\n 'nextCursor from the previous get_reviews call, to fetch the next page with the same app and filters'\n ),\n sortBy: z\n .enum(['date', 'rating'])\n .default('date')\n .describe('Sort reviews by date or rating'),\n});\n\nexport const generateReviewReplySchema = z.object({\n reviewId: z.string().describe('The review UUID to generate a reply for'),\n assetId: z.string().uuid().describe('The app UUID the review belongs to'),\n});\n\nexport const sendReviewReplySchema = z.object({\n reviewId: z.string().describe('The review UUID to reply to'),\n assetId: z.string().uuid().describe('The app UUID the review belongs to'),\n response: z.string().describe('The reply text to send'),\n});\n\nexport const translateReviewSchema = z.object({\n reviewId: z.string().describe('The review UUID to translate'),\n assetId: z.string().uuid().describe('The app UUID the review belongs to'),\n // The translate endpoint receives the review content in the request body\n // (it does not re-fetch it). Pass the fields from a get_reviews result.\n rating: z\n .number()\n .int()\n .min(1)\n .max(5)\n .describe('The review star rating, from get_reviews'),\n title: z.string().default('').describe('The review title, from get_reviews'),\n body: z.string().describe('The review text to translate, from get_reviews'),\n storeFront: z\n .string()\n .default('')\n .describe('The review storefront (e.g. \"SE\"), from get_reviews'),\n appVersionString: z\n .string()\n .default('')\n .describe('The app version the review was left on, from get_reviews'),\n});\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * Get reviews with filters\n */\nexport async function getReviews(\n input: z.input<typeof getReviewsSchema>,\n client: FloadApiClient\n) {\n try {\n // Resolve assetId from bundleId if needed\n let assetId = input.assetId;\n if (!assetId && input.bundleId) {\n const allApps = await client.get<AppListResponse>('/api/assets', {\n limit: 100,\n offset: 0,\n includeUnvalued: 'true',\n });\n const match = (allApps.data ?? []).find(\n app => app.bundleId === input.bundleId\n );\n if (!match) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `No app found with bundle ID: ${input.bundleId}`,\n },\n ],\n isError: true,\n };\n }\n assetId = match.id;\n }\n\n // Reviews live under /api/assets/:assetId/reviews \u2014 there is no\n // cross-asset listing route, so an app must be identified first.\n if (!assetId) {\n return {\n content: [\n {\n type: 'text' as const,\n text: 'Provide an assetId (or bundleId) to fetch reviews for. Use list_apps to find app IDs.',\n },\n ],\n isError: true,\n };\n }\n\n const params: Record<string, string | number | boolean | undefined> =\n reviewQueryParameters(input);\n\n const response = await client.get<ReviewsResponse>(\n `/api/assets/${assetId}/reviews`,\n params\n );\n let reviews = response.data?.reviews ?? [];\n // The API returns reviews date-sorted; rating sort is client-side.\n if (input.sortBy === 'rating') {\n reviews = [...reviews].sort(\n (a, b) => Number(b.rating ?? 0) - Number(a.rating ?? 0)\n );\n }\n\n const hasReply = (review: ReviewRecord) =>\n !!(review.developerResponse || review.replySource || review.hasReply);\n\n // Calculate summary stats\n const summary = {\n totalReviews: reviews.length,\n averageRating:\n reviews.length > 0\n ? (\n reviews.reduce((sum, review) => {\n const rating = Number(review.rating ?? 0);\n return sum + (Number.isFinite(rating) ? rating : 0);\n }, 0) / reviews.length\n ).toFixed(2)\n : 0,\n repliedCount: reviews.filter(review => hasReply(review)).length,\n unrepliedCount: reviews.filter(review => !hasReply(review)).length,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n summary,\n // Pass back as `cursor` to get the next page; null = last page.\n nextCursor: response.data?.nextCursor ?? null,\n reviews: reviews.map(review => ({\n id: review.id,\n appId: review.appId,\n platform: review.platform,\n rating: review.rating,\n title: review.title,\n // The handler exposes the review text as `review`.\n body: review.review ?? review.body,\n author: review.nickname || review.author,\n // Epoch ms from the handler.\n date: review.lastModified || review.date,\n version: review.appVersionString || review.version,\n storeFront: review.storeFront,\n hasReply: hasReply(review),\n replySource: review.replySource ?? null,\n hasDraft: review.hasDraft ?? false,\n reply: review.developerResponse\n ? typeof review.developerResponse === 'object'\n ? review.developerResponse.response\n : review.developerResponse\n : review.reply || null,\n // FLO-2571: where an App Store reply stands at Apple.\n replyPublication:\n typeof review.developerResponse === 'object'\n ? (review.developerResponse?.publication ?? null)\n : null,\n })),\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\nfunction reviewQueryParameters(input: z.input<typeof getReviewsSchema>) {\n const params: Record<string, string | number | boolean | undefined> = {\n limit: input.limit,\n };\n if (input.cursor) params.cursor = input.cursor;\n\n if (input.platform) params.platform = input.platform;\n if (input.rating !== undefined) params.rating = input.rating;\n if (input.replied !== undefined)\n params.responseStatus = input.replied ? 'replied' : 'unreplied';\n if (input.startDate) params.startDate = input.startDate;\n if (input.endDate) params.endDate = input.endDate;\n return params;\n}\n\n/**\n * Generate an AI draft reply for a review\n */\nexport async function generateReviewReply(\n input: z.input<typeof generateReviewReplySchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.post(\n `/api/assets/${input.assetId}/reviews/${input.reviewId}/generate-reply`,\n undefined\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Send a reply to an app review\n */\nexport async function sendReviewReply(\n input: z.input<typeof sendReviewReplySchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.post(\n `/api/assets/${input.assetId}/reviews/${input.reviewId}/respond`,\n // The API handler reads `responseText` from the body.\n { responseText: input.response }\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Translate a review to English\n */\nexport async function translateReview(\n input: z.input<typeof translateReviewSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.post(\n `/api/assets/${input.assetId}/reviews/${input.reviewId}/translate`,\n // The translate endpoint expects the review content in the body.\n {\n rating: input.rating,\n title: input.title,\n review: input.body,\n storeFront: input.storeFront,\n appVersionString: input.appVersionString,\n lastModified: Date.now(),\n }\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n", "/**\n * Metrics discovery and query tools for MCP\n * Tools: discover_metrics, get_metrics, discover_dimensions\n */\n\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\ninterface MetricAvailabilityResponse {\n data?: {\n availableMetrics?: string[];\n metricGroups?: Record<string, unknown>;\n };\n}\n\ninterface EnrichedMetric {\n name: string;\n displayName: string;\n category: string;\n type: string;\n}\n\n/** A plain point carries `value`; a breakdown point carries `total`. */\ninterface MetricPoint {\n date: string;\n value?: number;\n total?: number;\n}\n\ninterface MetricChange {\n currentValue?: number;\n effectiveFromDate?: string;\n effectiveToDate?: string;\n}\n\n/**\n * A breakdown read's value per dimension value (a country), as the Fload API\n * computes it for the metric's aggregation class (FLO-2487): `basis` says\n * what each value is. `total` sums the days; `latest` is the period's last\n * day (active subscriptions), never a sum; `daily_average` is a unique\n * metric's average a day (active devices), never a total for the period;\n * `average` and `ratio` are rates, which have no total.\n */\ninterface BreakdownPeriod {\n basis: 'total' | 'latest' | 'average' | 'daily_average' | 'ratio';\n total: number | null;\n previousTotal: number | null;\n change: number | null;\n values: Array<{\n label: string;\n code: string;\n value: number | null;\n previousValue: number | null;\n change: number | null;\n share: number | null;\n }>;\n}\n\ninterface MetricsTimeseriesResponse {\n data?: Record<string, MetricPoint[]>;\n changes?: Record<string, MetricChange | undefined>;\n breakdownTotals?: Record<string, BreakdownPeriod | undefined>;\n meta?: unknown;\n}\n\ninterface MetricSummary {\n /**\n * The metric's value over the period, as the Fload API computes it for the\n * metric's aggregation class: a sum for flows (downloads, proceeds), the\n * last value for levels (active subscriptions), an average for stored rates,\n * and the ratio of the period's sums for computed ratios (CPA, ARPPU).\n * It covers every requested day except recent days whose data is not\n * complete yet. Null when the API has no value for the period.\n */\n value: number | null;\n /** The first and last day `value` covers. */\n effectiveFromDate: string | null;\n effectiveToDate: string | null;\n min: number | null;\n max: number | null;\n dataPoints: number;\n}\n\nfunction summarize(\n points: MetricPoint[] | undefined,\n change: MetricChange | undefined\n): MetricSummary {\n const values = (Array.isArray(points) ? points : [])\n .map(point => point.value ?? point.total)\n .filter((value): value is number => typeof value === 'number');\n return {\n value: change?.currentValue ?? null,\n effectiveFromDate: change?.effectiveFromDate ?? null,\n effectiveToDate: change?.effectiveToDate ?? null,\n min: values.length > 0 ? Math.min(...values) : null,\n max: values.length > 0 ? Math.max(...values) : null,\n dataPoints: values.length,\n };\n}\n\ninterface DimensionValuesResponse {\n data?: unknown;\n}\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const discoverMetricsSchema = z.object({\n assetId: z\n .string()\n .uuid()\n .describe('App UUID to check available metrics for'),\n});\n\nexport const getMetricsSchema = z.object({\n assetId: z.string().uuid().describe('App UUID'),\n metrics: z\n .array(z.string())\n .min(1)\n .describe(\n 'Metric names to query (e.g., [\"proceeds\", \"totalDownloads\"]). Use discover_metrics first to see available metrics.'\n ),\n startDate: z\n .string()\n .optional()\n .describe('Start date (YYYY-MM-DD). Defaults to 30 days ago.'),\n endDate: z\n .string()\n .optional()\n .describe('End date (YYYY-MM-DD). Defaults to today.'),\n granularity: z\n .enum(['daily', 'weekly', 'monthly'])\n .default('daily')\n .describe('Data granularity'),\n dimension: z\n .string()\n .optional()\n .describe(\n '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.'\n ),\n dimensionFilter: z\n .string()\n .optional()\n .describe(\n 'Filter to a specific dimension value (e.g., \"US\" when dimension is \"storefront\")'\n ),\n});\n\nexport const discoverDimensionsSchema = z.object({\n assetId: z.string().uuid().describe('App UUID'),\n dimension: z\n .string()\n .optional()\n .describe(\n 'If provided, returns the available values for this dimension (e.g., countries for \"storefront\")'\n ),\n});\n\n// =============================================================================\n// METRIC DISPLAY INFO\n// =============================================================================\n\n// Human-readable names and categories for common metrics\nconst METRIC_INFO: Record<\n string,\n { displayName: string; category: string; type: string }\n> = {\n proceeds: {\n displayName: 'Net Revenue (after store cut)',\n category: 'Revenue',\n type: 'currency',\n },\n total_revenue: {\n displayName: 'Gross Revenue',\n category: 'Revenue',\n type: 'currency',\n },\n total_downloads: {\n displayName: 'Total Downloads',\n category: 'Downloads',\n type: 'count',\n },\n units: {\n displayName: 'First-time Downloads',\n category: 'Downloads',\n type: 'count',\n },\n redownloads: {\n displayName: 'Re-downloads',\n category: 'Downloads',\n type: 'count',\n },\n page_views: {\n displayName: 'App Store Page Views',\n category: 'Downloads',\n type: 'count',\n },\n impressions: {\n displayName: 'App Store Impressions',\n category: 'Downloads',\n type: 'count',\n },\n sessions: {\n displayName: 'App Sessions',\n category: 'Engagement',\n type: 'count',\n },\n active_devices: {\n displayName: 'Active Devices',\n category: 'Engagement',\n type: 'count',\n },\n crashes: { displayName: 'Crashes', category: 'Engagement', type: 'count' },\n paying_users: {\n displayName: 'Paying Users',\n category: 'Engagement',\n type: 'count',\n },\n active_subs: {\n displayName: 'Active Subscriptions',\n category: 'Subscriptions',\n type: 'count',\n },\n active_trials: {\n displayName: 'Active Trials',\n category: 'Subscriptions',\n type: 'count',\n },\n new_trials: {\n displayName: 'New Trials',\n category: 'Subscriptions',\n type: 'count',\n },\n trial_conversion_rate: {\n displayName: 'Trial Conversion Rate',\n category: 'Subscriptions',\n type: 'percentage',\n },\n subscription_retention_rate: {\n displayName: 'Subscription Retention Rate',\n category: 'Subscriptions',\n type: 'percentage',\n },\n products_sold: {\n displayName: 'Products Sold (IAP)',\n category: 'Revenue',\n type: 'count',\n },\n ad_spend: { displayName: 'Ad Spend', category: 'Ads', type: 'currency' },\n ad_impressions: {\n displayName: 'Ad Impressions',\n category: 'Ads',\n type: 'count',\n },\n ad_taps: { displayName: 'Ad Taps/Clicks', category: 'Ads', type: 'count' },\n ad_installs: {\n displayName: 'Ad-attributed Installs',\n category: 'Ads',\n type: 'count',\n },\n ad_conversions: {\n displayName: 'Ad Conversions',\n category: 'Ads',\n type: 'count',\n },\n};\n\n// Dimension display names\nconst DIMENSION_INFO: Record<string, string> = {\n storefront: 'Country',\n region: 'Region',\n platform: 'Platform (device type)',\n source: 'Source',\n appVersion: 'App Version',\n purchase: 'Product',\n appReferrer: 'App Referrer',\n domainReferrer: 'Domain Referrer',\n subscription_state: 'Subscription Type',\n duration: 'Duration',\n revenueShare: 'Revenue Share',\n campaign: 'Campaign',\n};\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\nexport async function discoverMetrics(\n input: z.input<typeof discoverMetricsSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get<MetricAvailabilityResponse>(\n `/api/assets/${input.assetId}/metrics/availability`\n );\n const availableMetrics = response.data?.availableMetrics ?? [];\n const metricGroups = response.data?.metricGroups ?? {};\n\n // Enrich with display names and categories\n const enriched = availableMetrics.map((metricName: string) => {\n const info = METRIC_INFO[metricName];\n return {\n name: metricName,\n displayName: info?.displayName || metricName,\n category: info?.category || 'Other',\n type: info?.type || 'count',\n };\n });\n\n // Group by category\n const byCategory: Record<string, EnrichedMetric[]> = {};\n for (const m of enriched) {\n (byCategory[m.category] ??= []).push(m);\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n assetId: input.assetId,\n totalAvailable: availableMetrics.length,\n metricsByCategory: byCategory,\n dataGroups: metricGroups,\n tip: 'Use the metric \"name\" field in get_metrics. You can query multiple metrics at once.',\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [{ type: 'text' as const, text: formatError(error) }],\n isError: true,\n };\n }\n}\n\nexport async function getMetrics(\n input: z.input<typeof getMetricsSchema>,\n client: FloadApiClient\n) {\n try {\n // Direct callers may omit defaulted fields; the MCP server has parsed them.\n const granularity = input.granularity ?? 'daily';\n // Default date range: last 30 days\n const endDate = input.endDate || new Date().toISOString().split('T')[0]!;\n const startDate =\n input.startDate ||\n (() => {\n const d = new Date();\n d.setDate(d.getDate() - 30);\n return d.toISOString().split('T')[0]!;\n })();\n\n const params: Record<string, string> = {\n metrics: input.metrics.join(','),\n fromDate: startDate,\n toDate: endDate,\n granularity,\n };\n\n // The API rolls every value up into `breakdownTotals` from an uncapped\n // read; `timeseries` stays capped to the top values a day, so an agent's\n // context is not flooded with every country for every day (FLO-2487).\n if (input.dimension) params.dimension = input.dimension;\n if (input.dimensionFilter && input.dimension) {\n params[`filter.${input.dimension}`] = input.dimensionFilter;\n }\n\n const path = `/api/assets/${input.assetId}/metrics/timeseries`;\n const response = await client.get<MetricsTimeseriesResponse>(path, params);\n // The summary is the value over the requested days. A weekly or monthly\n // read leaves out its still-open last bucket (the current week or month,\n // when the window ends today), so the summary comes from a daily read,\n // which leaves out only days whose data is not complete yet (FLO-1826).\n const summaryResponse =\n input.granularity === 'daily'\n ? response\n : await client.get<MetricsTimeseriesResponse>(path, {\n ...params,\n granularity: 'daily',\n });\n\n // The API returns { data: { metricName: [{date, value}] }, changes: {...}, meta: {...} }\n const data = response.data ?? {};\n const changes = summaryResponse.changes ?? {};\n const meta = response.meta ?? {};\n\n // The period value comes from the API, which aggregates each metric by\n // its class; summing or averaging the daily points here would be wrong for\n // levels and ratios (FLO-1826).\n const summaries: Record<string, MetricSummary> = {};\n for (const [metricName, points] of Object.entries(data)) {\n summaries[metricName] = summarize(points, changes[metricName]);\n }\n\n const info = METRIC_INFO;\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n assetId: input.assetId,\n dateRange: { start: startDate, end: endDate },\n granularity,\n dimension: input.dimension || null,\n metrics: Object.keys(data).map(name => ({\n name,\n displayName: info[name]?.displayName || name,\n type: info[name]?.type || 'count',\n summary: summaries[name],\n change: changes[name] || null,\n ...(input.dimension && {\n breakdown: summaryResponse.breakdownTotals?.[name] ?? null,\n }),\n })),\n timeseries: data,\n meta,\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [{ type: 'text' as const, text: formatError(error) }],\n isError: true,\n };\n }\n}\n\nexport async function discoverDimensions(\n input: z.input<typeof discoverDimensionsSchema>,\n client: FloadApiClient\n) {\n try {\n if (input.dimension) {\n // Get values for a specific dimension\n const response = await client.get<DimensionValuesResponse>(\n `/api/assets/${input.assetId}/metrics/dimensions/${input.dimension}/values`\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n assetId: input.assetId,\n dimension: input.dimension,\n displayName: DIMENSION_INFO[input.dimension] || input.dimension,\n values: response.data ?? response,\n }),\n },\n ],\n };\n }\n\n // Get available dimensions. The route returns [{id, label}] objects.\n const response = await client.get<{\n data?: Array<string | { id?: string; label?: string }>;\n }>(`/api/assets/${input.assetId}/metrics/dimensions`);\n const dimensions = Array.isArray(response.data) ? response.data : [];\n\n const enriched = dimensions.map(dim => {\n if (typeof dim === 'string') {\n return { name: dim, displayName: DIMENSION_INFO[dim] || dim };\n }\n const id = dim.id ?? '';\n return { name: id, displayName: dim.label ?? DIMENSION_INFO[id] ?? id };\n });\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n assetId: input.assetId,\n dimensions: enriched,\n tip: 'Use dimension name in get_metrics \"dimension\" param. Use discover_dimensions with a specific dimension to see available values.',\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [{ type: 'text' as const, text: formatError(error) }],\n isError: true,\n };\n }\n}\n", "/**\n * FLO-2549: get_download_impact \u2014 did Fload's listing changes move the\n * downloads they can affect? The same reader as the app metrics chart, the\n * monthly report, the audit and the remote MCP's getDownloadImpact\n * (`GET /api/assets/:assetId/metrics/download-impact`).\n */\n\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\nconst Day = z\n .string()\n .regex(/^\\d{4}-\\d{2}-\\d{2}$/)\n .optional();\n\nexport const getDownloadImpactSchema = z.object({\n assetId: z.string().uuid().describe('App UUID (App Store apps)'),\n from: Day.describe(\n 'First day drawn (YYYY-MM-DD); default 20 weeks before `to`'\n ),\n to: Day.describe(\n 'Last day drawn (YYYY-MM-DD); default the newest day with data'\n ),\n beforeFrom: Day.describe(\n 'Start of the \"before\" window compared (needs beforeTo; all windows within 400 days of each other)'\n ),\n beforeTo: Day.describe('End of the \"before\" window compared'),\n afterFrom: Day.describe(\n 'Start of the \"after\" window compared (needs afterTo)'\n ),\n afterTo: Day.describe('End of the \"after\" window compared'),\n country: z\n .string()\n .regex(/^[a-zA-Z]{2}$/)\n .optional()\n .describe(\n 'One storefront, two-letter code (e.g. \"us\"): narrows countries and keywords'\n ),\n includeDays: z\n .boolean()\n .optional()\n .describe('Also return every day (long). Weeks carry the same downloads.'),\n});\n\ninterface DownloadImpactResponse {\n days?: unknown;\n lastYearDays?: unknown;\n [key: string]: unknown;\n}\n\nexport async function getDownloadImpact(\n input: z.input<typeof getDownloadImpactSchema>,\n client: FloadApiClient\n) {\n try {\n const { assetId, includeDays, ...query } = input;\n const impact = await client.get<DownloadImpactResponse>(\n `/api/assets/${assetId}/metrics/download-impact`,\n query\n );\n const { days, lastYearDays, ...rest } = impact;\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(\n includeDays ? { ...rest, days, lastYearDays } : rest\n ),\n },\n ],\n };\n } catch (error) {\n return {\n content: [{ type: 'text' as const, text: formatError(error) }],\n isError: true,\n };\n }\n}\n", "/**\n * Agent tools for MCP\n * Tools: list_agents, get_agent_details, get_agent_run_history, trigger_agent_run, pause_agent, resume_agent, get_agent_activity\n */\n\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\ninterface AgentsResponse {\n data?: unknown[];\n agents?: unknown[];\n}\n\ninterface DataEnvelope {\n data?: unknown;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\n// =============================================================================\n// CONSTANTS\n// =============================================================================\n\n// Keep in step with the API's live agent catalog. Advertising a retired type\n// here is worse than omitting it: /api/agents/by-type/<type> 400s, the tool\n// swallows that into \"no <type> agent is provisioned \u2026 activate it from the\n// Agents page\", and the user is told to do something impossible.\nconst AGENT_TYPES = ['review', 'aso'] as const;\n\ntype AgentType = (typeof AGENT_TYPES)[number];\n\nconst AGENT_DESCRIPTIONS: Record<AgentType, string> = {\n review:\n 'AI-powered review management \u2014 drafts and sends replies to app store reviews',\n aso: 'App Store Optimization \u2014 listing optimization suggestions for better visibility',\n};\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const listAgentsSchema = z.object({});\n\nexport const getAgentDetailsSchema = z.object({\n agentType: z\n .enum(AGENT_TYPES)\n .describe('The type of agent to get details for'),\n assetId: z\n .string()\n .uuid()\n .optional()\n .describe('App UUID to get agent config for (when agent is per-asset)'),\n});\n\nexport const getAgentRunHistorySchema = z.object({\n agentType: z\n .enum(AGENT_TYPES)\n .describe('The type of agent to get run history for'),\n assetId: z.string().uuid().optional().describe('App UUID to filter runs'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .default(20)\n .describe('Maximum number of runs to return'),\n});\n\nexport const triggerAgentRunSchema = z.object({\n agentId: z\n .string()\n .describe('The agent ID to trigger a run for (the `id` from list_agents)'),\n assetId: z\n .string()\n .uuid()\n .optional()\n .describe('Optional app UUID to run the agent against'),\n});\n\nexport const pauseAgentSchema = z.object({\n agentId: z\n .string()\n .describe('The agent ID to pause (the `id` from list_agents)'),\n});\n\nexport const resumeAgentSchema = z.object({\n agentId: z\n .string()\n .describe('The agent ID to resume (the `id` from list_agents)'),\n});\n\nexport const getAgentActivitySchema = z.object({\n agentId: z\n .string()\n .describe('The agent ID to get activity for (the `id` from list_agents)'),\n});\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * List all available agent types and their status\n */\nexport async function listAgents(\n _input: z.input<typeof listAgentsSchema>,\n client: FloadApiClient\n) {\n try {\n // Try to get agent info from the API\n let apiAgents: unknown[] | null = null;\n try {\n const response = await client.get<AgentsResponse | unknown[]>(\n '/api/agents'\n );\n apiAgents = Array.isArray(response)\n ? response\n : (response.data ?? response.agents ?? null);\n } catch {\n // API route may not exist yet \u2014 fall back to static list\n }\n\n if (apiAgents && Array.isArray(apiAgents)) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n totalAgents: apiAgents.length,\n agents: apiAgents,\n }),\n },\n ],\n };\n }\n\n // Fallback: return static agent list with descriptions\n const agents = AGENT_TYPES.map(type => ({\n type,\n description: AGENT_DESCRIPTIONS[type],\n available: true,\n }));\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n totalAgents: agents.length,\n agents,\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Get details about a specific agent type\n */\nexport async function getAgentDetails(\n input: z.input<typeof getAgentDetailsSchema>,\n client: FloadApiClient\n) {\n try {\n // The per-type endpoint is /api/agents/by-type/:type \u2014 it returns the\n // agent row + its 10 most recent runs, or a nullable agent when that\n // type/scope has not been activated. (Passing type into /:agentId 404s.)\n try {\n const params: Record<string, string | undefined> = {};\n if (input.assetId) params.assetId = input.assetId;\n const response = await client.get<{\n agent?: Record<string, unknown>;\n recentRuns?: unknown[];\n }>(`/api/agents/by-type/${input.agentType}`, params);\n if (response.agent) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n agent: response.agent,\n recentRuns: response.recentRuns ?? [],\n }),\n },\n ],\n };\n }\n } catch {\n // Agent type not provisioned for this org \u2014 fall through to basic info.\n }\n\n const response: Record<string, unknown> = {\n type: input.agentType,\n description: AGENT_DESCRIPTIONS[input.agentType],\n message: `No ${input.agentType} agent is provisioned for this organization yet. Activate it from the Agents page or with trigger_agent_run once created.`,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Get agent run history\n */\nexport async function getAgentRunHistory(\n input: z.input<typeof getAgentRunHistorySchema>,\n client: FloadApiClient\n) {\n try {\n // Runs are keyed by agent id, not type \u2014 resolve the org's agent of this\n // type first without changing activation state, then fetch run history.\n let agentId: string | undefined;\n try {\n const byTypeParams: Record<string, string | undefined> = {};\n if (input.assetId) byTypeParams.assetId = input.assetId;\n const byType = await client.get<{ agent?: { id?: string } }>(\n `/api/agents/by-type/${input.agentType}`,\n byTypeParams\n );\n agentId = byType.agent?.id;\n } catch {\n // No agent of this type \u2014 report that instead of an empty list.\n }\n\n if (!agentId) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n agentType: input.agentType,\n runs: [],\n message: `No ${input.agentType} agent is provisioned for this organization yet, so there is no run history.`,\n }),\n },\n ],\n };\n }\n\n const response = await client.get<DataEnvelope>(\n `/api/agents/${agentId}/runs`,\n { limit: input.limit }\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n agentType: input.agentType,\n agentId,\n ...asRecord(response.data ?? response),\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Trigger a manual agent run\n */\nexport async function triggerAgentRun(\n input: z.input<typeof triggerAgentRunSchema>,\n client: FloadApiClient\n) {\n try {\n // The route merges body.triggerContext into the run's context; a bare\n // assetId at the top level is ignored.\n const body = input.assetId\n ? { triggerContext: { assetId: input.assetId } }\n : {};\n\n const response = await client.post<DataEnvelope>(\n `/api/agents/${input.agentId}/run`,\n body\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response.data ?? response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Pause an agent\n */\nexport async function pauseAgent(\n input: z.input<typeof pauseAgentSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.post<DataEnvelope>(\n `/api/agents/${input.agentId}/pause`\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response.data ?? response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Resume a paused agent\n */\nexport async function resumeAgent(\n input: z.input<typeof resumeAgentSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.post<DataEnvelope>(\n `/api/agents/${input.agentId}/resume`\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response.data ?? response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Get recent activity log for an agent\n */\nexport async function getAgentActivity(\n input: z.input<typeof getAgentActivitySchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get<DataEnvelope>(\n `/api/agents/${input.agentId}/activity`\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response.data ?? response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n", "/**\n * Ads performance tools for MCP\n * Tools: get_ads_performance\n */\n\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\ninterface CampaignRecord {\n id: string;\n assetId?: string | null;\n assetName?: string | null;\n platformCampaignId?: string | null;\n name?: string | null;\n status?: string | null;\n objective?: string | null;\n platform?: string | null;\n linkSource?: string | null;\n linkedAt?: string | null;\n totalSpend?: number | null;\n totalImpressions?: number | null;\n totalTaps?: number | null;\n totalInstalls?: number | null;\n avgCPI?: number | null;\n avgTTR?: number | null;\n avgCVR?: number | null;\n}\n\ninterface CampaignsResponse {\n data?: CampaignRecord[];\n campaigns?: CampaignRecord[];\n /** The metrics read failed: every metric is null (unknown), never 0. */\n metricsUnavailable?: boolean;\n}\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const getAdsPerformanceSchema = z.object({\n assetId: z.string().uuid().optional().describe('Filter by app UUID'),\n platform: z\n .enum(['apple_search_ads', 'google_ads', 'meta_ads', 'tiktok_ads'])\n .optional()\n .describe('Filter by ad platform'),\n fromDate: z\n .string()\n .optional()\n .describe('Start date for performance data (YYYY-MM-DD)'),\n toDate: z\n .string()\n .optional()\n .describe('End date for performance data (YYYY-MM-DD)'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .default(50)\n .describe('Maximum number of campaigns to return'),\n});\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * Get ad campaign performance data\n */\nexport async function getAdsPerformance(\n input: z.input<typeof getAdsPerformanceSchema>,\n client: FloadApiClient\n) {\n try {\n // The campaigns route reads assetId + from/to; platform and limit\n // are not supported server-side, so they're applied client-side below.\n const params: Record<string, string | number | undefined> = {};\n\n if (input.assetId) params.assetId = input.assetId;\n if (input.fromDate) params.from = input.fromDate;\n if (input.toDate) params.to = input.toDate;\n\n const response = await client.get<CampaignsResponse>(\n '/api/ads/campaigns',\n params\n );\n let campaigns = response.data ?? response.campaigns ?? [];\n if (input.platform) {\n campaigns = campaigns.filter(c => c.platform === input.platform);\n }\n campaigns = campaigns.slice(0, input.limit);\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n total: campaigns.length,\n // The server couldn't read the metrics: null spend is unknown,\n // never \"no spend\".\n ...(response.metricsUnavailable\n ? {\n metricsUnavailable: true,\n note: 'The ads metrics could not be read right now, so spend, impressions, taps and installs are unknown (null), not zero. Try again later.',\n }\n : {}),\n campaigns: campaigns.map(campaign => ({\n id: campaign.id,\n assetId: campaign.assetId,\n assetName: campaign.assetName,\n platformCampaignId: campaign.platformCampaignId,\n name: campaign.name,\n status: campaign.status,\n objective: campaign.objective,\n platform: campaign.platform,\n linkSource: campaign.linkSource,\n linkedAt: campaign.linkedAt,\n totalSpend: campaign.totalSpend ?? null,\n totalImpressions: campaign.totalImpressions ?? null,\n totalTaps: campaign.totalTaps ?? null,\n totalInstalls: campaign.totalInstalls ?? null,\n avgCPI: campaign.avgCPI ?? null,\n avgTTR: campaign.avgTTR ?? null,\n avgCVR: campaign.avgCVR ?? null,\n })),\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n", "/**\n * Dashboard tools for MCP\n * Tools: get_dashboard_overview\n */\n\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\ninterface DashboardOverviewResponse {\n data?: unknown;\n}\n\ninterface SidebarAsset {\n id: string;\n name: string;\n bundleId: string;\n appleAppId?: string | null;\n googleAppId?: string | null;\n currentValuation?: string | number | null;\n rating?: string | number | null;\n ratingCount?: number | null;\n category?: string | null;\n iconUrl?: string | null;\n}\n\ninterface SidebarAssetsResponse {\n data?: SidebarAsset[];\n}\n\nfunction parseDashboardNumber(\n value: string | number | null | undefined\n): number | null {\n if (value === null || value === undefined || value === '') return null;\n const parsed = typeof value === 'number' ? value : Number.parseFloat(value);\n return Number.isFinite(parsed) ? parsed : null;\n}\n\nfunction getSidebarAssets(\n response: SidebarAssetsResponse | SidebarAsset[] | null\n): SidebarAsset[] {\n if (!response) return [];\n if (Array.isArray(response)) return response;\n return response.data ?? [];\n}\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const getDashboardOverviewSchema = z.object({});\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * Get aggregated dashboard overview for the organization\n */\nexport async function getDashboardOverview(\n _input: z.input<typeof getDashboardOverviewSchema>,\n client: FloadApiClient\n) {\n try {\n // Fetch overview metrics and sidebar assets in parallel\n const overviewPromise: Promise<DashboardOverviewResponse | null> = client\n .get<DashboardOverviewResponse>('/api/dashboard/overview-metrics')\n .catch(() => null);\n const sidebarPromise: Promise<\n SidebarAssetsResponse | SidebarAsset[] | null\n > = client\n .get<SidebarAssetsResponse | SidebarAsset[]>(\n '/api/dashboard/sidebar-assets'\n )\n .catch(() => null);\n\n const [overviewResponse, sidebarResponse] = await Promise.all([\n overviewPromise,\n sidebarPromise,\n ]);\n\n const overview = overviewResponse?.data ?? overviewResponse ?? {};\n // Build the dashboard response\n const apps = getSidebarAssets(sidebarResponse);\n\n const totalValuation = apps.reduce((sum, app) => {\n return sum + (parseDashboardNumber(app.currentValuation) ?? 0);\n }, 0);\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n portfolio: {\n totalApps: apps.length,\n totalValuation: totalValuation > 0 ? totalValuation : null,\n apps: apps.map(app => ({\n id: app.id,\n name: app.name,\n bundleId: app.bundleId,\n platform: app.appleAppId\n ? 'ios'\n : app.googleAppId\n ? 'android'\n : 'unknown',\n currentValuation: parseDashboardNumber(app.currentValuation),\n rating: parseDashboardNumber(app.rating),\n ratingCount: app.ratingCount ?? null,\n category: app.category ?? null,\n iconUrl: app.iconUrl ?? null,\n })),\n },\n overview,\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n", "/**\n * Action tools for MCP\n * Tools: list_pending_actions, approve_action, reject_action, check_action_now,\n * rename_custom_page_action\n *\n * FLO-1595: inbox work is an Actions item (the inbox's one read model), so\n * these tools read `GET /api/actions/items` and act through\n * `POST /api/actions/commands`, the same commands the web inbox sends. A\n * notice has nothing to approve: its approve is `acknowledge` and its reject\n * `dismiss`, as the inbox's buttons mean on an informational card.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\nimport { publicMcpErrorMessage } from '../public-errors.js';\n\ninterface ActionItemSummary {\n id: string;\n kind: string;\n status: string;\n subjectKey?: string;\n assetId?: string | null;\n currentRevisionId: string | null;\n allowedCommands?: string[];\n /** FLO-2633: the request that proposed it with others (one inbox card). */\n proposalBatch?: string | null;\n}\n\ninterface ActionItemListResponse {\n items?: unknown[];\n nextCursor?: string | null;\n}\n\ninterface ActionItemDetailResponse {\n item?: ActionItemSummary;\n}\n\ninterface ActionCommandResponse {\n results?: Array<{\n itemId: string;\n result: string;\n httpStatus?: number;\n error?: string;\n item?: unknown;\n /**\n * FLO-2564: a refused change's refusal; `check` names the check that\n * said no, in plain words.\n */\n policyRefusal?: { kind: string; check?: string; message: string };\n /**\n * FLO-2575: the store already showed the change, so nothing was\n * approved or sent and the item is done.\n */\n alreadyLive?: boolean;\n }>;\n /** A refusal of the whole request (403 and the like) says why here. */\n message?: string;\n}\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const listPendingActionsSchema = z.object({\n assetId: z.string().uuid().optional().describe('Filter by app UUID'),\n view: z\n .enum(['open', 'queued'])\n .default('open')\n .describe(\n '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).'\n ),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .default(50)\n .describe('Maximum number of actions to return'),\n});\n\nexport const approveActionSchema = z.object({\n actionId: z\n .string()\n .describe('The inbox item ID to approve (from list_pending_actions)'),\n wholeGroup: z\n .boolean()\n .optional()\n .describe(\n \"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.\"\n ),\n});\n\nexport const rejectActionSchema = z.object({\n actionId: z\n .string()\n .describe('The inbox item ID to reject (from list_pending_actions)'),\n reason: z\n .string()\n .trim()\n .min(1)\n .max(1000)\n .optional()\n .describe(\n \"Why, in the user's words. Kept with the rejection so the agents do not propose the same thing again.\"\n ),\n});\n\n/** FLO-2324: an item Fload is reading back from the store (status verifying). */\nexport const checkActionNowSchema = z.object({\n actionId: z\n .string()\n .describe(\n 'The inbox item ID to check now (from list_pending_actions with view \"queued\", or an approve_action result; its commands include check_now)'\n ),\n});\n\n/** FLO-2423: a custom product page create App Store Connect refused for its name. */\nexport const renameCustomPageActionSchema = z.object({\n actionId: z\n .string()\n .describe(\n '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)'\n ),\n name: z\n .string()\n .trim()\n .min(1)\n .max(100)\n .describe(\n 'The new page name: at most 100 characters (UTF-16 units), not its current name, not a page the app already has'\n ),\n});\n\ntype Intent = 'approve' | 'reject';\n\n/** The command an approve / reject is for an item of this kind. */\nfunction commandFor(kind: string, intent: Intent): string {\n if (kind === 'notice')\n return intent === 'approve' ? 'acknowledge' : 'dismiss';\n return intent;\n}\n\nfunction toolText(payload: unknown, isError = false) {\n return {\n content: [{ type: 'text' as const, text: formatAsJson(payload) }],\n ...(isError ? { isError: true } : {}),\n };\n}\n\nfunction toolError(error: unknown) {\n return {\n content: [{ type: 'text' as const, text: formatError(error) }],\n isError: true,\n };\n}\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * List the inbox items waiting on the user: to approve, or for them to act\n * on (the inbox's Open view), newest last.\n */\nexport async function listPendingActions(\n input: z.input<typeof listPendingActionsSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get<ActionItemListResponse>(\n '/api/actions/items',\n { view: input.view ?? 'open', assetId: input.assetId, limit: input.limit }\n );\n const actions = response.items ?? [];\n return toolText({\n total: actions.length,\n actions,\n hasMore: Boolean(response.nextCursor),\n });\n } catch (error) {\n return toolError(error);\n }\n}\n\n/** Run one approve or reject for an item, as the inbox would. */\nasync function commandItem(\n client: FloadApiClient,\n itemId: string,\n intent: Intent,\n reason?: string\n) {\n const detail = await client.get<ActionItemDetailResponse>(\n `/api/actions/items/${encodeURIComponent(itemId)}`\n );\n const item = detail.item;\n if (!item) throw new Error('Action not found');\n const command = commandFor(item.kind, intent);\n // A single target answers with its own status (409 not allowed, 422 not\n // writable, \u2026) and says why in its result: read it rather than throw.\n const answer = await client.postForAnswer<ActionCommandResponse>(\n '/api/actions/commands',\n {\n command,\n idempotencyKey: `mcp:${command}:${item.id}:${randomUUID()}`,\n targets: [\n {\n itemId: item.id,\n ...(command === 'approve' && item.currentRevisionId\n ? { revisionId: item.currentRevisionId }\n : {}),\n },\n ],\n ...(command === 'reject' && reason ? { reason } : {}),\n }\n );\n const result = answer.body?.results?.[0];\n if (!result)\n throw new Error(\n answer.ok\n ? 'Fload returned no result for the command.'\n : 'Fload rejected the request. Please check access and try again.'\n );\n return {\n command,\n result: {\n ...result,\n error: result.error\n ? publicMcpErrorMessage(\n result.error,\n 'Fload could not apply this change.'\n )\n : undefined,\n },\n };\n}\n\n/** What an approve did, in the user's words. */\nfunction approveMessage(\n command: string,\n applied: boolean,\n result: CommandResult | undefined\n): string {\n if (!applied) return refusedMessage(result);\n if (command === 'acknowledge') return 'Acknowledged.';\n // FLO-2575: nothing was approved or sent.\n if (result?.alreadyLive)\n return 'Already live: the store already shows this change, so nothing was sent. The item is done.';\n return 'Approved. Fload delivers it after a short undo window; the inbox shows where it is.';\n}\n\n/**\n * Why an approve did not go through. FLO-2564: a refusal leads with the check\n * that said no, as the server names it (\"Stopped by the language check: \u2026\").\n */\nfunction refusedMessage(result: CommandResult | undefined): string {\n const said = result?.error ?? 'The approval could not be recorded.';\n const check = result?.policyRefusal?.check;\n return check ? `Stopped by the ${check}: ${said}` : said;\n}\n\n/**\n * Approve an inbox item (a notice is acknowledged). Approving a review reply\n * publishes it to the store after a short undo window.\n */\nexport async function approveAction(\n input: z.input<typeof approveActionSchema>,\n client: FloadApiClient\n) {\n try {\n if (input.wholeGroup) {\n // An item in no card of several approves as it would alone.\n const grouped = await approveGroup(client, input.actionId);\n if (grouped) return grouped;\n }\n const { command, result } = await commandItem(\n client,\n input.actionId,\n 'approve'\n );\n const applied =\n result?.result === 'applied' || result?.result === 'replayed';\n return toolText(\n {\n success: applied,\n actionId: input.actionId,\n command,\n result: result?.result ?? 'unknown',\n ...(result?.error ? { error: result.error } : {}),\n message: approveMessage(command, applied, result),\n item: result?.item,\n },\n !applied\n );\n } catch (error) {\n return toolError(error);\n }\n}\n\n/**\n * The items waiting in this item's card (its proposal batch), it first.\n * FLO-2668: only the languages still waiting on a decision: one already\n * approved is on its way to the store, no longer in the card.\n */\nasync function groupOf(\n client: FloadApiClient,\n item: ActionItemSummary\n): Promise<ActionItemSummary[]> {\n if (!item.proposalBatch || item.status !== 'needs_approval') return [item];\n const isSibling = (other: unknown): other is ActionItemSummary =>\n typeof other === 'object' &&\n other !== null &&\n (other as ActionItemSummary).status === 'needs_approval' &&\n (other as ActionItemSummary).proposalBatch === item.proposalBatch &&\n (other as ActionItemSummary).assetId === item.assetId &&\n (other as ActionItemSummary).id !== item.id;\n // Every page of the app's open work: a card's languages may sit past the\n // first page behind other work (review of #2514).\n const siblings: ActionItemSummary[] = [];\n let cursor: string | null | undefined;\n do {\n const response: ActionItemListResponse =\n await client.get<ActionItemListResponse>('/api/actions/items', {\n view: 'open',\n limit: 100,\n ...(item.assetId ? { assetId: item.assetId } : {}),\n ...(cursor ? { cursor } : {}),\n });\n siblings.push(...(response.items ?? []).filter(isSibling));\n cursor = response.nextCursor;\n } while (cursor);\n return [item, ...siblings];\n}\n\n/**\n * FLO-2633: approve every language of an item's card in ONE command, as\n * the inbox's Approve does; a language that cannot be approved now (stopped,\n * being rewritten) is left as it is and listed.\n */\nasync function approveGroup(client: FloadApiClient, actionId: string) {\n const detail = await client.get<ActionItemDetailResponse>(\n `/api/actions/items/${encodeURIComponent(actionId)}`\n );\n if (!detail.item) throw new Error('Action not found');\n const group = await groupOf(client, detail.item);\n if (group.length <= 1) return null;\n const approvable = group.filter(item =>\n item.allowedCommands?.includes('approve')\n );\n const skipped = group\n .filter(item => !approvable.includes(item))\n .map(item => item.id);\n if (approvable.length === 0)\n return toolText(\n {\n success: false,\n actionId,\n skipped,\n message: 'Nothing in this card can be approved right now.',\n },\n true\n );\n const answer = await client.postForAnswer<ActionCommandResponse>(\n '/api/actions/commands',\n {\n command: 'approve',\n idempotencyKey: `mcp:approve-group:${actionId}:${randomUUID()}`,\n targets: approvable.map(item => ({\n itemId: item.id,\n ...(item.currentRevisionId\n ? { revisionId: item.currentRevisionId }\n : {}),\n })),\n }\n );\n const results = (answer.body?.results ?? []).map(result => ({\n itemId: result.itemId,\n result: result.result,\n ...(result.error\n ? {\n error: publicMcpErrorMessage(\n result.error,\n 'Fload could not apply this change.'\n ),\n }\n : {}),\n }));\n const approved = results.filter(\n r => r.result === 'applied' || r.result === 'replayed'\n ).length;\n return toolText(\n {\n success: approved > 0,\n actionId,\n approved,\n results,\n ...(skipped.length ? { skipped } : {}),\n message:\n approved > 0\n ? `Approved ${approved} of ${group.length}. Fload delivers them after a short undo window; the inbox shows where each is.`\n : 'The approval could not be recorded.',\n },\n approved === 0\n );\n}\n\n/** Reject an inbox item (a notice is dismissed). Nothing is sent. */\nexport async function rejectAction(\n input: z.input<typeof rejectActionSchema>,\n client: FloadApiClient\n) {\n try {\n const { command, result } = await commandItem(\n client,\n input.actionId,\n 'reject',\n input.reason\n );\n const applied =\n result?.result === 'applied' || result?.result === 'replayed';\n return toolText(\n {\n success: applied,\n actionId: input.actionId,\n command,\n result: result?.result ?? 'unknown',\n ...(result?.error ? { error: result.error } : {}),\n message: applied\n ? command === 'dismiss'\n ? 'Dismissed.'\n : 'Rejected. Nothing was sent.'\n : (result?.error ?? 'The rejection could not be recorded.'),\n item: result?.item,\n },\n !applied\n );\n } catch (error) {\n return toolError(error);\n }\n}\n\n/**\n * FLO-2324: \"Check now\" on an item Fload is reading back from the store: it\n * reads the store again at once instead of at its next scheduled check.\n * Nothing is written to the store.\n */\nexport async function checkActionNow(\n input: z.input<typeof checkActionNowSchema>,\n client: FloadApiClient\n) {\n try {\n const answer = await client.postForAnswer<ActionCommandResponse>(\n '/api/actions/commands',\n {\n command: 'check_now',\n idempotencyKey: `mcp:check_now:${input.actionId}:${randomUUID()}`,\n targets: [{ itemId: input.actionId }],\n }\n );\n const result = answer.body?.results?.[0];\n const applied =\n result?.result === 'applied' || result?.result === 'replayed';\n const error = result?.error\n ? publicMcpErrorMessage(result.error, 'Fload could not check it now.')\n : undefined;\n return toolText(\n {\n success: applied,\n actionId: input.actionId,\n command: 'check_now',\n result: result?.result ?? 'unknown',\n ...(error ? { error } : {}),\n message: applied\n ? 'Fload is checking the store now; the item updates as soon as the store shows the change.'\n : (error ??\n (answer.ok\n ? 'Fload returned no result for the command.'\n : 'Fload rejected the request. Please check access and try again.')),\n item: result?.item,\n },\n !applied\n );\n } catch (error) {\n return toolError(error);\n }\n}\n\n// =============================================================================\n// FLO-2423: rename a custom product page create, and approve it again\n// =============================================================================\n\ntype CommandResult = NonNullable<ActionCommandResponse['results']>[number];\n\nconst applied = (result: CommandResult | undefined) =>\n result?.result === 'applied' || result?.result === 'replayed';\n\n/** One command for one item, answered with its result or the refusal's words. */\nasync function sendItemCommand(\n client: FloadApiClient,\n body: { command: string; itemId: string; revisionId: string | null } & Record<\n string,\n unknown\n >\n): Promise<{ result?: CommandResult; refusal: string | null }> {\n const { command, itemId, revisionId, ...extra } = body;\n const answer = await client.postForAnswer<ActionCommandResponse>(\n '/api/actions/commands',\n {\n command,\n idempotencyKey: `mcp:${command}:${itemId}:${randomUUID()}`,\n targets: [{ itemId, ...(revisionId ? { revisionId } : {}) }],\n ...extra,\n }\n );\n const result = answer.body?.results?.[0];\n if (applied(result)) return { result, refusal: null };\n const said = result?.error ?? answer.body?.message;\n return {\n result,\n refusal: publicMcpErrorMessage(\n said,\n answer.ok\n ? 'Fload returned no result for the command.'\n : 'Fload rejected the request. Please check access and try again.'\n ),\n };\n}\n\nfunction renameAnswer(\n input: z.input<typeof renameCustomPageActionSchema>,\n outcome: {\n renamed: boolean;\n approved: boolean;\n message: string;\n next?: string;\n },\n item?: unknown\n) {\n const success = outcome.renamed && outcome.approved;\n return toolText(\n {\n success,\n actionId: input.actionId,\n ...outcome,\n ...(item === undefined ? {} : { item }),\n },\n !success\n );\n}\n\n/**\n * Rename a custom product page create (the inbox's \"Create with this name\"):\n * `edit` with the new page name on the revision the item shows, then\n * `approve` on the revision the rename returned. Fload's engine then creates\n * the page under the new name after the usual undo window. The tool checks\n * no login of its own: whatever the server's edit and approve refuse is\n * answered as the server said it.\n */\nexport async function renameCustomPageAction(\n input: z.input<typeof renameCustomPageActionSchema>,\n client: FloadApiClient\n) {\n try {\n const name = input.name.trim();\n const detail = await client.get<ActionItemDetailResponse>(\n `/api/actions/items/${encodeURIComponent(input.actionId)}`\n );\n const item = detail.item;\n if (\n !item ||\n item.kind !== 'asc_custom_product_page' ||\n !item.subjectKey?.startsWith('asc-cpp:')\n )\n return renameAnswer(input, {\n renamed: false,\n approved: false,\n message: 'This item is not a request to create a custom product page.',\n });\n const edit = await sendItemCommand(client, {\n command: 'edit',\n itemId: item.id,\n revisionId: item.currentRevisionId,\n pageName: name,\n });\n if (edit.refusal)\n return renameAnswer(input, {\n renamed: false,\n approved: false,\n message: edit.refusal,\n });\n const renamed = edit.result?.item as ActionItemSummary | undefined;\n const approve = await sendItemCommand(client, {\n command: 'approve',\n itemId: item.id,\n revisionId: renamed?.currentRevisionId ?? null,\n });\n return renameAnswer(\n input,\n approve.refusal\n ? {\n renamed: true,\n approved: false,\n // The server's own refusal, as it said it.\n message: approve.refusal,\n next: `The page is renamed to \u201C${name}\u201D and waits for approval (approve_action).`,\n }\n : {\n renamed: true,\n approved: true,\n message: `Renamed to \u201C${name}\u201D and approved. Fload creates the page after a short undo window; the inbox shows where it is.`,\n },\n approve.result?.item ?? renamed\n );\n } catch (error) {\n return toolError(error);\n }\n}\n", "const INTERNAL_ERROR_PATTERNS: RegExp[] = [\n /\\b(stack|trace|at\\s+[\\w.$<>]+\\s*\\()/i,\n /\\b(sql|postgres|drizzle|database|constraint|duplicate key|violates|relation)\\b/i,\n /\\b(fetch|undici|socket|ECONNRESET|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|HTTP\\s+\\d{3})\\b/i,\n /\\b(token|secret|api[_-]?key|authorization|bearer|cookie|password)\\b/i,\n /\\b[a-z0-9]+_(secret|token|key)\\b/i,\n /\\b(secret|token|key)[_-][a-z0-9]+\\b/i,\n /\\b(scrap|browser|patchright|playwright|chromium|page\\.|locator|selector)\\b/i,\n /\\b(redis|bullmq|queue|job id|worker)\\b/i,\n];\n\nfunction looksInternal(message: string): boolean {\n return INTERNAL_ERROR_PATTERNS.some(pattern => pattern.test(message));\n}\n\nexport function publicMcpErrorMessage(\n message: unknown,\n fallbackMessage = 'Fload could not complete the request. Please try again.'\n): string {\n const raw =\n message instanceof Error\n ? message.message\n : typeof message === 'string'\n ? message\n : '';\n const normalized = raw.replace(/\\s+/g, ' ').trim();\n\n if (!normalized || normalized.length > 180 || looksInternal(normalized)) {\n return fallbackMessage;\n }\n\n return normalized;\n}\n\n/** Fload's permission scopes look like `read:aso` / `write:agents`. */\nconst SCOPE_PATTERN = /^(read|write):[a-z]{2,20}$/;\n\n/**\n * FLO-2773: the scope a 403 `insufficient_scope` refusal names, from the\n * RFC 6750 `WWW-Authenticate` header or the JSON body. Null when the refusal\n * is something else; an empty string when it names no recognisable scope.\n */\nexport function insufficientScopeOf(\n status: number,\n wwwAuthenticate: string | null,\n body: unknown\n): string | null {\n if (status !== 403) return null;\n const fromHeader = wwwAuthenticate?.includes('insufficient_scope')\n ? /scope=\"([^\"]*)\"/.exec(wwwAuthenticate)?.[1]\n : undefined;\n const record =\n body && typeof body === 'object' ? (body as Record<string, unknown>) : {};\n if (fromHeader === undefined && record.error !== 'insufficient_scope') {\n return null;\n }\n const scope =\n fromHeader ?? (typeof record.scope === 'string' ? record.scope : '');\n return SCOPE_PATTERN.test(scope) ? scope : '';\n}\n\n/** What to tell the person whose key lacks a scope, and how to fix it. */\nexport function insufficientScopeMessage(scope: string): string {\n const permission = scope\n ? `the ${scope} permission`\n : 'the permission this needs';\n return `This API key does not have ${permission}. Create a key that includes it in Fload: Settings \u2192 API keys.`;\n}\n", "/**\n * ASO (App Store Optimization) tools for MCP\n * Tools: get_aso_summary, get_aso_recommendations, get_aso_keywords,\n * get_aso_experiments, get_aso_locale_snapshots, trigger_aso_analysis\n */\n\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const getAsoSummarySchema = z.object({\n assetId: z.string().uuid().describe('App UUID to get ASO summary for'),\n});\n\nexport const getAsoRecommendationsSchema = z.object({\n assetId: z\n .string()\n .uuid()\n .describe('App UUID to get ASO recommendations for'),\n});\n\nexport const getAsoKeywordsSchema = z.object({\n assetId: z\n .string()\n .uuid()\n .describe('App UUID to get keyword intelligence for'),\n locale: z\n .string()\n .optional()\n .describe(\n 'Locale code to filter keywords (e.g., \"en-US\", \"de-DE\"). Returns all locales if omitted.'\n ),\n});\n\nexport const getAsoExperimentsSchema = z.object({\n assetId: z.string().uuid().describe('App UUID to list ASO experiments for'),\n status: z\n .enum([\n 'proposed',\n 'approved',\n 'applied',\n 'measuring',\n 'completed',\n 'reverted',\n ])\n .optional()\n .describe('Filter experiments by status'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .default(20)\n .describe('Maximum number of experiments to return'),\n cursor: z\n .string()\n .optional()\n .describe('Pagination cursor from a previous response (meta.nextCursor)'),\n});\n\nexport const getAsoLocaleSnapshotsSchema = z.object({\n assetId: z.string().uuid().describe('App UUID to get locale snapshots for'),\n store: z\n .enum(['ios', 'android'])\n .default('ios')\n .describe('Which store listing to read'),\n locale: z\n .string()\n .optional()\n .describe(\n 'Filter to a single locale (e.g. \"en-US\"). Returns all locales if omitted.'\n ),\n view: z\n .enum(['latest', 'history'])\n .default('latest')\n .describe(\n '\"latest\" (default) = newest snapshot per (locale, type); \"history\" = raw revisions newest first'\n ),\n limit: z\n .number()\n .int()\n .min(1)\n .max(500)\n .optional()\n .describe('Maximum snapshot rows to return (newest first)'),\n});\n\nexport const triggerAsoAnalysisSchema = z.object({\n assetId: z.string().uuid().describe('App UUID to trigger ASO analysis for'),\n});\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * Get ASO score, health, and overview for an app\n */\nexport async function getAsoSummary(\n input: z.input<typeof getAsoSummarySchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get(\n `/api/assets/${input.assetId}/aso/summary`\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Get current ASO recommendations (title, subtitle, keywords suggestions)\n */\nexport async function getAsoRecommendations(\n input: z.input<typeof getAsoRecommendationsSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get(\n `/api/assets/${input.assetId}/aso/recommendations`\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Get keyword rankings, search volume, and competitor data\n */\nexport async function getAsoKeywords(\n input: z.input<typeof getAsoKeywordsSchema>,\n client: FloadApiClient\n) {\n try {\n const params: Record<string, string | number | boolean | undefined> = {};\n if (input.locale) params.locale = input.locale;\n\n const response = await client.get(\n `/api/assets/${input.assetId}/aso/keyword-intelligence`,\n params\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * List ASO experiments with status filtering\n */\nexport async function getAsoExperiments(\n input: z.input<typeof getAsoExperimentsSchema>,\n client: FloadApiClient\n) {\n try {\n const params: Record<string, string | number | boolean | undefined> = {\n limit: input.limit,\n cursor: input.cursor,\n };\n if (input.status) params.status = input.status;\n\n const response = await client.get(\n `/api/assets/${input.assetId}/aso/experiments`,\n params\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Get current App Store/Google Play listing snapshots across all locales\n */\nexport async function getAsoLocaleSnapshots(\n input: z.input<typeof getAsoLocaleSnapshotsSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get(\n `/api/assets/${input.assetId}/aso/listing-snapshots`,\n {\n store: input.store,\n locale: input.locale,\n view: input.view,\n limit: input.limit,\n }\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Trigger a new ASO analysis run for an app\n */\nexport async function triggerAsoAnalysis(\n input: z.input<typeof triggerAsoAnalysisSchema>,\n client: FloadApiClient\n) {\n try {\n // The real route is /aso/refetch (re-pulls the listing + re-runs the\n // audit). /aso/analyze never existed.\n const response = await client.post(\n `/api/assets/${input.assetId}/aso/refetch`,\n { force: true }\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/** Read immutable per-object decisions and their source evidence. */\nexport const getAsoEvidenceSchema = z.object({ assetId: z.string().uuid() });\nexport async function getAsoEvidence(\n input: z.input<typeof getAsoEvidenceSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get(\n `/api/assets/${input.assetId}/aso/methodology`\n );\n return {\n content: [{ type: 'text' as const, text: formatAsJson(response) }],\n };\n } catch (error) {\n return {\n content: [{ type: 'text' as const, text: formatError(error) }],\n isError: true,\n };\n }\n}\n", "/**\n * Chat tools for MCP\n * Tools: list_conversations, get_conversation_messages, send_chat_message\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const listConversationsSchema = z.object({\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .default(20)\n .describe('Maximum number of conversations to return'),\n});\n\nexport const getConversationMessagesSchema = z.object({\n conversationId: z\n .string()\n .uuid()\n .describe('The conversation UUID to get messages for'),\n});\n\nexport const sendChatMessageSchema = z.object({\n message: z.string().describe('The message to send to the AI chat'),\n conversationId: z\n .string()\n .uuid()\n .optional()\n .describe(\n 'Existing conversation UUID to continue. Starts a new conversation if omitted.'\n ),\n agentType: z\n .string()\n .optional()\n .describe(\n 'Agent type to use for the conversation (e.g., review, monitoring)'\n ),\n});\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * List chat conversations\n */\nexport async function listConversations(\n input: z.input<typeof listConversationsSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get('/api/chat/conversations', {\n limit: input.limit,\n });\n const conversations = response.data || response.conversations || response;\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n totalConversations: Array.isArray(conversations)\n ? conversations.length\n : 0,\n conversations,\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Get messages in a conversation\n */\nexport async function getConversationMessages(\n input: z.input<typeof getConversationMessagesSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get(\n `/api/chat/messages/${input.conversationId}`\n );\n const messages = response.data || response.messages || response;\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n conversationId: input.conversationId,\n totalMessages: Array.isArray(messages) ? messages.length : 0,\n messages,\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * FLO-2669: the words the Fload app says for an answer in a new\n * organization's free first conversation (the API's\n * `@packages/shared-types/chat/free-conversation`; this package is published\n * on its own, so it keeps a copy, checked against the API's in its tests).\n */\nexport const FREE_CONVERSATION_LABEL = 'Free: your first conversation';\nexport const FREE_CONVERSATION_ENDED_NOTICE =\n 'Your free first conversation has ended; messages now use credits.';\n\n/**\n * What an answer cost, from its `data-usage` part: the credits it used, or\n * that the organization's free first conversation carried it. Null when the\n * stream said neither (an admin chat, or an older API).\n */\nexport type ChatAnswerCost =\n | { free: false; credits: number }\n | { free: true; label: string; messagesLeft: number; notice?: string };\n\nfunction answerCostOf(data: unknown): ChatAnswerCost | null {\n if (!data || typeof data !== 'object') return null;\n const usage = data as {\n credits?: unknown;\n freeConversation?: { messagesLeft?: unknown; ended?: unknown };\n };\n const free = usage.freeConversation;\n if (free && typeof free.messagesLeft === 'number') {\n return {\n free: true,\n label: FREE_CONVERSATION_LABEL,\n messagesLeft: free.messagesLeft,\n ...(free.ended === true\n ? { notice: FREE_CONVERSATION_ENDED_NOTICE }\n : {}),\n };\n }\n return typeof usage.credits === 'number'\n ? { free: false, credits: usage.credits }\n : null;\n}\n\n/**\n * Extract the assistant's text (and the tools it used, and what the answer\n * cost) from an AI SDK UI-message SSE stream. Tolerant: unknown event types\n * are skipped.\n */\nexport function parseUiMessageStream(raw: string): {\n reply: string;\n toolsUsed: string[];\n cost: ChatAnswerCost | null;\n} {\n let reply = '';\n const toolsUsed: string[] = [];\n let cost: ChatAnswerCost | null = null;\n for (const line of raw.split('\\n')) {\n if (!line.startsWith('data:')) continue;\n const payload = line.slice(5).trim();\n if (!payload || payload === '[DONE]') continue;\n try {\n const event = JSON.parse(payload) as Record<string, unknown>;\n if (event.type === 'text-delta') {\n reply += String(event.delta ?? event.textDelta ?? '');\n } else if (\n typeof event.type === 'string' &&\n event.type === 'tool-input-start' &&\n typeof event.toolName === 'string'\n ) {\n toolsUsed.push(event.toolName);\n } else if (event.type === 'data-usage') {\n cost = answerCostOf(event.data) ?? cost;\n }\n } catch {\n // Non-JSON data line \u2014 skip.\n }\n }\n return { reply, toolsUsed, cost };\n}\n\n/**\n * Send a message to the AI chat. POST /api/chat speaks the AI SDK chat\n * protocol: the body is { id, messages: UIMessage[] } and the response is\n * a UI-message event stream, not JSON.\n */\nexport async function sendChatMessage(\n input: z.input<typeof sendChatMessageSchema>,\n client: FloadApiClient\n) {\n try {\n const conversationId = input.conversationId ?? randomUUID();\n\n // POST /api/chat treats the client-sent messages array as the FULL\n // model context \u2014 continuing a conversation means replaying its prior\n // turns, exactly as the web client does.\n let priorMessages: Array<Record<string, unknown>> = [];\n if (input.conversationId) {\n // The route defaults to the OLDEST 50 messages (ascending order,\n // offset 0) \u2014 fetch generously and keep the most recent turns so\n // long conversations continue from where they left off.\n const history = await client.get<{\n data?: Array<{\n id: string;\n role: string;\n parts?: Array<{ type?: string; text?: string }>;\n }>;\n }>(`/api/chat/messages/${input.conversationId}`, { limit: 1000 });\n for (const message of history.data ?? []) {\n const textParts = (message.parts ?? []).filter(\n part => part.type === 'text' && typeof part.text === 'string'\n );\n if (textParts.length === 0) continue;\n priorMessages.push({\n id: message.id,\n role: message.role,\n parts: textParts,\n });\n }\n priorMessages = priorMessages.slice(-100);\n }\n\n const body: Record<string, unknown> = {\n id: conversationId,\n messages: [\n ...priorMessages,\n {\n id: randomUUID(),\n role: 'user',\n parts: [{ type: 'text', text: input.message }],\n },\n ],\n };\n if (input.agentType) {\n body.agentContext = {\n agentId: null,\n agentType: input.agentType,\n agentName: input.agentType,\n surface: 'mcp',\n };\n }\n\n const raw = await client.postStream('/api/chat', body);\n const { reply, toolsUsed, cost } = parseUiMessageStream(raw);\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n conversationId,\n reply: reply || 'The assistant returned no text response.',\n toolsUsed,\n // FLO-2669: the credits the answer used, or that it was free.\n ...(cost ? { cost } : {}),\n tip: 'Pass this conversationId to continue the conversation or to get_conversation_messages for the full transcript.',\n }),\n },\n ],\n ...(reply ? {} : { isError: true }),\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n", "/**\n * Tool registry for Fload MCP Server.\n *\n * Barrel re-exports every tool handler + schema, plus `registerTools`\n * which both the stdio entry (@fload-ai/mcp for local Claude Desktop /\n * Cursor / VS Code) and the HTTP transport (mounted at /mcp on the\n * Fload API for remote OAuth-authenticated agents) call to populate an\n * McpServer instance. Adding a tool in one place wires it into both.\n *\n * Every tool carries a `title` + either `readOnlyHint` or\n * `destructiveHint` (or both explicitly false for reversible side\n * effects). Anthropic's connector marketplace enforces this \u2014 tools\n * missing annotations fail review. See\n * https://modelcontextprotocol.io/specification/server/tools for the\n * annotation semantics.\n */\nimport type {\n McpServer,\n ToolCallback,\n} from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport type { z, ZodObject, ZodRawShape } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { RateLimiter } from '../rate-limiter.js';\n\nexport * from './apps.js';\nexport * from './reviews.js';\nexport * from './analytics.js';\nexport * from './download-impact.js';\nexport * from './agents.js';\nexport * from './ads.js';\nexport * from './dashboard.js';\nexport * from './actions.js';\nexport * from './aso.js';\nexport * from './chat.js';\n\nimport {\n listAppsSchema,\n listApps,\n getAppDetailsSchema,\n getAppDetails,\n} from './apps.js';\nimport {\n getReviewsSchema,\n getReviews,\n generateReviewReplySchema,\n generateReviewReply,\n sendReviewReplySchema,\n sendReviewReply,\n translateReviewSchema,\n translateReview,\n} from './reviews.js';\nimport {\n discoverMetricsSchema,\n discoverMetrics,\n getMetricsSchema,\n getMetrics,\n discoverDimensionsSchema,\n discoverDimensions,\n} from './analytics.js';\nimport {\n getDownloadImpactSchema,\n getDownloadImpact,\n} from './download-impact.js';\nimport {\n listAgentsSchema,\n listAgents,\n getAgentDetailsSchema,\n getAgentDetails,\n getAgentRunHistorySchema,\n getAgentRunHistory,\n triggerAgentRunSchema,\n triggerAgentRun,\n pauseAgentSchema,\n pauseAgent,\n resumeAgentSchema,\n resumeAgent,\n getAgentActivitySchema,\n getAgentActivity,\n} from './agents.js';\nimport {\n listConversationsSchema,\n listConversations,\n getConversationMessagesSchema,\n getConversationMessages,\n sendChatMessageSchema,\n sendChatMessage,\n} from './chat.js';\nimport { getAdsPerformanceSchema, getAdsPerformance } from './ads.js';\nimport {\n getDashboardOverviewSchema,\n getDashboardOverview,\n} from './dashboard.js';\nimport {\n listPendingActionsSchema,\n listPendingActions,\n approveActionSchema,\n approveAction,\n rejectActionSchema,\n rejectAction,\n checkActionNowSchema,\n checkActionNow,\n renameCustomPageActionSchema,\n renameCustomPageAction,\n} from './actions.js';\nimport {\n getAsoEvidenceSchema,\n getAsoEvidence,\n getAsoSummarySchema,\n getAsoSummary,\n getAsoRecommendationsSchema,\n getAsoRecommendations,\n getAsoKeywordsSchema,\n getAsoKeywords,\n getAsoExperimentsSchema,\n getAsoExperiments,\n getAsoLocaleSnapshotsSchema,\n getAsoLocaleSnapshots,\n triggerAsoAnalysisSchema,\n triggerAsoAnalysis,\n} from './aso.js';\n\nexport interface RegisterToolsOptions {\n /**\n * Custom rate limiter. Defaults to 100 requests/minute global.\n * The HTTP transport passes one scoped per-user so concurrent Claude/\n * ChatGPT/Cursor agents don't share a quota with each other.\n */\n rateLimiter?: RateLimiter;\n}\n\n/**\n * MCP tool annotations per spec. At least one of `readOnlyHint` or\n * `destructiveHint` must be set to satisfy Anthropic's directory check.\n * For reversible state changes (pause agent, approve a draft) we\n * set both to `false` explicitly.\n */\ninterface FloadToolAnnotations {\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n}\n\ntype FloadToolHandler<T extends ZodRawShape> = (\n input: z.infer<ZodObject<T>>,\n client: FloadApiClient\n) => Promise<CallToolResult>;\n\nexport function registerTools(\n server: McpServer,\n client: FloadApiClient,\n options: RegisterToolsOptions = {}\n): void {\n const rateLimiter = options.rateLimiter ?? new RateLimiter(100, 60_000);\n\n function wrapTool<T extends ZodRawShape>(\n handler: FloadToolHandler<T>\n ): ToolCallback<ZodObject<T>> {\n const callback: ToolCallback<ZodObject<T>> = async input => {\n const rateCheck = rateLimiter.check('default');\n if (!rateCheck.allowed) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `Rate limit exceeded. Try again in ${Math.ceil(\n rateCheck.retryAfterMs / 1000\n )}s. Limit: 100 requests/minute.`,\n },\n ],\n isError: true,\n };\n }\n return handler(input, client);\n };\n return callback;\n }\n\n // Helper: register a tool with the annotations the marketplace expects.\n // Keeps each tool one call so a reviewer can eyeball the whole surface.\n function tool<T extends ZodRawShape>(\n name: string,\n title: string,\n description: string,\n schema: ZodObject<T>,\n handler: FloadToolHandler<T>,\n annotations: FloadToolAnnotations\n ) {\n server.registerTool<ZodRawShape, ZodObject<T>>(\n name,\n {\n title,\n description,\n inputSchema: schema,\n annotations: { title, ...annotations },\n },\n wrapTool(handler)\n );\n }\n\n // \u2500\u2500 APPS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'list_apps',\n 'List apps',\n 'List all mobile apps in your Fload organization. Returns app metadata including name, bundle ID, platform (iOS/Android), icon URL, and category.',\n listAppsSchema,\n listApps,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_app_details',\n 'Get app details',\n '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.',\n getAppDetailsSchema,\n getAppDetails,\n { readOnlyHint: true, openWorldHint: false }\n );\n\n // \u2500\u2500 REVIEWS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'get_reviews',\n 'Get reviews',\n '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.',\n getReviewsSchema,\n getReviews,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'generate_review_reply',\n 'Generate review reply (AI draft)',\n '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.',\n generateReviewReplySchema,\n generateReviewReply,\n { readOnlyHint: false, destructiveHint: false, openWorldHint: true }\n );\n tool(\n 'send_review_reply',\n 'Send review reply',\n '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).',\n sendReviewReplySchema,\n sendReviewReply,\n { readOnlyHint: false, destructiveHint: true, openWorldHint: true }\n );\n tool(\n 'translate_review',\n 'Translate review',\n '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.',\n translateReviewSchema,\n translateReview,\n { readOnlyHint: true, openWorldHint: true }\n );\n\n // \u2500\u2500 ANALYTICS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'discover_metrics',\n 'Discover available metrics',\n \"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.\",\n discoverMetricsSchema,\n discoverMetrics,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_metrics',\n 'Get metrics',\n \"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.\",\n getMetricsSchema,\n getMetrics,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'discover_dimensions',\n 'Discover available dimensions',\n 'Discover available dimensions for breaking down metrics (e.g., country, platform, app version, campaign). Optionally get the available values for a specific dimension.',\n discoverDimensionsSchema,\n discoverDimensions,\n { readOnlyHint: true, openWorldHint: false }\n );\n\n tool(\n 'get_download_impact',\n 'Get what Fload changed on downloads',\n \"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.\",\n getDownloadImpactSchema,\n getDownloadImpact,\n { readOnlyHint: true, openWorldHint: false }\n );\n\n // \u2500\u2500 AGENTS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'list_agents',\n 'List agents',\n \"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.\",\n listAgentsSchema,\n listAgents,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_agent_details',\n 'Get agent details',\n 'Get detailed configuration and status for a specific agent type. For the review agent, returns per-asset settings (mode, tone, custom instructions).',\n getAgentDetailsSchema,\n getAgentDetails,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_agent_run_history',\n 'Get agent run history',\n 'Get run history for a specific agent type. Returns run status, timing, and error details.',\n getAgentRunHistorySchema,\n getAgentRunHistory,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'trigger_agent_run',\n 'Trigger agent run',\n '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.',\n triggerAgentRunSchema,\n triggerAgentRun,\n { readOnlyHint: false, destructiveHint: false, openWorldHint: true }\n );\n tool(\n 'pause_agent',\n 'Pause agent',\n '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.',\n pauseAgentSchema,\n pauseAgent,\n {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n }\n );\n tool(\n 'resume_agent',\n 'Resume agent',\n '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.',\n resumeAgentSchema,\n resumeAgent,\n {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n }\n );\n tool(\n 'get_agent_activity',\n 'Get agent activity',\n '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.',\n getAgentActivitySchema,\n getAgentActivity,\n { readOnlyHint: true, openWorldHint: false }\n );\n\n // \u2500\u2500 ADS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'get_ads_performance',\n 'Get ads performance',\n '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).',\n getAdsPerformanceSchema,\n getAdsPerformance,\n { readOnlyHint: true, openWorldHint: false }\n );\n\n // \u2500\u2500 DASHBOARD \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'get_dashboard_overview',\n 'Get dashboard overview',\n 'Get an aggregated dashboard overview for the organization. Returns portfolio summary (apps, valuations, ratings), data connector health status, and alerts (pending review drafts).',\n getDashboardOverviewSchema,\n getDashboardOverview,\n { readOnlyHint: true, openWorldHint: false }\n );\n\n // \u2500\u2500 PENDING ACTIONS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'list_pending_actions',\n 'List pending actions',\n '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.',\n listPendingActionsSchema,\n listPendingActions,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'approve_action',\n 'Approve pending action',\n '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).',\n approveActionSchema,\n approveAction,\n { readOnlyHint: false, destructiveHint: true, openWorldHint: true }\n );\n tool(\n 'reject_action',\n 'Reject pending action',\n \"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.\",\n rejectActionSchema,\n rejectAction,\n { readOnlyHint: false, destructiveHint: true, openWorldHint: false }\n );\n tool(\n 'check_action_now',\n 'Check a change in the store now',\n '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.',\n checkActionNowSchema,\n checkActionNow,\n { readOnlyHint: false, destructiveHint: false, openWorldHint: true }\n );\n tool(\n 'rename_custom_page_action',\n 'Rename a custom product page request and send it',\n '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.',\n renameCustomPageActionSchema,\n renameCustomPageAction,\n { readOnlyHint: false, destructiveHint: true, openWorldHint: true }\n );\n\n // \u2500\u2500 ASO \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'get_aso_summary',\n 'Get ASO summary',\n '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.',\n getAsoSummarySchema,\n getAsoSummary,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_aso_recommendations',\n 'Get ASO recommendations',\n '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.',\n getAsoRecommendationsSchema,\n getAsoRecommendations,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_aso_evidence',\n 'Get ASO decisions and evidence',\n '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.',\n getAsoEvidenceSchema,\n getAsoEvidence,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_aso_keywords',\n 'Get ASO keywords',\n '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.',\n getAsoKeywordsSchema,\n getAsoKeywords,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_aso_experiments',\n 'Get ASO experiments',\n '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.',\n getAsoExperimentsSchema,\n getAsoExperiments,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_aso_locale_snapshots',\n 'Get ASO locale snapshots',\n '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.',\n getAsoLocaleSnapshotsSchema,\n getAsoLocaleSnapshots,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'trigger_aso_analysis',\n 'Trigger ASO analysis',\n \"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.\",\n triggerAsoAnalysisSchema,\n triggerAsoAnalysis,\n { readOnlyHint: false, destructiveHint: false, openWorldHint: true }\n );\n\n // \u2500\u2500 CHAT \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'list_conversations',\n 'List conversations',\n '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.',\n listConversationsSchema,\n listConversations,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_conversation_messages',\n 'Get conversation messages',\n 'Get all messages in a specific chat conversation. Returns the full message history including user messages and AI responses with timestamps and roles.',\n getConversationMessagesSchema,\n getConversationMessages,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'send_chat_message',\n 'Send chat message',\n \"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).\",\n sendChatMessageSchema,\n sendChatMessage,\n { readOnlyHint: false, destructiveHint: false, openWorldHint: true }\n );\n}\n"],
5
- "mappings": ";AAAO,IAAM,cAAN,MAAkB;AAAA,EAGvB,YACU,WAAmB,KACnB,WAAmB,KAC3B;AAFQ;AACA;AAAA,EACP;AAAA,EAFO;AAAA,EACA;AAAA,EAJF,QAA+B,oBAAI,IAAI;AAAA,EAO/C,MAAM,KAIJ;AACA,UAAM,MAAM,KAAK,IAAI;AACrB,UAAM,cAAc,MAAM,KAAK;AAG/B,QAAI,aAAa,KAAK,MA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AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,EAAE,cAAc,OAAO,iBAAiB,OAAO,eAAe,KAAK;AAAA,EACrE;AACF;",
4
+ "sourcesContent": ["export class RateLimiter {\n private calls: Map<string, number[]> = new Map();\n\n constructor(\n private maxCalls: number = 100,\n private windowMs: number = 60_000\n ) {}\n\n check(key: string): {\n allowed: boolean;\n remaining: number;\n retryAfterMs: number;\n } {\n const now = Date.now();\n const windowStart = now - this.windowMs;\n\n // Get existing calls, prune expired\n let timestamps = this.calls.get(key) || [];\n timestamps = timestamps.filter(t => t > windowStart);\n\n if (timestamps.length >= this.maxCalls) {\n // With maxCalls 0 there is no call in the window to wait out.\n const [oldestInWindow] = timestamps;\n const retryAfterMs =\n oldestInWindow === undefined\n ? Number.NaN\n : oldestInWindow + this.windowMs - now;\n this.calls.set(key, timestamps);\n return { allowed: false, remaining: 0, retryAfterMs };\n }\n\n timestamps.push(now);\n this.calls.set(key, timestamps);\n return {\n allowed: true,\n remaining: this.maxCalls - timestamps.length,\n retryAfterMs: 0,\n };\n }\n}\n", "/**\n * App management tools for MCP\n * Tools: list_apps, get_app_details\n */\n\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\ninterface AppRecord {\n id: string;\n name: string;\n bundleId: string;\n appleAppId?: string | null;\n googleAppId?: string | null;\n currentValuation?: string | number | null;\n metadata?: unknown;\n createdAt?: string | null;\n updatedAt?: string | null;\n}\n\ninterface AppListResponse {\n data?: AppRecord[];\n}\n\ninterface AppDetailResponse {\n data?: AppRecord;\n}\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const listAppsSchema = z.object({\n platform: z\n .enum(['ios', 'android'])\n .optional()\n .describe('Filter by platform (ios or android)'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .default(50)\n .describe('Maximum number of apps to return'),\n});\n\nexport const getAppDetailsSchema = z.object({\n assetId: z\n .string()\n .uuid()\n .optional()\n .describe('App UUID from Fload database'),\n bundleId: z\n .string()\n .optional()\n .describe('App bundle ID (e.g., com.example.app)'),\n});\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * List all apps in the organization\n */\nexport async function listApps(\n input: z.input<typeof listAppsSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get<AppListResponse>('/api/assets', {\n limit: input.limit,\n offset: 0,\n // The listing hides assets without a valuation by default; \"list all\n // apps\" must include apps that haven't been valued yet (FLO-734).\n includeUnvalued: 'true',\n });\n const apps = response.data ?? [];\n\n // Filter by platform client-side if needed\n const filtered = input.platform\n ? apps.filter(app => {\n if (input.platform === 'ios') return !!app.appleAppId;\n if (input.platform === 'android') return !!app.googleAppId;\n return true;\n })\n : apps;\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n total: filtered.length,\n apps: filtered.map(app => ({\n id: app.id,\n name: app.name,\n bundleId: app.bundleId,\n platform: app.appleAppId\n ? 'ios'\n : app.googleAppId\n ? 'android'\n : 'unknown',\n addedAt: app.updatedAt || app.createdAt,\n })),\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Get detailed information about a specific app\n */\nexport async function getAppDetails(\n input: z.input<typeof getAppDetailsSchema>,\n client: FloadApiClient\n) {\n try {\n if (!input.assetId && !input.bundleId) {\n throw new Error('Either assetId or bundleId must be provided');\n }\n\n let assetId = input.assetId;\n\n // If bundleId provided, find the asset first\n if (!assetId && input.bundleId) {\n const allApps = await client.get<AppListResponse>('/api/assets', {\n limit: 100,\n offset: 0,\n includeUnvalued: 'true',\n });\n const match = (allApps.data ?? []).find(\n app => app.bundleId === input.bundleId\n );\n if (!match) {\n return {\n content: [\n {\n type: 'text' as const,\n text: 'App not found with that bundle ID',\n },\n ],\n isError: true,\n };\n }\n assetId = match.id;\n }\n\n const response = await client.get<AppDetailResponse>(\n `/api/assets/${assetId}`\n );\n const app = response.data;\n if (!app) {\n throw new Error('App details response did not include app data');\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n id: app.id,\n name: app.name,\n bundleId: app.bundleId,\n appleAppId: app.appleAppId,\n googleAppId: app.googleAppId,\n platform: app.appleAppId\n ? 'ios'\n : app.googleAppId\n ? 'android'\n : 'unknown',\n currentValuation: app.currentValuation,\n metadata: app.metadata,\n addedAt: app.createdAt,\n updatedAt: app.updatedAt,\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n", "/**\n * Data formatting utilities for MCP tool responses\n */\n\n/**\n * Format database results as JSON text for MCP response\n */\nexport function formatAsJson(data: unknown): string {\n return JSON.stringify(data, null, 2);\n}\n\n/**\n * Format error message for MCP error response\n */\nexport function formatError(error: unknown): string {\n if (error instanceof Error) {\n return `Error: ${error.message}`;\n }\n return `Unknown error: ${String(error)}`;\n}\n\n/**\n * Format date for display\n */\nexport function formatDate(date: Date): string {\n return date.toISOString().split('T')[0]!;\n}\n\n/**\n * Format large numbers with commas\n */\nexport function formatNumber(num: number): string {\n return num.toLocaleString();\n}\n", "/**\n * Review management tools for MCP\n * Tools: get_reviews, generate_review_reply, send_review_reply, translate_review\n */\n\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\ninterface AppRecord {\n id: string;\n bundleId: string;\n}\n\ninterface AppListResponse {\n data?: AppRecord[];\n}\n\ninterface ReviewRecord {\n id: string;\n appId?: string;\n platform?: string;\n rating?: number | string | null;\n title?: string | null;\n /** The handler maps DB `body` to API `review`. */\n review?: string | null;\n body?: string | null;\n nickname?: string | null;\n author?: string | null;\n lastModified?: number | string | null;\n date?: string | null;\n appVersionString?: string | null;\n version?: string | null;\n storeFront?: string | null;\n developerResponse?:\n | string\n | {\n response?: string | null;\n /** FLO-2571: live | publishing | removed | null, as the API reads it. */\n publication?: string | null;\n }\n | null;\n replySource?: 'agent' | 'user' | null;\n hasDraft?: boolean | null;\n hasReply?: boolean | null;\n reply?: string | null;\n}\n\n/**\n * GET /api/assets/:assetId/reviews returns\n * `{ data: { reviews, reviewCount, handledCount }, meta }` (FLO-734).\n */\ninterface ReviewsResponse {\n data?: {\n reviews?: ReviewRecord[];\n reviewCount?: number;\n /** Continuation for the next page; null/absent on the last page. */\n nextCursor?: string | null;\n handledCount?: number;\n };\n}\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const getReviewsSchema = z.object({\n assetId: z.string().uuid().optional().describe('App UUID to filter reviews'),\n bundleId: z.string().optional().describe('App bundle ID to filter reviews'),\n platform: z\n .enum(['ios', 'android'])\n .optional()\n .describe('Filter by platform'),\n rating: z\n .number()\n .int()\n .min(1)\n .max(5)\n .optional()\n .describe('Filter by star rating (1-5)'),\n replied: z\n .boolean()\n .optional()\n .describe('Filter by replied status (true = has reply, false = no reply)'),\n startDate: z\n .string()\n .optional()\n .describe('Filter reviews from this date (ISO format: YYYY-MM-DD)'),\n endDate: z\n .string()\n .optional()\n .describe('Filter reviews until this date (ISO format: YYYY-MM-DD)'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(200)\n .default(50)\n .describe('Maximum number of reviews to return'),\n cursor: z\n .string()\n .optional()\n .describe(\n 'nextCursor from the previous get_reviews call, to fetch the next page with the same app and filters'\n ),\n sortBy: z\n .enum(['date', 'rating'])\n .default('date')\n .describe('Sort reviews by date or rating'),\n});\n\nexport const generateReviewReplySchema = z.object({\n reviewId: z.string().describe('The review UUID to generate a reply for'),\n assetId: z.string().uuid().describe('The app UUID the review belongs to'),\n});\n\nexport const sendReviewReplySchema = z.object({\n reviewId: z.string().describe('The review UUID to reply to'),\n assetId: z.string().uuid().describe('The app UUID the review belongs to'),\n response: z.string().describe('The reply text to send'),\n});\n\nexport const translateReviewSchema = z.object({\n reviewId: z.string().describe('The review UUID to translate'),\n assetId: z.string().uuid().describe('The app UUID the review belongs to'),\n // The translate endpoint receives the review content in the request body\n // (it does not re-fetch it). Pass the fields from a get_reviews result.\n rating: z\n .number()\n .int()\n .min(1)\n .max(5)\n .describe('The review star rating, from get_reviews'),\n title: z.string().default('').describe('The review title, from get_reviews'),\n body: z.string().describe('The review text to translate, from get_reviews'),\n storeFront: z\n .string()\n .default('')\n .describe('The review storefront (e.g. \"SE\"), from get_reviews'),\n appVersionString: z\n .string()\n .default('')\n .describe('The app version the review was left on, from get_reviews'),\n});\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * Get reviews with filters\n */\nexport async function getReviews(\n input: z.input<typeof getReviewsSchema>,\n client: FloadApiClient\n) {\n try {\n // Resolve assetId from bundleId if needed\n let assetId = input.assetId;\n if (!assetId && input.bundleId) {\n const allApps = await client.get<AppListResponse>('/api/assets', {\n limit: 100,\n offset: 0,\n includeUnvalued: 'true',\n });\n const match = (allApps.data ?? []).find(\n app => app.bundleId === input.bundleId\n );\n if (!match) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `No app found with bundle ID: ${input.bundleId}`,\n },\n ],\n isError: true,\n };\n }\n assetId = match.id;\n }\n\n // Reviews live under /api/assets/:assetId/reviews \u2014 there is no\n // cross-asset listing route, so an app must be identified first.\n if (!assetId) {\n return {\n content: [\n {\n type: 'text' as const,\n text: 'Provide an assetId (or bundleId) to fetch reviews for. Use list_apps to find app IDs.',\n },\n ],\n isError: true,\n };\n }\n\n const params: Record<string, string | number | boolean | undefined> =\n reviewQueryParameters(input);\n\n const response = await client.get<ReviewsResponse>(\n `/api/assets/${assetId}/reviews`,\n params\n );\n let reviews = response.data?.reviews ?? [];\n // The API returns reviews date-sorted; rating sort is client-side.\n if (input.sortBy === 'rating') {\n reviews = [...reviews].sort(\n (a, b) => Number(b.rating ?? 0) - Number(a.rating ?? 0)\n );\n }\n\n const hasReply = (review: ReviewRecord) =>\n !!(review.developerResponse || review.replySource || review.hasReply);\n\n // Calculate summary stats\n const summary = {\n totalReviews: reviews.length,\n averageRating:\n reviews.length > 0\n ? (\n reviews.reduce((sum, review) => {\n const rating = Number(review.rating ?? 0);\n return sum + (Number.isFinite(rating) ? rating : 0);\n }, 0) / reviews.length\n ).toFixed(2)\n : 0,\n repliedCount: reviews.filter(review => hasReply(review)).length,\n unrepliedCount: reviews.filter(review => !hasReply(review)).length,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n summary,\n // Pass back as `cursor` to get the next page; null = last page.\n nextCursor: response.data?.nextCursor ?? null,\n reviews: reviews.map(review => ({\n id: review.id,\n appId: review.appId,\n platform: review.platform,\n rating: review.rating,\n title: review.title,\n // The handler exposes the review text as `review`.\n body: review.review ?? review.body,\n author: review.nickname || review.author,\n // Epoch ms from the handler.\n date: review.lastModified || review.date,\n version: review.appVersionString || review.version,\n storeFront: review.storeFront,\n hasReply: hasReply(review),\n replySource: review.replySource ?? null,\n hasDraft: review.hasDraft ?? false,\n reply: review.developerResponse\n ? typeof review.developerResponse === 'object'\n ? review.developerResponse.response\n : review.developerResponse\n : review.reply || null,\n // FLO-2571: where an App Store reply stands at Apple.\n replyPublication:\n typeof review.developerResponse === 'object'\n ? (review.developerResponse?.publication ?? null)\n : null,\n })),\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\nfunction reviewQueryParameters(input: z.input<typeof getReviewsSchema>) {\n const params: Record<string, string | number | boolean | undefined> = {\n limit: input.limit,\n };\n if (input.cursor) params.cursor = input.cursor;\n\n if (input.platform) params.platform = input.platform;\n if (input.rating !== undefined) params.rating = input.rating;\n if (input.replied !== undefined)\n params.responseStatus = input.replied ? 'replied' : 'unreplied';\n if (input.startDate) params.startDate = input.startDate;\n if (input.endDate) params.endDate = input.endDate;\n return params;\n}\n\n/**\n * Generate an AI draft reply for a review\n */\nexport async function generateReviewReply(\n input: z.input<typeof generateReviewReplySchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.post(\n `/api/assets/${input.assetId}/reviews/${input.reviewId}/generate-reply`,\n undefined\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Send a reply to an app review\n */\nexport async function sendReviewReply(\n input: z.input<typeof sendReviewReplySchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.post(\n `/api/assets/${input.assetId}/reviews/${input.reviewId}/respond`,\n // The API handler reads `responseText` from the body.\n { responseText: input.response }\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Translate a review to English\n */\nexport async function translateReview(\n input: z.input<typeof translateReviewSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.post(\n `/api/assets/${input.assetId}/reviews/${input.reviewId}/translate`,\n // The translate endpoint expects the review content in the body.\n {\n rating: input.rating,\n title: input.title,\n review: input.body,\n storeFront: input.storeFront,\n appVersionString: input.appVersionString,\n lastModified: Date.now(),\n }\n );\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n", "/**\n * Metrics discovery and query tools for MCP\n * Tools: discover_metrics, get_metrics, discover_dimensions\n */\n\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\ninterface MetricAvailabilityResponse {\n data?: {\n availableMetrics?: string[];\n metricGroups?: Record<string, unknown>;\n };\n}\n\ninterface EnrichedMetric {\n name: string;\n displayName: string;\n category: string;\n type: string;\n}\n\n/** A plain point carries `value`; a breakdown point carries `total`. */\ninterface MetricPoint {\n date: string;\n value?: number;\n total?: number;\n}\n\ninterface MetricChange {\n currentValue?: number;\n effectiveFromDate?: string;\n effectiveToDate?: string;\n}\n\n/**\n * A breakdown read's value per dimension value (a country), as the Fload API\n * computes it for the metric's aggregation class (FLO-2487): `basis` says\n * what each value is. `total` sums the days; `latest` is the period's last\n * day (active subscriptions), never a sum; `daily_average` is a unique\n * metric's average a day (active devices), never a total for the period;\n * `average` and `ratio` are rates, which have no total.\n */\ninterface BreakdownPeriod {\n basis: 'total' | 'latest' | 'average' | 'daily_average' | 'ratio';\n total: number | null;\n previousTotal: number | null;\n change: number | null;\n values: Array<{\n label: string;\n code: string;\n value: number | null;\n previousValue: number | null;\n change: number | null;\n share: number | null;\n }>;\n}\n\ninterface MetricsTimeseriesResponse {\n data?: Record<string, MetricPoint[]>;\n changes?: Record<string, MetricChange | undefined>;\n breakdownTotals?: Record<string, BreakdownPeriod | undefined>;\n meta?: UnavailableMeta;\n}\n\n/**\n * FLO-2840: requested metrics the API could not report and why: `reason`\n * (`no_data` or `source_filter`) and, for `no_data`, the `cause`\n * (`not_reported`: none of the connected sources has ever sent it, or\n * `not_in_window`). Never a 0.\n */\ninterface UnavailableMeta {\n unavailableMetrics?: string[];\n unavailableMetricReasons?: Record<\n string,\n { reason: string; cause?: string; message: string } | undefined\n >;\n}\n\n/**\n * The `unavailable.reason` values get_metrics emits, exactly the ones its\n * description names: the API's `no_data` with cause `not_reported` becomes\n * `not_reported`; any other `no_data` (cause `not_in_window`) stays `no_data`.\n */\nexport const UNAVAILABLE_REASONS = [\n 'not_reported',\n 'no_data',\n 'source_filter',\n] as const;\ntype UnavailableReasonValue = (typeof UNAVAILABLE_REASONS)[number];\n\nfunction unavailableReasonValue(reason: {\n reason: string;\n cause?: string;\n}): UnavailableReasonValue {\n if (reason.cause === 'not_reported') return 'not_reported';\n // A source filter, a dimension filter (a country) or the breakdown's\n // dimension (a metric stored only as a total) hides it.\n const hiddenByCause =\n reason.cause === 'filtered_out' || reason.cause === 'not_by_dimension';\n if (reason.reason === 'source_filter' || hiddenByCause) {\n return 'source_filter';\n }\n return 'no_data';\n}\n\n/** Why the API could not report this metric, when it says so. */\nfunction unavailableReason(name: string, meta: UnavailableMeta) {\n if (!(meta.unavailableMetrics ?? []).includes(name)) return undefined;\n const reason = meta.unavailableMetricReasons?.[name];\n return {\n reason: reason ? unavailableReasonValue(reason) : 'no_data',\n message: reason?.message ?? 'Unavailable for this query.',\n };\n}\n\n/**\n * The requested metrics the API declared unavailable and returned no series\n * for (a base metric no source sent), each with its reason.\n */\nfunction unavailableEntries(\n requested: readonly string[],\n data: Record<string, unknown>,\n meta: UnavailableMeta\n) {\n return requested.flatMap(name => {\n const unavailable = unavailableReason(name, meta);\n if (!unavailable || name in data) return [];\n return [\n {\n name,\n displayName: METRIC_INFO[name]?.displayName || name,\n type: METRIC_INFO[name]?.type || 'count',\n summary: null,\n change: null,\n unavailable,\n },\n ];\n });\n}\n\ninterface MetricSummary {\n /**\n * The metric's value over the period, as the Fload API computes it for the\n * metric's aggregation class: a sum for flows (downloads, proceeds), the\n * last value for levels (active subscriptions), an average for stored rates,\n * and the ratio of the period's sums for computed ratios (CPA, ARPPU).\n * It covers every requested day except recent days whose data is not\n * complete yet. Null when the API has no value for the period.\n */\n value: number | null;\n /** The first and last day `value` covers. */\n effectiveFromDate: string | null;\n effectiveToDate: string | null;\n min: number | null;\n max: number | null;\n dataPoints: number;\n}\n\nfunction summarize(\n points: MetricPoint[] | undefined,\n change: MetricChange | undefined\n): MetricSummary {\n const values = (Array.isArray(points) ? points : [])\n .map(point => point.value ?? point.total)\n .filter((value): value is number => typeof value === 'number');\n return {\n value: change?.currentValue ?? null,\n effectiveFromDate: change?.effectiveFromDate ?? null,\n effectiveToDate: change?.effectiveToDate ?? null,\n min: values.length > 0 ? Math.min(...values) : null,\n max: values.length > 0 ? Math.max(...values) : null,\n dataPoints: values.length,\n };\n}\n\ninterface DimensionValuesResponse {\n data?: unknown;\n}\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const discoverMetricsSchema = z.object({\n assetId: z\n .string()\n .uuid()\n .describe('App UUID to check available metrics for'),\n});\n\nexport const getMetricsSchema = z.object({\n assetId: z.string().uuid().describe('App UUID'),\n metrics: z\n .array(z.string())\n .min(1)\n .describe(\n 'Metric names to query (e.g., [\"proceeds\", \"totalDownloads\"]). Use discover_metrics first to see available metrics.'\n ),\n startDate: z\n .string()\n .optional()\n .describe('Start date (YYYY-MM-DD). Defaults to 30 days ago.'),\n endDate: z\n .string()\n .optional()\n .describe('End date (YYYY-MM-DD). Defaults to today.'),\n granularity: z\n .enum(['daily', 'weekly', 'monthly'])\n .default('daily')\n .describe('Data granularity'),\n dimension: z\n .string()\n .optional()\n .describe(\n '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.'\n ),\n dimensionFilter: z\n .string()\n .optional()\n .describe(\n 'Filter to a specific dimension value (e.g., \"US\" when dimension is \"storefront\")'\n ),\n});\n\nexport const discoverDimensionsSchema = z.object({\n assetId: z.string().uuid().describe('App UUID'),\n dimension: z\n .string()\n .optional()\n .describe(\n 'If provided, returns the available values for this dimension (e.g., countries for \"storefront\")'\n ),\n});\n\n// =============================================================================\n// METRIC DISPLAY INFO\n// =============================================================================\n\n// Human-readable names and categories for common metrics\nconst METRIC_INFO: Record<\n string,\n { displayName: string; category: string; type: string }\n> = {\n proceeds: {\n displayName: 'Net Revenue (after store cut)',\n category: 'Revenue',\n type: 'currency',\n },\n total_revenue: {\n displayName: 'Gross Revenue',\n category: 'Revenue',\n type: 'currency',\n },\n total_downloads: {\n displayName: 'Total Downloads',\n category: 'Downloads',\n type: 'count',\n },\n units: {\n displayName: 'First-time Downloads',\n category: 'Downloads',\n type: 'count',\n },\n redownloads: {\n displayName: 'Re-downloads',\n category: 'Downloads',\n type: 'count',\n },\n page_views: {\n displayName: 'App Store Page Views',\n category: 'Downloads',\n type: 'count',\n },\n impressions: {\n displayName: 'App Store Impressions',\n category: 'Downloads',\n type: 'count',\n },\n sessions: {\n displayName: 'App Sessions',\n category: 'Engagement',\n type: 'count',\n },\n active_devices: {\n displayName: 'Active Devices',\n category: 'Engagement',\n type: 'count',\n },\n crashes: { displayName: 'Crashes', category: 'Engagement', type: 'count' },\n paying_users: {\n displayName: 'Paying Users',\n category: 'Engagement',\n type: 'count',\n },\n active_subs: {\n displayName: 'Active Subscriptions',\n category: 'Subscriptions',\n type: 'count',\n },\n active_trials: {\n displayName: 'Active Trials',\n category: 'Subscriptions',\n type: 'count',\n },\n new_trials: {\n displayName: 'New Trials',\n category: 'Subscriptions',\n type: 'count',\n },\n trial_conversion_rate: {\n displayName: 'Trial Conversion Rate',\n category: 'Subscriptions',\n type: 'percentage',\n },\n subscription_retention_rate: {\n displayName: 'Subscription Retention Rate',\n category: 'Subscriptions',\n type: 'percentage',\n },\n products_sold: {\n displayName: 'Products Sold (IAP)',\n category: 'Revenue',\n type: 'count',\n },\n ad_spend: { displayName: 'Ad Spend', category: 'Ads', type: 'currency' },\n ad_impressions: {\n displayName: 'Ad Impressions',\n category: 'Ads',\n type: 'count',\n },\n ad_taps: { displayName: 'Ad Taps/Clicks', category: 'Ads', type: 'count' },\n ad_installs: {\n displayName: 'Ad-attributed Installs',\n category: 'Ads',\n type: 'count',\n },\n ad_conversions: {\n displayName: 'Ad Conversions',\n category: 'Ads',\n type: 'count',\n },\n};\n\n// Dimension display names\nconst DIMENSION_INFO: Record<string, string> = {\n storefront: 'Country',\n region: 'Region',\n platform: 'Platform (device type)',\n source: 'Source',\n appVersion: 'App Version',\n purchase: 'Product',\n appReferrer: 'App Referrer',\n domainReferrer: 'Domain Referrer',\n subscription_state: 'Subscription Type',\n duration: 'Duration',\n revenueShare: 'Revenue Share',\n campaign: 'Campaign',\n};\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\nexport async function discoverMetrics(\n input: z.input<typeof discoverMetricsSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get<MetricAvailabilityResponse>(\n `/api/assets/${input.assetId}/metrics/availability`\n );\n const availableMetrics = response.data?.availableMetrics ?? [];\n const metricGroups = response.data?.metricGroups ?? {};\n\n // Enrich with display names and categories\n const enriched = availableMetrics.map((metricName: string) => {\n const info = METRIC_INFO[metricName];\n return {\n name: metricName,\n displayName: info?.displayName || metricName,\n category: info?.category || 'Other',\n type: info?.type || 'count',\n };\n });\n\n // Group by category\n const byCategory: Record<string, EnrichedMetric[]> = {};\n for (const m of enriched) {\n (byCategory[m.category] ??= []).push(m);\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n assetId: input.assetId,\n totalAvailable: availableMetrics.length,\n metricsByCategory: byCategory,\n dataGroups: metricGroups,\n tip: 'Use the metric \"name\" field in get_metrics. You can query multiple metrics at once.',\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [{ type: 'text' as const, text: formatError(error) }],\n isError: true,\n };\n }\n}\n\nexport async function getMetrics(\n input: z.input<typeof getMetricsSchema>,\n client: FloadApiClient\n) {\n try {\n // Direct callers may omit defaulted fields; the MCP server has parsed them.\n const granularity = input.granularity ?? 'daily';\n // Default date range: last 30 days\n const endDate = input.endDate || new Date().toISOString().split('T')[0]!;\n const startDate =\n input.startDate ||\n (() => {\n const d = new Date();\n d.setDate(d.getDate() - 30);\n return d.toISOString().split('T')[0]!;\n })();\n\n const params: Record<string, string> = {\n metrics: input.metrics.join(','),\n fromDate: startDate,\n toDate: endDate,\n granularity,\n };\n\n // The API rolls every value up into `breakdownTotals` from an uncapped\n // read; `timeseries` stays capped to the top values a day, so an agent's\n // context is not flooded with every country for every day (FLO-2487).\n if (input.dimension) params.dimension = input.dimension;\n if (input.dimensionFilter && input.dimension) {\n params[`filter.${input.dimension}`] = input.dimensionFilter;\n }\n\n const path = `/api/assets/${input.assetId}/metrics/timeseries`;\n const response = await client.get<MetricsTimeseriesResponse>(path, params);\n // The summary is the value over the requested days. A weekly or monthly\n // read leaves out its still-open last bucket (the current week or month,\n // when the window ends today), so the summary comes from a daily read,\n // which leaves out only days whose data is not complete yet (FLO-1826).\n const summaryResponse =\n input.granularity === 'daily'\n ? response\n : await client.get<MetricsTimeseriesResponse>(path, {\n ...params,\n granularity: 'daily',\n });\n\n // The API returns { data: { metricName: [{date, value}] }, changes: {...}, meta: {...} }\n const data = response.data ?? {};\n const changes = summaryResponse.changes ?? {};\n const meta = response.meta ?? {};\n\n // The period value comes from the API, which aggregates each metric by\n // its class; summing or averaging the daily points here would be wrong for\n // levels and ratios (FLO-1826).\n const summaries: Record<string, MetricSummary> = {};\n for (const [metricName, points] of Object.entries(data)) {\n summaries[metricName] = summarize(points, changes[metricName]);\n }\n\n const info = METRIC_INFO;\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n assetId: input.assetId,\n dateRange: { start: startDate, end: endDate },\n granularity,\n dimension: input.dimension || null,\n metrics: [\n ...Object.keys(data).map(name => ({\n name,\n displayName: info[name]?.displayName || name,\n type: info[name]?.type || 'count',\n summary: summaries[name],\n change: changes[name] || null,\n ...(input.dimension && {\n breakdown: summaryResponse.breakdownTotals?.[name] ?? null,\n }),\n // A computed metric the API marks unavailable comes back as an\n // empty series: it carries its reason too.\n ...(unavailableReason(name, meta) && {\n unavailable: unavailableReason(name, meta),\n }),\n })),\n // FLO-2840: listed with the reason, never dropped or 0.\n ...unavailableEntries(input.metrics, data, meta),\n ],\n timeseries: data,\n meta,\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [{ type: 'text' as const, text: formatError(error) }],\n isError: true,\n };\n }\n}\n\nexport async function discoverDimensions(\n input: z.input<typeof discoverDimensionsSchema>,\n client: FloadApiClient\n) {\n try {\n if (input.dimension) {\n // Get values for a specific dimension\n const response = await client.get<DimensionValuesResponse>(\n `/api/assets/${input.assetId}/metrics/dimensions/${input.dimension}/values`\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n assetId: input.assetId,\n dimension: input.dimension,\n displayName: DIMENSION_INFO[input.dimension] || input.dimension,\n values: response.data ?? response,\n }),\n },\n ],\n };\n }\n\n // Get available dimensions. The route returns [{id, label}] objects.\n const response = await client.get<{\n data?: Array<string | { id?: string; label?: string }>;\n }>(`/api/assets/${input.assetId}/metrics/dimensions`);\n const dimensions = Array.isArray(response.data) ? response.data : [];\n\n const enriched = dimensions.map(dim => {\n if (typeof dim === 'string') {\n return { name: dim, displayName: DIMENSION_INFO[dim] || dim };\n }\n const id = dim.id ?? '';\n return { name: id, displayName: dim.label ?? DIMENSION_INFO[id] ?? id };\n });\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n assetId: input.assetId,\n dimensions: enriched,\n tip: 'Use dimension name in get_metrics \"dimension\" param. Use discover_dimensions with a specific dimension to see available values.',\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [{ type: 'text' as const, text: formatError(error) }],\n isError: true,\n };\n }\n}\n", "/**\n * FLO-2549: get_download_impact \u2014 did Fload's listing changes move the\n * downloads they can affect? The same reader as the app metrics chart, the\n * monthly report, the audit and the remote MCP's getDownloadImpact\n * (`GET /api/assets/:assetId/metrics/download-impact`).\n */\n\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\nconst Day = z\n .string()\n .regex(/^\\d{4}-\\d{2}-\\d{2}$/)\n .optional();\n\nexport const getDownloadImpactSchema = z.object({\n assetId: z.string().uuid().describe('App UUID (App Store apps)'),\n from: Day.describe(\n 'First day drawn (YYYY-MM-DD); default 20 weeks before `to`'\n ),\n to: Day.describe(\n 'Last day drawn (YYYY-MM-DD); default the newest day with data'\n ),\n beforeFrom: Day.describe(\n 'Start of the \"before\" window compared (needs beforeTo; all windows within 400 days of each other)'\n ),\n beforeTo: Day.describe('End of the \"before\" window compared'),\n afterFrom: Day.describe(\n 'Start of the \"after\" window compared (needs afterTo)'\n ),\n afterTo: Day.describe('End of the \"after\" window compared'),\n country: z\n .string()\n .regex(/^[a-zA-Z]{2}$/)\n .optional()\n .describe(\n 'One storefront, two-letter code (e.g. \"us\"): narrows countries and keywords'\n ),\n includeDays: z\n .boolean()\n .optional()\n .describe('Also return every day (long). Weeks carry the same downloads.'),\n});\n\ninterface DownloadImpactResponse {\n days?: unknown;\n lastYearDays?: unknown;\n [key: string]: unknown;\n}\n\nexport async function getDownloadImpact(\n input: z.input<typeof getDownloadImpactSchema>,\n client: FloadApiClient\n) {\n try {\n const { assetId, includeDays, ...query } = input;\n const impact = await client.get<DownloadImpactResponse>(\n `/api/assets/${assetId}/metrics/download-impact`,\n query\n );\n const { days, lastYearDays, ...rest } = impact;\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(\n includeDays ? { ...rest, days, lastYearDays } : rest\n ),\n },\n ],\n };\n } catch (error) {\n return {\n content: [{ type: 'text' as const, text: formatError(error) }],\n isError: true,\n };\n }\n}\n", "/**\n * Agent tools for MCP\n * Tools: list_agents, get_agent_details, get_agent_run_history, trigger_agent_run, pause_agent, resume_agent, get_agent_activity\n */\n\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\ninterface AgentsResponse {\n data?: unknown[];\n agents?: unknown[];\n}\n\ninterface DataEnvelope {\n data?: unknown;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\n// =============================================================================\n// CONSTANTS\n// =============================================================================\n\n// Keep in step with the API's live agent catalog. Advertising a retired type\n// here is worse than omitting it: /api/agents/by-type/<type> 400s, the tool\n// swallows that into \"no <type> agent is provisioned \u2026 activate it from the\n// Agents page\", and the user is told to do something impossible.\nconst AGENT_TYPES = ['review', 'aso'] as const;\n\ntype AgentType = (typeof AGENT_TYPES)[number];\n\nconst AGENT_DESCRIPTIONS: Record<AgentType, string> = {\n review:\n 'AI-powered review management \u2014 drafts and sends replies to app store reviews',\n aso: 'App Store Optimization \u2014 listing optimization suggestions for better visibility',\n};\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const listAgentsSchema = z.object({});\n\nexport const getAgentDetailsSchema = z.object({\n agentType: z\n .enum(AGENT_TYPES)\n .describe('The type of agent to get details for'),\n assetId: z\n .string()\n .uuid()\n .optional()\n .describe('App UUID to get agent config for (when agent is per-asset)'),\n});\n\nexport const getAgentRunHistorySchema = z.object({\n agentType: z\n .enum(AGENT_TYPES)\n .describe('The type of agent to get run history for'),\n assetId: z.string().uuid().optional().describe('App UUID to filter runs'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .default(20)\n .describe('Maximum number of runs to return'),\n});\n\nexport const triggerAgentRunSchema = z.object({\n agentId: z\n .string()\n .describe('The agent ID to trigger a run for (the `id` from list_agents)'),\n assetId: z\n .string()\n .uuid()\n .optional()\n .describe('Optional app UUID to run the agent against'),\n});\n\nexport const pauseAgentSchema = z.object({\n agentId: z\n .string()\n .describe('The agent ID to pause (the `id` from list_agents)'),\n});\n\nexport const resumeAgentSchema = z.object({\n agentId: z\n .string()\n .describe('The agent ID to resume (the `id` from list_agents)'),\n});\n\nexport const getAgentActivitySchema = z.object({\n agentId: z\n .string()\n .describe('The agent ID to get activity for (the `id` from list_agents)'),\n});\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * List all available agent types and their status\n */\nexport async function listAgents(\n _input: z.input<typeof listAgentsSchema>,\n client: FloadApiClient\n) {\n try {\n // Try to get agent info from the API\n let apiAgents: unknown[] | null = null;\n try {\n const response = await client.get<AgentsResponse | unknown[]>(\n '/api/agents'\n );\n apiAgents = Array.isArray(response)\n ? response\n : (response.data ?? response.agents ?? null);\n } catch {\n // API route may not exist yet \u2014 fall back to static list\n }\n\n if (apiAgents && Array.isArray(apiAgents)) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n totalAgents: apiAgents.length,\n agents: apiAgents,\n }),\n },\n ],\n };\n }\n\n // Fallback: return static agent list with descriptions\n const agents = AGENT_TYPES.map(type => ({\n type,\n description: AGENT_DESCRIPTIONS[type],\n available: true,\n }));\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n totalAgents: agents.length,\n agents,\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Get details about a specific agent type\n */\nexport async function getAgentDetails(\n input: z.input<typeof getAgentDetailsSchema>,\n client: FloadApiClient\n) {\n try {\n // The per-type endpoint is /api/agents/by-type/:type \u2014 it returns the\n // agent row + its 10 most recent runs, or a nullable agent when that\n // type/scope has not been activated. (Passing type into /:agentId 404s.)\n try {\n const params: Record<string, string | undefined> = {};\n if (input.assetId) params.assetId = input.assetId;\n const response = await client.get<{\n agent?: Record<string, unknown>;\n recentRuns?: unknown[];\n }>(`/api/agents/by-type/${input.agentType}`, params);\n if (response.agent) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n agent: response.agent,\n recentRuns: response.recentRuns ?? [],\n }),\n },\n ],\n };\n }\n } catch {\n // Agent type not provisioned for this org \u2014 fall through to basic info.\n }\n\n const response: Record<string, unknown> = {\n type: input.agentType,\n description: AGENT_DESCRIPTIONS[input.agentType],\n message: `No ${input.agentType} agent is provisioned for this organization yet. Activate it from the Agents page or with trigger_agent_run once created.`,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Get agent run history\n */\nexport async function getAgentRunHistory(\n input: z.input<typeof getAgentRunHistorySchema>,\n client: FloadApiClient\n) {\n try {\n // Runs are keyed by agent id, not type \u2014 resolve the org's agent of this\n // type first without changing activation state, then fetch run history.\n let agentId: string | undefined;\n try {\n const byTypeParams: Record<string, string | undefined> = {};\n if (input.assetId) byTypeParams.assetId = input.assetId;\n const byType = await client.get<{ agent?: { id?: string } }>(\n `/api/agents/by-type/${input.agentType}`,\n byTypeParams\n );\n agentId = byType.agent?.id;\n } catch {\n // No agent of this type \u2014 report that instead of an empty list.\n }\n\n if (!agentId) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n agentType: input.agentType,\n runs: [],\n message: `No ${input.agentType} agent is provisioned for this organization yet, so there is no run history.`,\n }),\n },\n ],\n };\n }\n\n const response = await client.get<DataEnvelope>(\n `/api/agents/${agentId}/runs`,\n { limit: input.limit }\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n agentType: input.agentType,\n agentId,\n ...asRecord(response.data ?? response),\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Trigger a manual agent run\n */\nexport async function triggerAgentRun(\n input: z.input<typeof triggerAgentRunSchema>,\n client: FloadApiClient\n) {\n try {\n // The route merges body.triggerContext into the run's context; a bare\n // assetId at the top level is ignored.\n const body = input.assetId\n ? { triggerContext: { assetId: input.assetId } }\n : {};\n\n const response = await client.post<DataEnvelope>(\n `/api/agents/${input.agentId}/run`,\n body\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response.data ?? response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Pause an agent\n */\nexport async function pauseAgent(\n input: z.input<typeof pauseAgentSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.post<DataEnvelope>(\n `/api/agents/${input.agentId}/pause`\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response.data ?? response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Resume a paused agent\n */\nexport async function resumeAgent(\n input: z.input<typeof resumeAgentSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.post<DataEnvelope>(\n `/api/agents/${input.agentId}/resume`\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response.data ?? response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Get recent activity log for an agent\n */\nexport async function getAgentActivity(\n input: z.input<typeof getAgentActivitySchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get<DataEnvelope>(\n `/api/agents/${input.agentId}/activity`\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response.data ?? response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n", "/**\n * Ads performance tools for MCP\n * Tools: get_ads_performance\n */\n\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\ninterface CampaignRecord {\n id: string;\n assetId?: string | null;\n assetName?: string | null;\n platformCampaignId?: string | null;\n name?: string | null;\n status?: string | null;\n objective?: string | null;\n platform?: string | null;\n linkSource?: string | null;\n linkedAt?: string | null;\n totalSpend?: number | null;\n totalImpressions?: number | null;\n totalTaps?: number | null;\n totalInstalls?: number | null;\n avgCPI?: number | null;\n avgTTR?: number | null;\n avgCVR?: number | null;\n}\n\ninterface CampaignsResponse {\n data?: CampaignRecord[];\n campaigns?: CampaignRecord[];\n /** The metrics read failed: every metric is null (unknown), never 0. */\n metricsUnavailable?: boolean;\n}\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const getAdsPerformanceSchema = z.object({\n assetId: z.string().uuid().optional().describe('Filter by app UUID'),\n platform: z\n .enum(['apple_search_ads', 'google_ads', 'meta_ads', 'tiktok_ads'])\n .optional()\n .describe('Filter by ad platform'),\n fromDate: z\n .string()\n .optional()\n .describe('Start date for performance data (YYYY-MM-DD)'),\n toDate: z\n .string()\n .optional()\n .describe('End date for performance data (YYYY-MM-DD)'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .default(50)\n .describe('Maximum number of campaigns to return'),\n});\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * Get ad campaign performance data\n */\nexport async function getAdsPerformance(\n input: z.input<typeof getAdsPerformanceSchema>,\n client: FloadApiClient\n) {\n try {\n // The campaigns route reads assetId + from/to; platform and limit\n // are not supported server-side, so they're applied client-side below.\n const params: Record<string, string | number | undefined> = {};\n\n if (input.assetId) params.assetId = input.assetId;\n if (input.fromDate) params.from = input.fromDate;\n if (input.toDate) params.to = input.toDate;\n\n const response = await client.get<CampaignsResponse>(\n '/api/ads/campaigns',\n params\n );\n let campaigns = response.data ?? response.campaigns ?? [];\n if (input.platform) {\n campaigns = campaigns.filter(c => c.platform === input.platform);\n }\n campaigns = campaigns.slice(0, input.limit);\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n total: campaigns.length,\n // The server couldn't read the metrics: null spend is unknown,\n // never \"no spend\".\n ...(response.metricsUnavailable\n ? {\n metricsUnavailable: true,\n note: 'The ads metrics could not be read right now, so spend, impressions, taps and installs are unknown (null), not zero. Try again later.',\n }\n : {}),\n campaigns: campaigns.map(campaign => ({\n id: campaign.id,\n assetId: campaign.assetId,\n assetName: campaign.assetName,\n platformCampaignId: campaign.platformCampaignId,\n name: campaign.name,\n status: campaign.status,\n objective: campaign.objective,\n platform: campaign.platform,\n linkSource: campaign.linkSource,\n linkedAt: campaign.linkedAt,\n totalSpend: campaign.totalSpend ?? null,\n totalImpressions: campaign.totalImpressions ?? null,\n totalTaps: campaign.totalTaps ?? null,\n totalInstalls: campaign.totalInstalls ?? null,\n avgCPI: campaign.avgCPI ?? null,\n avgTTR: campaign.avgTTR ?? null,\n avgCVR: campaign.avgCVR ?? null,\n })),\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n", "/**\n * Dashboard tools for MCP\n * Tools: get_dashboard_overview\n */\n\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\ninterface DashboardOverviewResponse {\n data?: unknown;\n}\n\ninterface SidebarAsset {\n id: string;\n name: string;\n bundleId: string;\n appleAppId?: string | null;\n googleAppId?: string | null;\n currentValuation?: string | number | null;\n rating?: string | number | null;\n ratingCount?: number | null;\n category?: string | null;\n iconUrl?: string | null;\n}\n\ninterface SidebarAssetsResponse {\n data?: SidebarAsset[];\n}\n\nfunction parseDashboardNumber(\n value: string | number | null | undefined\n): number | null {\n if (value === null || value === undefined || value === '') return null;\n const parsed = typeof value === 'number' ? value : Number.parseFloat(value);\n return Number.isFinite(parsed) ? parsed : null;\n}\n\nfunction getSidebarAssets(\n response: SidebarAssetsResponse | SidebarAsset[] | null\n): SidebarAsset[] {\n if (!response) return [];\n if (Array.isArray(response)) return response;\n return response.data ?? [];\n}\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const getDashboardOverviewSchema = z.object({});\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * Get aggregated dashboard overview for the organization\n */\nexport async function getDashboardOverview(\n _input: z.input<typeof getDashboardOverviewSchema>,\n client: FloadApiClient\n) {\n try {\n // Fetch overview metrics and sidebar assets in parallel\n const overviewPromise: Promise<DashboardOverviewResponse | null> = client\n .get<DashboardOverviewResponse>('/api/dashboard/overview-metrics')\n .catch(() => null);\n const sidebarPromise: Promise<\n SidebarAssetsResponse | SidebarAsset[] | null\n > = client\n .get<SidebarAssetsResponse | SidebarAsset[]>(\n '/api/dashboard/sidebar-assets'\n )\n .catch(() => null);\n\n const [overviewResponse, sidebarResponse] = await Promise.all([\n overviewPromise,\n sidebarPromise,\n ]);\n\n const overview = overviewResponse?.data ?? overviewResponse ?? {};\n // Build the dashboard response\n const apps = getSidebarAssets(sidebarResponse);\n\n const totalValuation = apps.reduce((sum, app) => {\n return sum + (parseDashboardNumber(app.currentValuation) ?? 0);\n }, 0);\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n portfolio: {\n totalApps: apps.length,\n totalValuation: totalValuation > 0 ? totalValuation : null,\n apps: apps.map(app => ({\n id: app.id,\n name: app.name,\n bundleId: app.bundleId,\n platform: app.appleAppId\n ? 'ios'\n : app.googleAppId\n ? 'android'\n : 'unknown',\n currentValuation: parseDashboardNumber(app.currentValuation),\n rating: parseDashboardNumber(app.rating),\n ratingCount: app.ratingCount ?? null,\n category: app.category ?? null,\n iconUrl: app.iconUrl ?? null,\n })),\n },\n overview,\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n", "/**\n * Action tools for MCP\n * Tools: list_pending_actions, approve_action, reject_action, check_action_now,\n * rename_custom_page_action\n *\n * FLO-1595: inbox work is an Actions item (the inbox's one read model), so\n * these tools read `GET /api/actions/items` and act through\n * `POST /api/actions/commands`, the same commands the web inbox sends. A\n * notice has nothing to approve: its approve is `acknowledge` and its reject\n * `dismiss`, as the inbox's buttons mean on an informational card.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\nimport { publicMcpErrorMessage } from '../public-errors.js';\n\ninterface ActionItemSummary {\n id: string;\n kind: string;\n status: string;\n subjectKey?: string;\n assetId?: string | null;\n currentRevisionId: string | null;\n allowedCommands?: string[];\n /** FLO-2633: the request that proposed it with others (one inbox card). */\n proposalBatch?: string | null;\n}\n\ninterface ActionItemListResponse {\n items?: unknown[];\n nextCursor?: string | null;\n}\n\ninterface ActionItemDetailResponse {\n item?: ActionItemSummary;\n}\n\ninterface ActionCommandResponse {\n results?: Array<{\n itemId: string;\n result: string;\n httpStatus?: number;\n error?: string;\n item?: unknown;\n /**\n * FLO-2564: a refused change's refusal; `check` names the check that\n * said no, in plain words.\n */\n policyRefusal?: { kind: string; check?: string; message: string };\n /**\n * FLO-2575: the store already showed the change, so nothing was\n * approved or sent and the item is done.\n */\n alreadyLive?: boolean;\n }>;\n /** A refusal of the whole request (403 and the like) says why here. */\n message?: string;\n}\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const listPendingActionsSchema = z.object({\n assetId: z.string().uuid().optional().describe('Filter by app UUID'),\n view: z\n .enum(['open', 'queued'])\n .default('open')\n .describe(\n '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).'\n ),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .default(50)\n .describe('Maximum number of actions to return'),\n});\n\nexport const approveActionSchema = z.object({\n actionId: z\n .string()\n .describe('The inbox item ID to approve (from list_pending_actions)'),\n wholeGroup: z\n .boolean()\n .optional()\n .describe(\n \"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.\"\n ),\n});\n\nexport const rejectActionSchema = z.object({\n actionId: z\n .string()\n .describe('The inbox item ID to reject (from list_pending_actions)'),\n reason: z\n .string()\n .trim()\n .min(1)\n .max(1000)\n .optional()\n .describe(\n \"Why, in the user's words. Kept with the rejection so the agents do not propose the same thing again.\"\n ),\n});\n\n/** FLO-2324: an item Fload is reading back from the store (status verifying). */\nexport const checkActionNowSchema = z.object({\n actionId: z\n .string()\n .describe(\n 'The inbox item ID to check now (from list_pending_actions with view \"queued\", or an approve_action result; its commands include check_now)'\n ),\n});\n\n/** FLO-2423: a custom product page create App Store Connect refused for its name. */\nexport const renameCustomPageActionSchema = z.object({\n actionId: z\n .string()\n .describe(\n '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)'\n ),\n name: z\n .string()\n .trim()\n .min(1)\n .max(100)\n .describe(\n 'The new page name: at most 100 characters (UTF-16 units), not its current name, not a page the app already has'\n ),\n});\n\ntype Intent = 'approve' | 'reject';\n\n/** The command an approve / reject is for an item of this kind. */\nfunction commandFor(kind: string, intent: Intent): string {\n if (kind === 'notice')\n return intent === 'approve' ? 'acknowledge' : 'dismiss';\n return intent;\n}\n\nfunction toolText(payload: unknown, isError = false) {\n return {\n content: [{ type: 'text' as const, text: formatAsJson(payload) }],\n ...(isError ? { isError: true } : {}),\n };\n}\n\nfunction toolError(error: unknown) {\n return {\n content: [{ type: 'text' as const, text: formatError(error) }],\n isError: true,\n };\n}\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * List the inbox items waiting on the user: to approve, or for them to act\n * on (the inbox's Open view), newest last.\n */\nexport async function listPendingActions(\n input: z.input<typeof listPendingActionsSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get<ActionItemListResponse>(\n '/api/actions/items',\n { view: input.view ?? 'open', assetId: input.assetId, limit: input.limit }\n );\n const actions = response.items ?? [];\n return toolText({\n total: actions.length,\n actions,\n hasMore: Boolean(response.nextCursor),\n });\n } catch (error) {\n return toolError(error);\n }\n}\n\n/** Run one approve or reject for an item, as the inbox would. */\nasync function commandItem(\n client: FloadApiClient,\n itemId: string,\n intent: Intent,\n reason?: string\n) {\n const detail = await client.get<ActionItemDetailResponse>(\n `/api/actions/items/${encodeURIComponent(itemId)}`\n );\n const item = detail.item;\n if (!item) throw new Error('Action not found');\n const command = commandFor(item.kind, intent);\n // A single target answers with its own status (409 not allowed, 422 not\n // writable, \u2026) and says why in its result: read it rather than throw.\n const answer = await client.postForAnswer<ActionCommandResponse>(\n '/api/actions/commands',\n {\n command,\n idempotencyKey: `mcp:${command}:${item.id}:${randomUUID()}`,\n targets: [\n {\n itemId: item.id,\n ...(command === 'approve' && item.currentRevisionId\n ? { revisionId: item.currentRevisionId }\n : {}),\n },\n ],\n ...(command === 'reject' && reason ? { reason } : {}),\n }\n );\n const result = answer.body?.results?.[0];\n if (!result)\n throw new Error(\n answer.ok\n ? 'Fload returned no result for the command.'\n : 'Fload rejected the request. Please check access and try again.'\n );\n return {\n command,\n result: {\n ...result,\n error: result.error\n ? publicMcpErrorMessage(\n result.error,\n 'Fload could not apply this change.'\n )\n : undefined,\n },\n };\n}\n\n/** What an approve did, in the user's words. */\nfunction approveMessage(\n command: string,\n applied: boolean,\n result: CommandResult | undefined\n): string {\n if (!applied) return refusedMessage(result);\n if (command === 'acknowledge') return 'Acknowledged.';\n // FLO-2575: nothing was approved or sent.\n if (result?.alreadyLive)\n return 'Already live: the store already shows this change, so nothing was sent. The item is done.';\n return 'Approved. Fload delivers it after a short undo window; the inbox shows where it is.';\n}\n\n/**\n * Why an approve did not go through. FLO-2564: a refusal leads with the check\n * that said no, as the server names it (\"Stopped by the language check: \u2026\").\n */\nfunction refusedMessage(result: CommandResult | undefined): string {\n const said = result?.error ?? 'The approval could not be recorded.';\n const check = result?.policyRefusal?.check;\n return check ? `Stopped by the ${check}: ${said}` : said;\n}\n\n/**\n * Approve an inbox item (a notice is acknowledged). Approving a review reply\n * publishes it to the store after a short undo window.\n */\nexport async function approveAction(\n input: z.input<typeof approveActionSchema>,\n client: FloadApiClient\n) {\n try {\n if (input.wholeGroup) {\n // An item in no card of several approves as it would alone.\n const grouped = await approveGroup(client, input.actionId);\n if (grouped) return grouped;\n }\n const { command, result } = await commandItem(\n client,\n input.actionId,\n 'approve'\n );\n const applied =\n result?.result === 'applied' || result?.result === 'replayed';\n return toolText(\n {\n success: applied,\n actionId: input.actionId,\n command,\n result: result?.result ?? 'unknown',\n ...(result?.error ? { error: result.error } : {}),\n message: approveMessage(command, applied, result),\n item: result?.item,\n },\n !applied\n );\n } catch (error) {\n return toolError(error);\n }\n}\n\n/**\n * The items waiting in this item's card (its proposal batch), it first.\n * FLO-2668: only the languages still waiting on a decision: one already\n * approved is on its way to the store, no longer in the card.\n */\nasync function groupOf(\n client: FloadApiClient,\n item: ActionItemSummary\n): Promise<ActionItemSummary[]> {\n if (!item.proposalBatch || item.status !== 'needs_approval') return [item];\n const isSibling = (other: unknown): other is ActionItemSummary =>\n typeof other === 'object' &&\n other !== null &&\n (other as ActionItemSummary).status === 'needs_approval' &&\n (other as ActionItemSummary).proposalBatch === item.proposalBatch &&\n (other as ActionItemSummary).assetId === item.assetId &&\n (other as ActionItemSummary).id !== item.id;\n // Every page of the app's open work: a card's languages may sit past the\n // first page behind other work (review of #2514).\n const siblings: ActionItemSummary[] = [];\n let cursor: string | null | undefined;\n do {\n const response: ActionItemListResponse =\n await client.get<ActionItemListResponse>('/api/actions/items', {\n view: 'open',\n limit: 100,\n ...(item.assetId ? { assetId: item.assetId } : {}),\n ...(cursor ? { cursor } : {}),\n });\n siblings.push(...(response.items ?? []).filter(isSibling));\n cursor = response.nextCursor;\n } while (cursor);\n return [item, ...siblings];\n}\n\n/**\n * FLO-2633: approve every language of an item's card in ONE command, as\n * the inbox's Approve does; a language that cannot be approved now (stopped,\n * being rewritten) is left as it is and listed.\n */\nasync function approveGroup(client: FloadApiClient, actionId: string) {\n const detail = await client.get<ActionItemDetailResponse>(\n `/api/actions/items/${encodeURIComponent(actionId)}`\n );\n if (!detail.item) throw new Error('Action not found');\n const group = await groupOf(client, detail.item);\n if (group.length <= 1) return null;\n const approvable = group.filter(item =>\n item.allowedCommands?.includes('approve')\n );\n const skipped = group\n .filter(item => !approvable.includes(item))\n .map(item => item.id);\n if (approvable.length === 0)\n return toolText(\n {\n success: false,\n actionId,\n skipped,\n message: 'Nothing in this card can be approved right now.',\n },\n true\n );\n const answer = await client.postForAnswer<ActionCommandResponse>(\n '/api/actions/commands',\n {\n command: 'approve',\n idempotencyKey: `mcp:approve-group:${actionId}:${randomUUID()}`,\n targets: approvable.map(item => ({\n itemId: item.id,\n ...(item.currentRevisionId\n ? { revisionId: item.currentRevisionId }\n : {}),\n })),\n }\n );\n const results = (answer.body?.results ?? []).map(result => ({\n itemId: result.itemId,\n result: result.result,\n ...(result.error\n ? {\n error: publicMcpErrorMessage(\n result.error,\n 'Fload could not apply this change.'\n ),\n }\n : {}),\n }));\n const approved = results.filter(\n r => r.result === 'applied' || r.result === 'replayed'\n ).length;\n return toolText(\n {\n success: approved > 0,\n actionId,\n approved,\n results,\n ...(skipped.length ? { skipped } : {}),\n message:\n approved > 0\n ? `Approved ${approved} of ${group.length}. Fload delivers them after a short undo window; the inbox shows where each is.`\n : 'The approval could not be recorded.',\n },\n approved === 0\n );\n}\n\n/** Reject an inbox item (a notice is dismissed). Nothing is sent. */\nexport async function rejectAction(\n input: z.input<typeof rejectActionSchema>,\n client: FloadApiClient\n) {\n try {\n const { command, result } = await commandItem(\n client,\n input.actionId,\n 'reject',\n input.reason\n );\n const applied =\n result?.result === 'applied' || result?.result === 'replayed';\n return toolText(\n {\n success: applied,\n actionId: input.actionId,\n command,\n result: result?.result ?? 'unknown',\n ...(result?.error ? { error: result.error } : {}),\n message: applied\n ? command === 'dismiss'\n ? 'Dismissed.'\n : 'Rejected. Nothing was sent.'\n : (result?.error ?? 'The rejection could not be recorded.'),\n item: result?.item,\n },\n !applied\n );\n } catch (error) {\n return toolError(error);\n }\n}\n\n/**\n * FLO-2324: \"Check now\" on an item Fload is reading back from the store: it\n * reads the store again at once instead of at its next scheduled check.\n * Nothing is written to the store.\n */\nexport async function checkActionNow(\n input: z.input<typeof checkActionNowSchema>,\n client: FloadApiClient\n) {\n try {\n const answer = await client.postForAnswer<ActionCommandResponse>(\n '/api/actions/commands',\n {\n command: 'check_now',\n idempotencyKey: `mcp:check_now:${input.actionId}:${randomUUID()}`,\n targets: [{ itemId: input.actionId }],\n }\n );\n const result = answer.body?.results?.[0];\n const applied =\n result?.result === 'applied' || result?.result === 'replayed';\n const error = result?.error\n ? publicMcpErrorMessage(result.error, 'Fload could not check it now.')\n : undefined;\n return toolText(\n {\n success: applied,\n actionId: input.actionId,\n command: 'check_now',\n result: result?.result ?? 'unknown',\n ...(error ? { error } : {}),\n message: applied\n ? 'Fload is checking the store now; the item updates as soon as the store shows the change.'\n : (error ??\n (answer.ok\n ? 'Fload returned no result for the command.'\n : 'Fload rejected the request. Please check access and try again.')),\n item: result?.item,\n },\n !applied\n );\n } catch (error) {\n return toolError(error);\n }\n}\n\n// =============================================================================\n// FLO-2423: rename a custom product page create, and approve it again\n// =============================================================================\n\ntype CommandResult = NonNullable<ActionCommandResponse['results']>[number];\n\nconst applied = (result: CommandResult | undefined) =>\n result?.result === 'applied' || result?.result === 'replayed';\n\n/** One command for one item, answered with its result or the refusal's words. */\nasync function sendItemCommand(\n client: FloadApiClient,\n body: { command: string; itemId: string; revisionId: string | null } & Record<\n string,\n unknown\n >\n): Promise<{ result?: CommandResult; refusal: string | null }> {\n const { command, itemId, revisionId, ...extra } = body;\n const answer = await client.postForAnswer<ActionCommandResponse>(\n '/api/actions/commands',\n {\n command,\n idempotencyKey: `mcp:${command}:${itemId}:${randomUUID()}`,\n targets: [{ itemId, ...(revisionId ? { revisionId } : {}) }],\n ...extra,\n }\n );\n const result = answer.body?.results?.[0];\n if (applied(result)) return { result, refusal: null };\n const said = result?.error ?? answer.body?.message;\n return {\n result,\n refusal: publicMcpErrorMessage(\n said,\n answer.ok\n ? 'Fload returned no result for the command.'\n : 'Fload rejected the request. Please check access and try again.'\n ),\n };\n}\n\nfunction renameAnswer(\n input: z.input<typeof renameCustomPageActionSchema>,\n outcome: {\n renamed: boolean;\n approved: boolean;\n message: string;\n next?: string;\n },\n item?: unknown\n) {\n const success = outcome.renamed && outcome.approved;\n return toolText(\n {\n success,\n actionId: input.actionId,\n ...outcome,\n ...(item === undefined ? {} : { item }),\n },\n !success\n );\n}\n\n/**\n * Rename a custom product page create (the inbox's \"Create with this name\"):\n * `edit` with the new page name on the revision the item shows, then\n * `approve` on the revision the rename returned. Fload's engine then creates\n * the page under the new name after the usual undo window. The tool checks\n * no login of its own: whatever the server's edit and approve refuse is\n * answered as the server said it.\n */\nexport async function renameCustomPageAction(\n input: z.input<typeof renameCustomPageActionSchema>,\n client: FloadApiClient\n) {\n try {\n const name = input.name.trim();\n const detail = await client.get<ActionItemDetailResponse>(\n `/api/actions/items/${encodeURIComponent(input.actionId)}`\n );\n const item = detail.item;\n if (\n !item ||\n item.kind !== 'asc_custom_product_page' ||\n !item.subjectKey?.startsWith('asc-cpp:')\n )\n return renameAnswer(input, {\n renamed: false,\n approved: false,\n message: 'This item is not a request to create a custom product page.',\n });\n const edit = await sendItemCommand(client, {\n command: 'edit',\n itemId: item.id,\n revisionId: item.currentRevisionId,\n pageName: name,\n });\n if (edit.refusal)\n return renameAnswer(input, {\n renamed: false,\n approved: false,\n message: edit.refusal,\n });\n const renamed = edit.result?.item as ActionItemSummary | undefined;\n const approve = await sendItemCommand(client, {\n command: 'approve',\n itemId: item.id,\n revisionId: renamed?.currentRevisionId ?? null,\n });\n return renameAnswer(\n input,\n approve.refusal\n ? {\n renamed: true,\n approved: false,\n // The server's own refusal, as it said it.\n message: approve.refusal,\n next: `The page is renamed to \u201C${name}\u201D and waits for approval (approve_action).`,\n }\n : {\n renamed: true,\n approved: true,\n message: `Renamed to \u201C${name}\u201D and approved. Fload creates the page after a short undo window; the inbox shows where it is.`,\n },\n approve.result?.item ?? renamed\n );\n } catch (error) {\n return toolError(error);\n }\n}\n", "const INTERNAL_ERROR_PATTERNS: RegExp[] = [\n /\\b(stack|trace|at\\s+[\\w.$<>]+\\s*\\()/i,\n /\\b(sql|postgres|drizzle|database|constraint|duplicate key|violates|relation)\\b/i,\n /\\b(fetch|undici|socket|ECONNRESET|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|HTTP\\s+\\d{3})\\b/i,\n /\\b(token|secret|api[_-]?key|authorization|bearer|cookie|password)\\b/i,\n /\\b[a-z0-9]+_(secret|token|key)\\b/i,\n /\\b(secret|token|key)[_-][a-z0-9]+\\b/i,\n /\\b(scrap|browser|patchright|playwright|chromium|page\\.|locator|selector)\\b/i,\n /\\b(redis|bullmq|queue|job id|worker)\\b/i,\n];\n\nfunction looksInternal(message: string): boolean {\n return INTERNAL_ERROR_PATTERNS.some(pattern => pattern.test(message));\n}\n\nexport function publicMcpErrorMessage(\n message: unknown,\n fallbackMessage = 'Fload could not complete the request. Please try again.'\n): string {\n const raw =\n message instanceof Error\n ? message.message\n : typeof message === 'string'\n ? message\n : '';\n const normalized = raw.replace(/\\s+/g, ' ').trim();\n\n if (!normalized || normalized.length > 180 || looksInternal(normalized)) {\n return fallbackMessage;\n }\n\n return normalized;\n}\n\n/** Fload's permission scopes look like `read:aso` / `write:agents`. */\nconst SCOPE_PATTERN = /^(read|write):[a-z]{2,20}$/;\n\n/**\n * FLO-2773: the scope a 403 `insufficient_scope` refusal names, from the\n * RFC 6750 `WWW-Authenticate` header or the JSON body. Null when the refusal\n * is something else; an empty string when it names no recognisable scope.\n */\nexport function insufficientScopeOf(\n status: number,\n wwwAuthenticate: string | null,\n body: unknown\n): string | null {\n if (status !== 403) return null;\n const fromHeader = wwwAuthenticate?.includes('insufficient_scope')\n ? /scope=\"([^\"]*)\"/.exec(wwwAuthenticate)?.[1]\n : undefined;\n const record =\n body && typeof body === 'object' ? (body as Record<string, unknown>) : {};\n if (fromHeader === undefined && record.error !== 'insufficient_scope') {\n return null;\n }\n const scope =\n fromHeader ?? (typeof record.scope === 'string' ? record.scope : '');\n return SCOPE_PATTERN.test(scope) ? scope : '';\n}\n\n/** What to tell the person whose key lacks a scope, and how to fix it. */\nexport function insufficientScopeMessage(scope: string): string {\n const permission = scope\n ? `the ${scope} permission`\n : 'the permission this needs';\n return `This API key does not have ${permission}. Create a key that includes it in Fload: Settings \u2192 API keys.`;\n}\n", "/**\n * ASO (App Store Optimization) tools for MCP\n * Tools: get_aso_summary, get_aso_recommendations, get_aso_keywords,\n * get_aso_experiments, get_aso_locale_snapshots, trigger_aso_analysis\n */\n\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const getAsoSummarySchema = z.object({\n assetId: z.string().uuid().describe('App UUID to get ASO summary for'),\n});\n\nexport const getAsoRecommendationsSchema = z.object({\n assetId: z\n .string()\n .uuid()\n .describe('App UUID to get ASO recommendations for'),\n});\n\nexport const getAsoKeywordsSchema = z.object({\n assetId: z\n .string()\n .uuid()\n .describe('App UUID to get keyword intelligence for'),\n locale: z\n .string()\n .optional()\n .describe(\n 'Locale code to filter keywords (e.g., \"en-US\", \"de-DE\"). Returns all locales if omitted.'\n ),\n});\n\nexport const getAsoExperimentsSchema = z.object({\n assetId: z.string().uuid().describe('App UUID to list ASO experiments for'),\n status: z\n .enum([\n 'proposed',\n 'approved',\n 'applied',\n 'measuring',\n 'completed',\n 'reverted',\n ])\n .optional()\n .describe('Filter experiments by status'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .default(20)\n .describe('Maximum number of experiments to return'),\n cursor: z\n .string()\n .optional()\n .describe('Pagination cursor from a previous response (meta.nextCursor)'),\n});\n\nexport const getAsoLocaleSnapshotsSchema = z.object({\n assetId: z.string().uuid().describe('App UUID to get locale snapshots for'),\n store: z\n .enum(['ios', 'android'])\n .default('ios')\n .describe('Which store listing to read'),\n locale: z\n .string()\n .optional()\n .describe(\n 'Filter to a single locale (e.g. \"en-US\"). Returns all locales if omitted.'\n ),\n view: z\n .enum(['latest', 'history'])\n .default('latest')\n .describe(\n '\"latest\" (default) = newest snapshot per (locale, type); \"history\" = raw revisions newest first'\n ),\n limit: z\n .number()\n .int()\n .min(1)\n .max(500)\n .optional()\n .describe('Maximum snapshot rows to return (newest first)'),\n});\n\nexport const triggerAsoAnalysisSchema = z.object({\n assetId: z.string().uuid().describe('App UUID to trigger ASO analysis for'),\n});\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * Get ASO score, health, and overview for an app\n */\nexport async function getAsoSummary(\n input: z.input<typeof getAsoSummarySchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get(\n `/api/assets/${input.assetId}/aso/summary`\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Get current ASO recommendations (title, subtitle, keywords suggestions)\n */\nexport async function getAsoRecommendations(\n input: z.input<typeof getAsoRecommendationsSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get(\n `/api/assets/${input.assetId}/aso/recommendations`\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Get keyword rankings, search volume, and competitor data\n */\nexport async function getAsoKeywords(\n input: z.input<typeof getAsoKeywordsSchema>,\n client: FloadApiClient\n) {\n try {\n const params: Record<string, string | number | boolean | undefined> = {};\n if (input.locale) params.locale = input.locale;\n\n const response = await client.get(\n `/api/assets/${input.assetId}/aso/keyword-intelligence`,\n params\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * List ASO experiments with status filtering\n */\nexport async function getAsoExperiments(\n input: z.input<typeof getAsoExperimentsSchema>,\n client: FloadApiClient\n) {\n try {\n const params: Record<string, string | number | boolean | undefined> = {\n limit: input.limit,\n cursor: input.cursor,\n };\n if (input.status) params.status = input.status;\n\n const response = await client.get(\n `/api/assets/${input.assetId}/aso/experiments`,\n params\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Get current App Store/Google Play listing snapshots across all locales\n */\nexport async function getAsoLocaleSnapshots(\n input: z.input<typeof getAsoLocaleSnapshotsSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get(\n `/api/assets/${input.assetId}/aso/listing-snapshots`,\n {\n store: input.store,\n locale: input.locale,\n view: input.view,\n limit: input.limit,\n }\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Trigger a new ASO analysis run for an app\n */\nexport async function triggerAsoAnalysis(\n input: z.input<typeof triggerAsoAnalysisSchema>,\n client: FloadApiClient\n) {\n try {\n // The real route is /aso/refetch (re-pulls the listing + re-runs the\n // audit). /aso/analyze never existed.\n const response = await client.post(\n `/api/assets/${input.assetId}/aso/refetch`,\n { force: true }\n );\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson(response),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/** Read immutable per-object decisions and their source evidence. */\nexport const getAsoEvidenceSchema = z.object({ assetId: z.string().uuid() });\nexport async function getAsoEvidence(\n input: z.input<typeof getAsoEvidenceSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get(\n `/api/assets/${input.assetId}/aso/methodology`\n );\n return {\n content: [{ type: 'text' as const, text: formatAsJson(response) }],\n };\n } catch (error) {\n return {\n content: [{ type: 'text' as const, text: formatError(error) }],\n isError: true,\n };\n }\n}\n", "/**\n * Chat tools for MCP\n * Tools: list_conversations, get_conversation_messages, send_chat_message\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { z } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { formatAsJson, formatError } from '../lib/format.js';\n\n// =============================================================================\n// SCHEMAS\n// =============================================================================\n\nexport const listConversationsSchema = z.object({\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .default(20)\n .describe('Maximum number of conversations to return'),\n});\n\nexport const getConversationMessagesSchema = z.object({\n conversationId: z\n .string()\n .uuid()\n .describe('The conversation UUID to get messages for'),\n});\n\nexport const sendChatMessageSchema = z.object({\n message: z.string().describe('The message to send to the AI chat'),\n conversationId: z\n .string()\n .uuid()\n .optional()\n .describe(\n 'Existing conversation UUID to continue. Starts a new conversation if omitted.'\n ),\n agentType: z\n .string()\n .optional()\n .describe(\n 'Agent type to use for the conversation (e.g., review, monitoring)'\n ),\n});\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\n/**\n * List chat conversations\n */\nexport async function listConversations(\n input: z.input<typeof listConversationsSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get('/api/chat/conversations', {\n limit: input.limit,\n });\n const conversations = response.data || response.conversations || response;\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n totalConversations: Array.isArray(conversations)\n ? conversations.length\n : 0,\n conversations,\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * Get messages in a conversation\n */\nexport async function getConversationMessages(\n input: z.input<typeof getConversationMessagesSchema>,\n client: FloadApiClient\n) {\n try {\n const response = await client.get(\n `/api/chat/messages/${input.conversationId}`\n );\n const messages = response.data || response.messages || response;\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n conversationId: input.conversationId,\n totalMessages: Array.isArray(messages) ? messages.length : 0,\n messages,\n }),\n },\n ],\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * FLO-2669: the words the Fload app says for an answer in a new\n * organization's free first conversation (the API's\n * `@packages/shared-types/chat/free-conversation`; this package is published\n * on its own, so it keeps a copy, checked against the API's in its tests).\n */\nexport const FREE_CONVERSATION_LABEL = 'Free: your first conversation';\nexport const FREE_CONVERSATION_ENDED_NOTICE =\n 'Your free first conversation has ended; messages now use credits.';\n\n/**\n * What an answer cost, from its `data-usage` part: the credits it used, or\n * that the organization's free first conversation carried it. Null when the\n * stream said neither (an admin chat, or an older API).\n */\nexport type ChatAnswerCost =\n | { free: false; credits: number }\n | { free: true; label: string; messagesLeft: number; notice?: string };\n\nfunction answerCostOf(data: unknown): ChatAnswerCost | null {\n if (!data || typeof data !== 'object') return null;\n const usage = data as {\n credits?: unknown;\n freeConversation?: { messagesLeft?: unknown; ended?: unknown };\n };\n const free = usage.freeConversation;\n if (free && typeof free.messagesLeft === 'number') {\n return {\n free: true,\n label: FREE_CONVERSATION_LABEL,\n messagesLeft: free.messagesLeft,\n ...(free.ended === true\n ? { notice: FREE_CONVERSATION_ENDED_NOTICE }\n : {}),\n };\n }\n return typeof usage.credits === 'number'\n ? { free: false, credits: usage.credits }\n : null;\n}\n\n/**\n * Extract the assistant's text (and the tools it used, and what the answer\n * cost) from an AI SDK UI-message SSE stream. Tolerant: unknown event types\n * are skipped.\n */\nexport function parseUiMessageStream(raw: string): {\n reply: string;\n toolsUsed: string[];\n cost: ChatAnswerCost | null;\n} {\n let reply = '';\n const toolsUsed: string[] = [];\n let cost: ChatAnswerCost | null = null;\n for (const line of raw.split('\\n')) {\n if (!line.startsWith('data:')) continue;\n const payload = line.slice(5).trim();\n if (!payload || payload === '[DONE]') continue;\n try {\n const event = JSON.parse(payload) as Record<string, unknown>;\n if (event.type === 'text-delta') {\n reply += String(event.delta ?? event.textDelta ?? '');\n } else if (\n typeof event.type === 'string' &&\n event.type === 'tool-input-start' &&\n typeof event.toolName === 'string'\n ) {\n toolsUsed.push(event.toolName);\n } else if (event.type === 'data-usage') {\n cost = answerCostOf(event.data) ?? cost;\n }\n } catch {\n // Non-JSON data line \u2014 skip.\n }\n }\n return { reply, toolsUsed, cost };\n}\n\n/**\n * Send a message to the AI chat. POST /api/chat speaks the AI SDK chat\n * protocol: the body is { id, messages: UIMessage[] } and the response is\n * a UI-message event stream, not JSON.\n */\nexport async function sendChatMessage(\n input: z.input<typeof sendChatMessageSchema>,\n client: FloadApiClient\n) {\n try {\n const conversationId = input.conversationId ?? randomUUID();\n\n // POST /api/chat treats the client-sent messages array as the FULL\n // model context \u2014 continuing a conversation means replaying its prior\n // turns, exactly as the web client does.\n let priorMessages: Array<Record<string, unknown>> = [];\n if (input.conversationId) {\n // The route defaults to the OLDEST 50 messages (ascending order,\n // offset 0) \u2014 fetch generously and keep the most recent turns so\n // long conversations continue from where they left off.\n const history = await client.get<{\n data?: Array<{\n id: string;\n role: string;\n parts?: Array<{ type?: string; text?: string }>;\n }>;\n }>(`/api/chat/messages/${input.conversationId}`, { limit: 1000 });\n for (const message of history.data ?? []) {\n const textParts = (message.parts ?? []).filter(\n part => part.type === 'text' && typeof part.text === 'string'\n );\n if (textParts.length === 0) continue;\n priorMessages.push({\n id: message.id,\n role: message.role,\n parts: textParts,\n });\n }\n priorMessages = priorMessages.slice(-100);\n }\n\n const body: Record<string, unknown> = {\n id: conversationId,\n messages: [\n ...priorMessages,\n {\n id: randomUUID(),\n role: 'user',\n parts: [{ type: 'text', text: input.message }],\n },\n ],\n };\n if (input.agentType) {\n body.agentContext = {\n agentId: null,\n agentType: input.agentType,\n agentName: input.agentType,\n surface: 'mcp',\n };\n }\n\n const raw = await client.postStream('/api/chat', body);\n const { reply, toolsUsed, cost } = parseUiMessageStream(raw);\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAsJson({\n conversationId,\n reply: reply || 'The assistant returned no text response.',\n toolsUsed,\n // FLO-2669: the credits the answer used, or that it was free.\n ...(cost ? { cost } : {}),\n tip: 'Pass this conversationId to continue the conversation or to get_conversation_messages for the full transcript.',\n }),\n },\n ],\n ...(reply ? {} : { isError: true }),\n };\n } catch (error) {\n return {\n content: [\n {\n type: 'text' as const,\n text: formatError(error),\n },\n ],\n isError: true,\n };\n }\n}\n", "/**\n * Tool registry for Fload MCP Server.\n *\n * Barrel re-exports every tool handler + schema, plus `registerTools`\n * which both the stdio entry (@fload-ai/mcp for local Claude Desktop /\n * Cursor / VS Code) and the HTTP transport (mounted at /mcp on the\n * Fload API for remote OAuth-authenticated agents) call to populate an\n * McpServer instance. Adding a tool in one place wires it into both.\n *\n * Every tool carries a `title` + either `readOnlyHint` or\n * `destructiveHint` (or both explicitly false for reversible side\n * effects). Anthropic's connector marketplace enforces this \u2014 tools\n * missing annotations fail review. See\n * https://modelcontextprotocol.io/specification/server/tools for the\n * annotation semantics.\n */\nimport type {\n McpServer,\n ToolCallback,\n} from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport type { z, ZodObject, ZodRawShape } from 'zod';\nimport type { FloadApiClient } from '../api-client.js';\nimport { RateLimiter } from '../rate-limiter.js';\n\nexport * from './apps.js';\nexport * from './reviews.js';\nexport * from './analytics.js';\nexport * from './download-impact.js';\nexport * from './agents.js';\nexport * from './ads.js';\nexport * from './dashboard.js';\nexport * from './actions.js';\nexport * from './aso.js';\nexport * from './chat.js';\n\nimport {\n listAppsSchema,\n listApps,\n getAppDetailsSchema,\n getAppDetails,\n} from './apps.js';\nimport {\n getReviewsSchema,\n getReviews,\n generateReviewReplySchema,\n generateReviewReply,\n sendReviewReplySchema,\n sendReviewReply,\n translateReviewSchema,\n translateReview,\n} from './reviews.js';\nimport {\n discoverMetricsSchema,\n discoverMetrics,\n getMetricsSchema,\n getMetrics,\n discoverDimensionsSchema,\n discoverDimensions,\n} from './analytics.js';\nimport {\n getDownloadImpactSchema,\n getDownloadImpact,\n} from './download-impact.js';\nimport {\n listAgentsSchema,\n listAgents,\n getAgentDetailsSchema,\n getAgentDetails,\n getAgentRunHistorySchema,\n getAgentRunHistory,\n triggerAgentRunSchema,\n triggerAgentRun,\n pauseAgentSchema,\n pauseAgent,\n resumeAgentSchema,\n resumeAgent,\n getAgentActivitySchema,\n getAgentActivity,\n} from './agents.js';\nimport {\n listConversationsSchema,\n listConversations,\n getConversationMessagesSchema,\n getConversationMessages,\n sendChatMessageSchema,\n sendChatMessage,\n} from './chat.js';\nimport { getAdsPerformanceSchema, getAdsPerformance } from './ads.js';\nimport {\n getDashboardOverviewSchema,\n getDashboardOverview,\n} from './dashboard.js';\nimport {\n listPendingActionsSchema,\n listPendingActions,\n approveActionSchema,\n approveAction,\n rejectActionSchema,\n rejectAction,\n checkActionNowSchema,\n checkActionNow,\n renameCustomPageActionSchema,\n renameCustomPageAction,\n} from './actions.js';\nimport {\n getAsoEvidenceSchema,\n getAsoEvidence,\n getAsoSummarySchema,\n getAsoSummary,\n getAsoRecommendationsSchema,\n getAsoRecommendations,\n getAsoKeywordsSchema,\n getAsoKeywords,\n getAsoExperimentsSchema,\n getAsoExperiments,\n getAsoLocaleSnapshotsSchema,\n getAsoLocaleSnapshots,\n triggerAsoAnalysisSchema,\n triggerAsoAnalysis,\n} from './aso.js';\n\nexport interface RegisterToolsOptions {\n /**\n * Custom rate limiter. Defaults to 100 requests/minute global.\n * The HTTP transport passes one scoped per-user so concurrent Claude/\n * ChatGPT/Cursor agents don't share a quota with each other.\n */\n rateLimiter?: RateLimiter;\n}\n\n/**\n * MCP tool annotations per spec. At least one of `readOnlyHint` or\n * `destructiveHint` must be set to satisfy Anthropic's directory check.\n * For reversible state changes (pause agent, approve a draft) we\n * set both to `false` explicitly.\n */\ninterface FloadToolAnnotations {\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n}\n\ntype FloadToolHandler<T extends ZodRawShape> = (\n input: z.infer<ZodObject<T>>,\n client: FloadApiClient\n) => Promise<CallToolResult>;\n\nexport function registerTools(\n server: McpServer,\n client: FloadApiClient,\n options: RegisterToolsOptions = {}\n): void {\n const rateLimiter = options.rateLimiter ?? new RateLimiter(100, 60_000);\n\n function wrapTool<T extends ZodRawShape>(\n handler: FloadToolHandler<T>\n ): ToolCallback<ZodObject<T>> {\n const callback: ToolCallback<ZodObject<T>> = async input => {\n const rateCheck = rateLimiter.check('default');\n if (!rateCheck.allowed) {\n return {\n content: [\n {\n type: 'text' as const,\n text: `Rate limit exceeded. Try again in ${Math.ceil(\n rateCheck.retryAfterMs / 1000\n )}s. Limit: 100 requests/minute.`,\n },\n ],\n isError: true,\n };\n }\n return handler(input, client);\n };\n return callback;\n }\n\n // Helper: register a tool with the annotations the marketplace expects.\n // Keeps each tool one call so a reviewer can eyeball the whole surface.\n function tool<T extends ZodRawShape>(\n name: string,\n title: string,\n description: string,\n schema: ZodObject<T>,\n handler: FloadToolHandler<T>,\n annotations: FloadToolAnnotations\n ) {\n server.registerTool<ZodRawShape, ZodObject<T>>(\n name,\n {\n title,\n description,\n inputSchema: schema,\n annotations: { title, ...annotations },\n },\n wrapTool(handler)\n );\n }\n\n // \u2500\u2500 APPS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'list_apps',\n 'List apps',\n 'List all mobile apps in your Fload organization. Returns app metadata including name, bundle ID, platform (iOS/Android), icon URL, and category.',\n listAppsSchema,\n listApps,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_app_details',\n 'Get app details',\n '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.',\n getAppDetailsSchema,\n getAppDetails,\n { readOnlyHint: true, openWorldHint: false }\n );\n\n // \u2500\u2500 REVIEWS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'get_reviews',\n 'Get reviews',\n '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.',\n getReviewsSchema,\n getReviews,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'generate_review_reply',\n 'Generate review reply (AI draft)',\n '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.',\n generateReviewReplySchema,\n generateReviewReply,\n { readOnlyHint: false, destructiveHint: false, openWorldHint: true }\n );\n tool(\n 'send_review_reply',\n 'Send review reply',\n '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.',\n sendReviewReplySchema,\n sendReviewReply,\n { readOnlyHint: false, destructiveHint: true, openWorldHint: true }\n );\n tool(\n 'translate_review',\n 'Translate review',\n '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.',\n translateReviewSchema,\n translateReview,\n { readOnlyHint: true, openWorldHint: true }\n );\n\n // \u2500\u2500 ANALYTICS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'discover_metrics',\n 'Discover available metrics',\n \"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.\",\n discoverMetricsSchema,\n discoverMetrics,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_metrics',\n 'Get metrics',\n \"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.\",\n getMetricsSchema,\n getMetrics,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'discover_dimensions',\n 'Discover available dimensions',\n 'Discover available dimensions for breaking down metrics (e.g., country, platform, app version, campaign). Optionally get the available values for a specific dimension.',\n discoverDimensionsSchema,\n discoverDimensions,\n { readOnlyHint: true, openWorldHint: false }\n );\n\n tool(\n 'get_download_impact',\n 'Get what Fload changed on downloads',\n \"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.\",\n getDownloadImpactSchema,\n getDownloadImpact,\n { readOnlyHint: true, openWorldHint: false }\n );\n\n // \u2500\u2500 AGENTS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'list_agents',\n 'List agents',\n \"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.\",\n listAgentsSchema,\n listAgents,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_agent_details',\n 'Get agent details',\n 'Get detailed configuration and status for a specific agent type. For the review agent, returns per-asset settings (mode, tone, custom instructions).',\n getAgentDetailsSchema,\n getAgentDetails,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_agent_run_history',\n 'Get agent run history',\n 'Get run history for a specific agent type. Returns run status, timing, and error details.',\n getAgentRunHistorySchema,\n getAgentRunHistory,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'trigger_agent_run',\n 'Trigger agent run',\n '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.',\n triggerAgentRunSchema,\n triggerAgentRun,\n { readOnlyHint: false, destructiveHint: false, openWorldHint: true }\n );\n tool(\n 'pause_agent',\n 'Pause agent',\n '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.',\n pauseAgentSchema,\n pauseAgent,\n {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n }\n );\n tool(\n 'resume_agent',\n 'Resume agent',\n '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.',\n resumeAgentSchema,\n resumeAgent,\n {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n }\n );\n tool(\n 'get_agent_activity',\n 'Get agent activity',\n '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.',\n getAgentActivitySchema,\n getAgentActivity,\n { readOnlyHint: true, openWorldHint: false }\n );\n\n // \u2500\u2500 ADS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'get_ads_performance',\n 'Get ads performance',\n '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).',\n getAdsPerformanceSchema,\n getAdsPerformance,\n { readOnlyHint: true, openWorldHint: false }\n );\n\n // \u2500\u2500 DASHBOARD \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'get_dashboard_overview',\n 'Get dashboard overview',\n 'Get an aggregated dashboard overview for the organization. Returns portfolio summary (apps, valuations, ratings), data connector health status, and alerts (pending review drafts).',\n getDashboardOverviewSchema,\n getDashboardOverview,\n { readOnlyHint: true, openWorldHint: false }\n );\n\n // \u2500\u2500 PENDING ACTIONS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'list_pending_actions',\n 'List pending actions',\n '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.',\n listPendingActionsSchema,\n listPendingActions,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'approve_action',\n 'Approve pending action',\n '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).',\n approveActionSchema,\n approveAction,\n { readOnlyHint: false, destructiveHint: true, openWorldHint: true }\n );\n tool(\n 'reject_action',\n 'Reject pending action',\n \"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.\",\n rejectActionSchema,\n rejectAction,\n { readOnlyHint: false, destructiveHint: true, openWorldHint: false }\n );\n tool(\n 'check_action_now',\n 'Check a change in the store now',\n '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.',\n checkActionNowSchema,\n checkActionNow,\n { readOnlyHint: false, destructiveHint: false, openWorldHint: true }\n );\n tool(\n 'rename_custom_page_action',\n 'Rename a custom product page request and send it',\n '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.',\n renameCustomPageActionSchema,\n renameCustomPageAction,\n { readOnlyHint: false, destructiveHint: true, openWorldHint: true }\n );\n\n // \u2500\u2500 ASO \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'get_aso_summary',\n 'Get ASO summary',\n '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.',\n getAsoSummarySchema,\n getAsoSummary,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_aso_recommendations',\n 'Get ASO recommendations',\n '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.',\n getAsoRecommendationsSchema,\n getAsoRecommendations,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_aso_evidence',\n 'Get ASO decisions and evidence',\n '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.',\n getAsoEvidenceSchema,\n getAsoEvidence,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_aso_keywords',\n 'Get ASO keywords',\n '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.',\n getAsoKeywordsSchema,\n getAsoKeywords,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_aso_experiments',\n 'Get ASO experiments',\n '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.',\n getAsoExperimentsSchema,\n getAsoExperiments,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_aso_locale_snapshots',\n 'Get ASO locale snapshots',\n '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.',\n getAsoLocaleSnapshotsSchema,\n getAsoLocaleSnapshots,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'trigger_aso_analysis',\n 'Trigger ASO analysis',\n \"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.\",\n triggerAsoAnalysisSchema,\n triggerAsoAnalysis,\n { readOnlyHint: false, destructiveHint: false, openWorldHint: true }\n );\n\n // \u2500\u2500 CHAT \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n tool(\n 'list_conversations',\n 'List conversations',\n '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.',\n listConversationsSchema,\n listConversations,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'get_conversation_messages',\n 'Get conversation messages',\n 'Get all messages in a specific chat conversation. Returns the full message history including user messages and AI responses with timestamps and roles.',\n getConversationMessagesSchema,\n getConversationMessages,\n { readOnlyHint: true, openWorldHint: false }\n );\n tool(\n 'send_chat_message',\n 'Send chat message',\n \"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).\",\n sendChatMessageSchema,\n sendChatMessage,\n { readOnlyHint: false, destructiveHint: false, openWorldHint: true }\n );\n}\n"],
5
+ "mappings": ";AAAO,IAAM,cAAN,MAAkB;AAAA,EAGvB,YACU,WAAmB,KACnB,WAAmB,KAC3B;AAFQ;AACA;AAAA,EACP;AAAA,EAFO;AAAA,EACA;AAAA,EAJF,QAA+B,oBAAI,IAAI;AAAA,EAO/C,MAAM,KAIJ;AACA,UAAM,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AO,eAAe,KAAK;AAAA,EACrE;AACF;",
6
6
  "names": ["app", "z", "z", "z", "z", "response", "z", "z", "z", "z", "response", "z", "z", "z", "z", "z", "z", "applied", "z", "z", "randomUUID", "z", "z", "randomUUID"]
7
7
  }