@adport/mcp 0.12.2 → 0.13.1

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.
package/dist/bin.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  assembleRuntime,
4
4
  runStdioServer
5
- } from "./chunk-LLAXR25X.js";
5
+ } from "./chunk-TEP7TOPQ.js";
6
6
 
7
7
  // src/bin.ts
8
8
  var includeRawTools = process.argv.includes("--raw-api-tools");
@@ -22,7 +22,7 @@ import { createOpenAIModule } from "@adport/provider-openai";
22
22
  // package.json
23
23
  var package_default = {
24
24
  name: "@adport/mcp",
25
- version: "0.12.2",
25
+ version: "0.13.1",
26
26
  description: "adport MCP server \u2014 the open control plane for paid media",
27
27
  license: "Apache-2.0",
28
28
  type: "module",
@@ -73,7 +73,7 @@ var package_default = {
73
73
  jsdom: "26.1.0",
74
74
  tsup: "^8.3.0",
75
75
  typescript: "^5.8.0",
76
- vitest: "^4.1.10",
76
+ vitest: "^5.1.1",
77
77
  "@modelcontextprotocol/client": "^2.4.0"
78
78
  },
79
79
  repository: {
@@ -680,6 +680,7 @@ ${RECORD_COLLECTION_UI}
680
680
  }
681
681
  function recordPayload(data) {
682
682
  if(object(data)&&Array.isArray(data.records))return {records:data.records};
683
+ if(data._adport?.tool==='google_custom_conversion_goals' && Array.isArray(data.goals))return {records:data.goals};
683
684
  const value=data.value ?? data.data ?? data.result ?? data;
684
685
  if(!object(value))return value;
685
686
  for(const key of ['keyword','audience','pixel','capi_integration','mobile_app','dataset','board','campaign','ad_group','ad','asset','customer_list'])if(object(value[key]))return value[key];
@@ -767,6 +768,13 @@ ${RECORD_COLLECTION_UI}
767
768
  workflowCell(entityHeaders[i],esc(workflowText(value)||(i===0?'Record '+(index+1):'—')),i===0)).join('')+'</tr>';
768
769
  }
769
770
 
771
+ function campaignGoalSettings(data) {
772
+ if(data._adport?.tool!=='google_custom_conversion_goals'||!Array.isArray(data.campaigns)||!data.campaigns.length)return '';
773
+ const rows=data.campaigns.map(campaign=>'<article class="record-row"><div class="record-heading"><strong>'+
774
+ esc(campaign.name||campaign.campaign_id)+'</strong></div><p class="operation-note">'+esc(campaign.summary)+'</p></article>').join('');
775
+ return '<section aria-label="Campaign goal settings" data-campaign-goals><h3>Campaign goal settings</h3>'+rows+'</section>';
776
+ }
777
+
770
778
  function renderRecordPages(message='') {
771
779
  const pages=recordPages,area=app.querySelector('[data-record-pages]');if(!pages||!area)return;
772
780
  const next=pages.rows.length<1000 && galleryNext(pages.meta);
@@ -798,6 +806,7 @@ ${RECORD_COLLECTION_UI}
798
806
  pages.seen.add(key);pages.meta={...meta,...(!added||pages.rows.length>=1000?{next:undefined}:{})};pages.data=value;
799
807
  state.hasLocalResult=true;state.result={structuredContent:{...value,records:pages.rows.slice(),_adport:pages.meta}};
800
808
  const notes=app.querySelector('.record-notes');if(notes)notes.innerHTML=notices(value);
809
+ const settings=app.querySelector('[data-campaign-goals]');if(settings)settings.outerHTML=campaignGoalSettings(value);
801
810
  const details=app.querySelector('[data-record-details]');if(details){details.querySelector('summary').textContent='Details · '+pages.rows.length+' loaded';details.querySelector('pre').textContent=JSON.stringify({loaded_records:pages.rows,latest_page:Object.fromEntries(Object.entries(value).filter(([field])=>field!=='_adport'))},null,2);}
802
811
  pages.busy=false;renderRecordPages(pages.rows.length>=1000?'Showing 1,000 records. Ask your assistant if you need more results.':!added&&rows.length?'No new records were returned. Ask your assistant for a fresh view.':'');
803
812
  }catch(error){if(recordPages===pages){pages.busy=false;renderRecordPages(error?.message||'Could not load more records.');}}
@@ -819,8 +828,8 @@ ${RECORD_COLLECTION_UI}
819
828
  const markup=shown.map((row,index)=>recordEntryMarkup(row,index,displayMeta,table)).join('');
820
829
  const content=rows.length?table?'<div class="workflow-scroll" role="region" aria-label="Returned records" tabindex="0"><table class="workflow-table workflow-stack" role="table">'+workflowHeader(entityHeaders)+
821
830
  '<tbody data-record-list role="rowgroup">'+markup+'</tbody></table></div>':
822
- '<div class="record-list" data-record-list role="region" aria-label="Returned records" tabindex="0">'+markup+'</div>':'<p class="operation-note">No results returned.</p>';
823
- app.innerHTML=chrome(operationHeader(title,scope,meta.provider)+'<div class="record-notes">'+notices(data)+'</div>'+content+(rows.length>1000?'<p class="operation-note">Showing 1,000 of '+rows.length+' records. The full response is in Details.</p>':'')+'<div data-record-pages></div><details data-record-details><summary>Details'+(entries?' · '+entries.length+' results':'')+'</summary><pre>'+esc(JSON.stringify(clean,null,2))+'</pre></details>','');
831
+ '<div class="record-list" data-record-list role="region" aria-label="Returned records" tabindex="0">'+markup+'</div>':'<p class="operation-note">'+(meta.tool==='google_custom_conversion_goals'?'No custom conversion goals returned.':'No results returned.')+'</p>';
832
+ app.innerHTML=chrome(operationHeader(title,scope,meta.provider)+'<div class="record-notes">'+notices(data)+'</div>'+content+(rows.length>1000?'<p class="operation-note">Showing 1,000 of '+rows.length+' records. The full response is in Details.</p>':'')+'<div data-record-pages></div>'+campaignGoalSettings(data)+'<details data-record-details><summary>Details'+(entries?' · '+entries.length+' results':'')+'</summary><pre>'+esc(JSON.stringify(clean,null,2))+'</pre></details>','');
824
833
  if(Array.isArray(entries)&&rows.length&&galleryNext(meta)){
825
834
  recordPages={scope:galleryScope(meta),meta,data,table,rows:rows.slice(0,1000),items:new Map(),seen:new Set([galleryStable(meta.refresh.arguments)]),busy:false};
826
835
  const nodes=app.querySelectorAll('[data-record-list]>*');recordPages.rows.forEach((row,index)=>{const identity=object(row)&&(typeof row.id==='string'&&row.id||typeof row.id==='number'&&Number.isSafeInteger(row.id))?'id:'+String(row.id):galleryStable(meta.refresh.arguments)+':'+index;recordPages.items.set(identity,{row,index,node:nodes[index]});});
@@ -1226,6 +1235,10 @@ var OPERATION_RECONCILIATION_UI = String.raw`
1226
1235
 
1227
1236
  // src/operation-ui.ts
1228
1237
  var OPERATION_UI_SCRIPT = String.raw`
1238
+ const bulkNegativeKeywordTools = new Set(['google_create_negative_keyword_list','google_update_negative_keyword_list','google_link_negative_keyword_list','google_add_campaign_negative_keywords']);
1239
+ function callOperationTool(tool,args) {
1240
+ return callTool(tool,args,bulkNegativeKeywordTools.has(tool) ? 180000 : undefined);
1241
+ }
1229
1242
  const attempts = new Map(), pendingRequests = new Map();
1230
1243
  let cancelHold = () => {}, expiryTimer;
1231
1244
  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -1306,7 +1319,7 @@ var OPERATION_UI_SCRIPT = String.raw`
1306
1319
  const previewArgs={...args};delete previewArgs.pending_operation_id;
1307
1320
  attempt.refreshing=true;render(state.result);
1308
1321
  try {
1309
- const result=await callTool(tool,previewArgs),value=resultData(result),meta=value._adport;
1322
+ const result=await callOperationTool(tool,previewArgs),value=resultData(result),meta=value._adport;
1310
1323
  if(result?.isError || value.error) throw new Error(value.message || 'The connection is not ready. Finish account selection before refreshing again.');
1311
1324
  if(value.applied!==false || value.status!=='pending_validation' || typeof value.pending_operation_id!=='string'
1312
1325
  || value.pending_operation_id===pending || meta?.tool!==tool || meta.context?.project_id!==attempt.recovery.project_id
@@ -1382,7 +1395,7 @@ var OPERATION_UI_SCRIPT = String.raw`
1382
1395
  return 'unconfirmed';
1383
1396
  }
1384
1397
  function callHostTool(tool,args) {
1385
- return callTool(tool,args).catch(error=>{throw new Error((error?.message || 'No confirmation arrived.')+' The write may have succeeded; check its status before retrying.');});
1398
+ return callOperationTool(tool,args).catch(error=>{throw new Error((error?.message || 'No confirmation arrived.')+' The write may have succeeded; check its status before retrying.');});
1386
1399
  }
1387
1400
  async function approve(tool,args,pending,expires) {
1388
1401
  if(attempts.has(pending) || pendingOf(state.result)!==pending) return;
@@ -1524,23 +1537,6 @@ var GAQL_REPORT_UI = String.raw`
1524
1537
  return human(human(path.replace(/^segments\./, '')).toLowerCase()).replace(/\bid\b/i, 'ID');
1525
1538
  }
1526
1539
 
1527
- const gaqlMoneyFormats = new Map();
1528
- function gaqlAmount(amount, currency) {
1529
- const locale = state.host.locale || 'en', key = locale + '/' + (currency || '');
1530
- if (!gaqlMoneyFormats.has(key)) {
1531
- const digits = currency ? new Intl.NumberFormat(locale, {style:'currency', currency}).resolvedOptions().maximumFractionDigits : 2;
1532
- gaqlMoneyFormats.set(key, {
1533
- format: new Intl.NumberFormat(locale, {minimumFractionDigits:digits, maximumFractionDigits:digits}),
1534
- unit: 10 ** -digits
1535
- });
1536
- }
1537
- const {format, unit} = gaqlMoneyFormats.get(key);
1538
- if (Number(amount) !== 0 && Math.abs(Number(amount)) < unit) {
1539
- return Number(amount) < 0 ? '>' + format.format(-unit) : '<' + format.format(unit);
1540
- }
1541
- return format.format(amount);
1542
- }
1543
-
1544
1540
  function gaqlHasTrend(points, dimensions, paths) {
1545
1541
  // A dated series must refer to the same returned entity and breakdown on every date.
1546
1542
  if (points.length > 366 || new Set(points.map(point => point.date)).size < 2) return false;
@@ -1611,6 +1607,134 @@ var GAQL_REPORT_UI = String.raw`
1611
1607
  }
1612
1608
  `;
1613
1609
 
1610
+ // src/meta-insights-ui.ts
1611
+ var META_INSIGHTS_UI = String.raw`
1612
+ const metaBreakdownLabels = {
1613
+ publisher_platform:'Platform', platform_position:'Placement', impression_device:'Impression device', device_platform:'Device platform',
1614
+ age:'Age', gender:'Gender', country:'Country', region:'Region', dma:'DMA', zip:'ZIP', product_id:'Product ID',
1615
+ hourly_stats_aggregated_by_advertiser_time_zone:'Hour (ad account)', hourly_stats_aggregated_by_audience_time_zone:'Hour (audience)',
1616
+ image_asset:'Image', video_asset:'Video', title_asset:'Headline', body_asset:'Ad text', ad_format_asset:'Ad format',
1617
+ objective:'Objective', buying_type:'Buying type', attribution_setting:'Attribution setting'
1618
+ };
1619
+ function metaBreakdownKeys(payload) {
1620
+ return [...new Set([...arr(payload?.breakdowns).filter(key => typeof key === 'string'), ...Object.keys(metaBreakdownLabels)])];
1621
+ }
1622
+ function metaBreakdownValue(key, value) {
1623
+ if (object(value)) return workflowText(value.name || value.text || value.title || value.id || value.hash);
1624
+ if (typeof value === 'boolean') return value ? 'Yes' : 'No';
1625
+ const text = workflowText(value);
1626
+ return ['publisher_platform','platform_position','impression_device','device_platform','gender'].includes(key) ? human(text) : text;
1627
+ }
1628
+ function metaEntityValues(rows, level) {
1629
+ const names = rows.map(row => workflowText(row[level + '_name'])), ids = rows.map(row => workflowText(row[level + '_id']));
1630
+ const byName = new Map();
1631
+ names.forEach((name, i) => {
1632
+ if (!byName.has(name)) byName.set(name, new Set());
1633
+ byName.get(name).add(ids[i]);
1634
+ });
1635
+ return names.map((name, i) => name && ids[i] && byName.get(name).size > 1 ? name + ' (' + ids[i] + ')' : name || ids[i]);
1636
+ }
1637
+ function metaMetricLabel(key) {
1638
+ const [kind, action] = key.split(' · ');
1639
+ if (!action) return nativeReportLabel(key);
1640
+ const event = action.replaceAll('_', ' ');
1641
+ if (kind === 'actions' && /(?:^|_)(?:purchase|lead|install|click|registration)$/.test(action)) return human(event) + 's';
1642
+ if (kind === 'action_values') return human(event) + ' value';
1643
+ if (kind === 'cost_per_action_type') return 'Cost per ' + event;
1644
+ if (kind === 'purchase_roas') return human(event) + ' ROAS';
1645
+ return nativeReportLabel(key);
1646
+ }
1647
+
1648
+ function metaInsightsReport(records, points, payload) {
1649
+ const rows = records.map(record => record?.native || {}), dimensions = [];
1650
+ const add = (label, values) => {
1651
+ if (values.some(Boolean)) dimensions.push({label, values, shared:values.every(value => value === values[0])});
1652
+ };
1653
+ for (const [level, label] of [['account','Account'],['campaign','Campaign'],['adset','Ad set'],['ad','Ad']]) {
1654
+ add(label, metaEntityValues(rows, level));
1655
+ }
1656
+ for (const key of metaBreakdownKeys(payload)) {
1657
+ if (rows.some(row => Object.hasOwn(row, key))) add(Object.hasOwn(metaBreakdownLabels,key) ? metaBreakdownLabels[key] : recordLabel(key), rows.map(row => metaBreakdownValue(key, row[key])));
1658
+ }
1659
+ const seriesDimensions = dimensions.filter(dimension => !dimension.shared);
1660
+ const locale = state.host.locale || 'en';
1661
+ const dates = new Intl.DateTimeFormat(locale, {month:'short', day:'numeric', year:'numeric', timeZone:'UTC'});
1662
+ const periodLabels = new Map();
1663
+ const periods = rows.map(row => {
1664
+ const start = reportDate(row.date_start), end = reportDate(row.date_stop), key = [start,end].join('/');
1665
+ if (!periodLabels.has(key)) {
1666
+ const from = start && new Date(start), to = end && new Date(end);
1667
+ const period = from && to && from <= to ? dates.formatRange(from, to) :
1668
+ from && !to ? 'From ' + dates.format(from) : to && !from ? 'Through ' + dates.format(to) : '';
1669
+ periodLabels.set(key, period);
1670
+ }
1671
+ return periodLabels.get(key);
1672
+ });
1673
+ add('Period', periods);
1674
+
1675
+ const varying = dimensions.filter(dimension => !dimension.shared), scope = dimensions.filter(dimension => dimension.shared).map(dimension => dimension.values[0]);
1676
+ const joined = (columns, i) => columns.map(column => column.values[i] || '—').join(' · ');
1677
+ const label = varying.map(dimension => dimension.label).join(' / ');
1678
+ const title = varying.length ? 'Performance by ' + varying.map(dimension => dimension.label.toLowerCase()).join(' and ') : 'Meta ad performance';
1679
+ const currencies = new Set(records.map(record => record?.currency || ''));
1680
+ const numeric = new Intl.NumberFormat(locale, {maximumFractionDigits:2});
1681
+ const fieldsByRow = points.map(point => {
1682
+ const fields = new Map();
1683
+ for (const field of point.fields) {
1684
+ const display = field.shortDisplay ?? (field.value === null ? field.display : numeric.format(field.display));
1685
+ const suffix = /(?:^|_)ctr$/.test(field.key) ? '%' : field.key.startsWith('purchase_roas · ') ? '×' : '';
1686
+ const shortDisplay = display + (field.value !== null ? suffix : '');
1687
+ fields.set(field.key, fields.has(field.key) ? {...field, value:null, shortDisplay:'See Details'} :
1688
+ {...field, label:metaMetricLabel(field.key), shortDisplay, display:shortDisplay + (field.unit ? ' ' + field.unit : '')});
1689
+ }
1690
+ return fields;
1691
+ });
1692
+ const keys = [...new Set(fieldsByRow.flatMap(fields => [...fields.keys()]))];
1693
+ const priority = key => /^(?:actions|purchase_roas|cost_per_action_type) · (?:.*[_.])?(?:purchase|lead|install|registration)$/.test(key) ? 5 : reportMetricPriority(key);
1694
+ keys.sort((a,b) => priority(a) - priority(b));
1695
+ const isMoney = key => nativeReportMoneyField(key, 'meta');
1696
+ if (keys.some(isMoney) && currencies.has('')) scope.push('Currency unavailable');
1697
+ const subject = scope.join(' · ');
1698
+ const view = html => ({title, subject, html});
1699
+ if (!keys.length) return view(workflowNote('No metrics were returned for this selection.'));
1700
+ if (rows.length > 1 && !varying.length) return view(workflowNote('These rows have no distinguishing labels. Include a campaign, ad set, ad name, or a breakdown such as placement to compare them.'));
1701
+
1702
+ const shown = keys.slice(0,5), currency = currencies.size === 1 && records[0]?.currency;
1703
+ const metricHeader = key => metaMetricLabel(key) + (currency && isMoney(key) ? ' · ' + currency : '');
1704
+ const cell = (i, key) => {
1705
+ const field = fieldsByRow[i].get(key);
1706
+ if (!field) return '—';
1707
+ return field.shortDisplay + (field.value !== null && isMoney(key) && currencies.size > 1 ? ' ' + (records[i]?.currency || '(unknown currency)') : '');
1708
+ };
1709
+ const extra = keys.length > shown.length ? workflowNote((keys.length - shown.length) + ' more metrics in Details.') : '';
1710
+ if (rows.length === 1) return view('<div class="meta-insight-kpis">' + workflowFields(shown.map(key => [metricHeader(key),cell(0,key)])) + '</div>' + extra);
1711
+
1712
+ const names = rows.map((_,i) => joined(varying,i));
1713
+ const distinct = new Set(names).size === rows.length && rows.every((_,i) => varying.some(column => column.values[i]));
1714
+ const comparable = periods.every(period => period === periods[0]) && (!isMoney(keys[0]) || (currencies.size === 1 && (currency || new Set(rows.map(row => row.account_id)).size === 1)));
1715
+ const ranked = comparable && (keys[0] === 'spend' || keys.length === 1) && fieldsByRow.some(fields => available(fields.get(keys[0])?.value));
1716
+ const order = rows.map((_,i) => i);
1717
+ if (ranked) order.sort((a,b) => (fieldsByRow[b].get(keys[0])?.value ?? -Infinity) - (fieldsByRow[a].get(keys[0])?.value ?? -Infinity));
1718
+
1719
+ // Only join daily observations of an identified entity or breakdown.
1720
+ const series = rows.map((_,i) => joined(seriesDimensions,i) || joined(dimensions.filter(column => column.label !== 'Period'),i));
1721
+ const seriesCount = new Set(series).size;
1722
+ const trend = keys.length === 1 && distinct && rows.length <= 366 && dimensions.some(column => column.label !== 'Period') &&
1723
+ points.every(point => point.date) && new Set(points.map(point => point.date)).size > 1 && seriesCount <= 3 &&
1724
+ seriesCount < rows.length && (!isMoney(keys[0]) || currencies.size === 1);
1725
+ if (trend || (keys.length === 1 && ranked && distinct && rows.length <= 8)) {
1726
+ const pointsForChart = order.map(i => ({name:names[i], series:series[i], date:points[i].date, fields:[fieldsByRow[i].get(keys[0])].filter(Boolean)}));
1727
+ const chart = reportCharts(pointsForChart, {metric:keys[0], mode:trend ? undefined : 'bars', label:metaMetricLabel(keys[0]) + (trend ? ' over time' : '')});
1728
+ return {...view(chart.html), mount:chart.mount};
1729
+ }
1730
+ const note = distinct ? '' : workflowNote('Some rows share a label or are missing one. A more specific name, ID, or breakdown can distinguish them.');
1731
+ const values = order.slice(0,1000).map(i => [names[i], ...shown.map(key => cell(i,key))]);
1732
+ const table = workflowTable([label, ...shown.map(metricHeader)], values, title, {compact:true, sorted:ranked ? 1 : -1});
1733
+ const limit = values.length < rows.length ? workflowNote('Showing 1,000 of ' + rows.length.toLocaleString(locale) + ' returned rows. All rows are in Details.') : '';
1734
+ return view(note + '<div class="meta-insights-table">' + table + '</div>' + extra + limit);
1735
+ }
1736
+ `;
1737
+
1614
1738
  // src/native-report-ui.ts
1615
1739
  var NATIVE_REPORT_TOOLS = [
1616
1740
  "ga4_report",
@@ -1631,10 +1755,17 @@ var NATIVE_REPORT_TOOLS = [
1631
1755
  ];
1632
1756
  var NATIVE_REPORT_UI_STYLES = String.raw`
1633
1757
  .native-report-metrics { grid-template-columns:repeat(auto-fit,minmax(min(110px,100%),1fr)) }
1758
+ .meta-insights-table .workflow-table :is(th,td):not(:first-child) { text-align:right; white-space:nowrap }
1759
+ .meta-insights-table .workflow-table :is(th,td):first-child { min-width:8rem }
1760
+ .meta-insights-table [aria-sort="descending"]::after { content:' ↓'; color:var(--ink) }
1761
+ .meta-insight-kpis .record-fields { display:flex; flex-wrap:wrap; gap:14px 28px }
1762
+ .meta-insight-kpis .record-fields dt { color:var(--muted); font-size:11px }
1763
+ .meta-insight-kpis .record-fields dd { margin:4px 0 0; font-size:20px; font-weight:600; font-variant-numeric:tabular-nums }
1634
1764
  `;
1635
1765
  var NATIVE_REPORT_UI_SCRIPT = String.raw`
1636
1766
  const nativeReportTools=new Set(${JSON.stringify(NATIVE_REPORT_TOOLS)});
1637
1767
  ${GAQL_REPORT_UI}
1768
+ ${META_INSIGHTS_UI}
1638
1769
  function nativeReportDecimal(value,scale=0) {
1639
1770
  const text=typeof value==='number'&&Number.isFinite(value)?String(value):typeof value==='string'?value:'';
1640
1771
  if(!/^-?\d+(?:\.\d+)?$/.test(text))return null;
@@ -1665,7 +1796,7 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
1665
1796
  return typeof value==='string'||typeof value==='number'||typeof value==='boolean'?String(value):'—';
1666
1797
  }
1667
1798
  function nativeReportMoneyField(key,provider,moneyFields=[]) {
1668
- return moneyFields.includes(key)||/^(spend|revenue|cpc|cpm|cost_per_conversion|costInLocalCurrency|costInUsd|total_complete_payment_rate|conversion_.*_total_value)$|^(?:action_values|cost_per_action_type) · /i.test(key)||provider==='google'&&(/Micros$/.test(key)||/conversionsValue$/i.test(key));
1799
+ return moneyFields.includes(key)||/^(spend|revenue|cpc|cpm|cost_per_conversion|costInLocalCurrency|costInUsd|total_complete_payment_rate|conversion_.*_total_value)$|^(?:action_values|cost_per_action_type) · /i.test(key)||provider==='meta'&&/^(?:cpp$|cost_per_)/.test(key)||provider==='google'&&(/Micros$/.test(key)||/conversionsValue$/i.test(key));
1669
1800
  }
1670
1801
  function nativeReportScale(key,provider) { return provider==='reddit'?/total_value$/i.test(key)?2:6:provider==='google'&&/Micros$/.test(key)?6:0; }
1671
1802
  function reportBucket(value) {
@@ -1685,9 +1816,11 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
1685
1816
  const googleName=googleDimensions?.get(googleEntity);
1686
1817
  const bucket=dimensions.conversionLagBucket??dimensions.conversionOrAdjustmentLagBucket;
1687
1818
  const analyticsName=['ga4','gsc'].includes(provider)?Object.values(dimensions).filter(value=>typeof value==='string'&&value).join(' · '):null;
1688
- const name=bucket?reportBucket(bucket):googleName??analyticsName??first(names,[row,metrics,dimensions]) ?? first(ids,[row,dimensions]) ?? (provider==='google'?'Report':'Result '+(index+1));
1819
+ const identity=bucket?reportBucket(bucket):googleName??analyticsName??first(names,[row,metrics,dimensions])??first(ids,[row,dimensions]);
1820
+ const name=identity??(provider==='google'?'Report':provider==='meta'?'Reported metrics':'Result '+(index+1));
1689
1821
  const status=first(['entity_status','status'],[row]);
1690
1822
  const dimensionKeys=['date','day','week','month','stat_time_day','stat_time_hour','country','countryOrRegion','countryCode','country_code','country_id','deviceClass','device_platform','age','gender','platform','placement','insight_value','genre','BidMatchType','match_type','date_start','date_stop','start_time','end_time'];
1823
+ if(provider==='meta')dimensionKeys.push(...metaBreakdownKeys(payload));
1691
1824
  const context=[...new Set([...dimensionKeys.flatMap(key=>[row[key],dimensions[key]]),...(provider==='google'?Object.entries(dimensions).filter(([key,value])=>!['conversionLagBucket','conversionOrAdjustmentLagBucket','date'].includes(key)&&typeof value==='string').map(([,value])=>human(value.toLowerCase())):[]),...(bucket&&googleName?[googleName]:[])].filter(value=>typeof value==='string'&&value))];
1692
1825
  const currency=[row.currency,row.account_currency,row.currency_code,row.customer?.currencyCode,metrics.currency,payload.currency,payload.metadata?.currencyCode,meta.currency].find(value=>typeof value==='string'&&/^[A-Z]{3}$/.test(value));
1693
1826
  const ignored=new Set([...names,...ids,...dimensionKeys,'currency','account_currency','currency_code','entity_type','status','entity_status','report_type','FileUrlExpiryTimeUtc','file_available','timezone']);
@@ -1703,7 +1836,7 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
1703
1836
  const priority=key=>/^(spend|impressions|clicks)$/i.test(key)?['spend','impressions','clicks'].indexOf(key.toLowerCase()):/^(conversion|conversions|purchases)$|^actions · purchase$/i.test(key)?3:4;
1704
1837
  fields.sort((a,b)=>priority(a[0])-priority(b[0]));
1705
1838
  const moneyFields=provider==='ga4'?arr(payload.metric_headers).filter(header=>header.type==='TYPE_CURRENCY').map(header=>header.name):[];
1706
- return {name,status,context,currency,moneyFields,provider,fields,gaqlDimensions:googleDimensions,gaqlEntity:googleEntity,native:row,date:reportDate(dimensions.stat_time_day??(provider==='ga4'&&/^\d{8}$/.test(dimensions.date||'')?dimensions.date.replace(/^(\d{4})(\d{2})(\d{2})$/,'$1-$2-$3'):dimensions.date)??(row.date_start===row.date_stop?row.date_start:null)??(row.date_range?.start===row.date_range?.end?row.date_range?.start:null)),series:googleName||(['ga4','gsc'].includes(provider)?Object.entries(dimensions).filter(([key])=>key!=='date').map(([,value])=>value).join(' · ')||'Website':name)};
1839
+ return {name,identity,status,context,currency,moneyFields,provider,fields,gaqlDimensions:googleDimensions,gaqlEntity:googleEntity,native:row,date:reportDate(dimensions.stat_time_day??(provider==='ga4'&&/^\d{8}$/.test(dimensions.date||'')?dimensions.date.replace(/^(\d{4})(\d{2})(\d{2})$/,'$1-$2-$3'):dimensions.date)??(row.date_start===row.date_stop?row.date_start:null)??(row.date_range?.start===row.date_range?.end?row.date_range?.start:null)),series:googleName||(['ga4','gsc'].includes(provider)?Object.entries(dimensions).filter(([key])=>key!=='date').map(([,value])=>value).join(' · ')||'Website':name)};
1707
1840
  }
1708
1841
  function nativeChartRecord(record) {
1709
1842
  if(!record)return {name:'Unavailable row',context:[],fields:[]};
@@ -1712,9 +1845,9 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
1712
1845
  const ratio=nativeReportRatio(key,record.provider);
1713
1846
  const value=record.provider==='spotify'&&String(raw)==='-5'?null:reportNumber(monetary?scaled:raw);
1714
1847
  const display=nativeReportMetric(key,raw,record.provider,record.currency,record.moneyFields);
1715
- const googleMoney=record.provider==='google'&&monetary;
1716
- const shortDisplay=googleMoney&&scaled!==null?gaqlAmount(scaled,record.currency):undefined;
1717
- return {key,label:key==='costInLocalCurrency'?'Spend':key==='costInUsd'?'Spend · USD':nativeReportLabel(key),value:ratio&&value!==null?value*100:value,display,shortDisplay,unit:ratio?'%':monetary?key==='costInUsd'?'USD':record.currency||(googleMoney?'Currency unavailable':'Account units'):''};
1848
+ const shortMoney=monetary&&['google','meta'].includes(record.provider);
1849
+ const shortDisplay=shortMoney&&scaled!==null?reportAmount(scaled,record.currency):undefined;
1850
+ return {key,label:key==='costInLocalCurrency'?'Spend':key==='costInUsd'?'Spend · USD':nativeReportLabel(key),value:ratio&&value!==null?value*100:value,display,shortDisplay,unit:ratio?'%':monetary?key==='costInUsd'?'USD':record.currency||(record.provider==='meta'?'':shortMoney?'Currency unavailable':'Account units'):''};
1718
1851
  });
1719
1852
  const low=record.native.lowImpressionShare,high=record.native.highImpressionShare;
1720
1853
  const range=record.provider==='apple'&&[low,high].every(value=>typeof value==='number'&&Number.isFinite(value)&&value>=0&&value<=1)&&low<=high?[low,high]:undefined;
@@ -1737,19 +1870,27 @@ var NATIVE_REPORT_UI_SCRIPT = String.raw`
1737
1870
  const errors=arr(data.errors).filter(error=>error?.error_code).map(error=>'<p class="notice">Goal '+esc(error.goal_id||'unavailable')+': '+esc(error.error_code)+'</p>').join('');
1738
1871
  const missingGoals=arr(data.not_returned_goal_ids).filter(id=>!arr(data.errors).some(error=>error?.goal_id===id&&error?.error_code));
1739
1872
  const absent=missingGoals.length?'<p class="notice">No summary returned for goal'+(missingGoals.length===1?'':'s')+' '+missingGoals.map(esc).join(', ')+'.</p>':'';
1740
- const records=entries.slice(0,1000).map((row,index)=>nativeReportRecord(row,index,meta,payload)),delay=provider==='google'&&entries.some(row=>row?.segments?.conversionLagBucket||row?.segments?.conversionOrAdjustmentLagBucket);
1873
+ const records=(provider==='meta'?entries:entries.slice(0,1000)).map((row,index)=>nativeReportRecord(row,index,meta,payload)),delay=provider==='google'&&entries.some(row=>row?.segments?.conversionLagBucket||row?.segments?.conversionOrAdjustmentLagBucket);
1741
1874
  const pageArgs=['ga4_report','gsc_search_analytics'].includes(meta.tool)?readPageArgs(meta,'data-report-next'):null;
1742
1875
  const points=records.map(nativeChartRecord);
1743
- const table=provider==='google'&&!delay&&entries.length?gaqlReportTable(records,points):null;
1876
+ let presentation;
1877
+ if(entries.length && provider==='meta') presentation=metaInsightsReport(records,points,payload);
1878
+ if(entries.length && provider==='google' && !delay) presentation=gaqlReportTable(records,points);
1879
+ if(!presentation && records.length>1 && records.every(row=>row&&!workflowText(row.identity)) &&
1880
+ new Set(records.map(row=>JSON.stringify([row.context,row.date,row.currency]))).size===1) {
1881
+ presentation={html:workflowNote('These rows have no distinguishing labels. Include an entity name or a breakdown to compare them.'), detailRows:true};
1882
+ }
1744
1883
  const entity=records[0]?.gaqlEntity;
1745
1884
  const dimension=entity&&records.every(row=>row?.gaqlEntity===entity)?gaqlEntities.get(entity).toLowerCase():undefined;
1746
- const chart=table?null:reportCharts(points,delay?{dimension:'delay',mode:'bars',metric:records.some(record=>record?.fields.some(([key])=>key==='conversions'))?'conversions':undefined}:meta.tool==='apple_impression_share'?{metric:'Impression share',dimension:'search term'}:{dimension});
1885
+ const chart=entries.length&&!presentation?reportCharts(points,delay?{dimension:'delay',mode:'bars',metric:records.some(record=>record?.fields.some(([key])=>key==='conversions'))?'conversions':undefined}:meta.tool==='apple_impression_share'?{metric:'Impression share',dimension:'search term'}:{dimension}):null;
1747
1886
  const analytics=['ga4','gsc'].includes(provider),range=payload?.date_range;
1748
1887
  const period=analytics&&object(range)?[range.start_date??range.start,range.end_date??range.end].filter(workflowText).join(' – '):'';
1749
- const subject=table?.subject||(analytics?[meta.accountId,period].filter(Boolean).join(' · '):'');
1750
- const body=table?.html||(entries.length?chart.html:'<p class="operation-note">'+missing+'</p>');
1751
- app.innerHTML=chrome(operationHeader(table?.title||(delay?'Conversion delay':title),subject,provider)+notices({...data,...(meta.tool==='linkedin_demographic_report'?{notes:[]}:{}),errors:arr(data.errors).filter(error=>!error?.error_code)})+errors+absent+'<section data-native-report data-read-page-focus tabindex="-1">'+body+(meta.tool==='linkedin_demographic_report'?'<p class="report-chart-foot">Approximate demographics · privacy thresholds apply</p>':'')+(entries.length>1000?'<p class="operation-note">Showing 1,000 returned rows. The full response is in Details.</p>':'')+readPageMarkup(pageArgs,'data-report-next','data-report-page-status')+'<details class="report-data"><summary>Details · '+entries.length+' results</summary>'+(!table&&entries.length?'<div class="record-list" role="region" aria-label="Native report data" tabindex="0">'+entries.slice(0,1000).map((row,index)=>nativeReportRow(row,index,meta,payload)).join('')+'</div>':'')+'<pre>'+esc(JSON.stringify(clean,null,2))+'</pre></details></section>',table?entries.length+(entries.length===1?' row':' rows'):'');
1752
- chart?.mount();
1888
+ const subject=presentation?.subject||(analytics?[meta.accountId,period].filter(Boolean).join(' · '):'');
1889
+ const view=presentation||chart;
1890
+ const body=view?.html||'<p class="operation-note">'+missing+'</p>';
1891
+ const showDetailRows=!presentation||presentation.detailRows||provider==='meta'&&entries.length===1;
1892
+ app.innerHTML=chrome(operationHeader(presentation?.title||(delay?'Conversion delay':title),subject,provider)+notices({...data,...(meta.tool==='linkedin_demographic_report'?{notes:[]}:{}),errors:arr(data.errors).filter(error=>!error?.error_code)})+errors+absent+'<section data-native-report data-read-page-focus tabindex="-1">'+body+(meta.tool==='linkedin_demographic_report'?'<p class="report-chart-foot">Approximate demographics · privacy thresholds apply</p>':'')+(provider!=='meta'&&entries.length>1000?'<p class="operation-note">Showing 1,000 returned rows. The full response is in Details.</p>':'')+readPageMarkup(pageArgs,'data-report-next','data-report-page-status')+'<details class="report-data"><summary>Details · '+entries.length+' result'+(entries.length===1?'':'s')+'</summary>'+(showDetailRows&&entries.length?'<div class="record-list" role="region" aria-label="Native report data" tabindex="0">'+entries.slice(0,1000).map((row,index)=>nativeReportRow(row,index,meta,payload)).join('')+'</div>':'')+'<pre>'+esc(JSON.stringify(clean,null,2))+'</pre></details></section>',presentation?entries.length+(entries.length===1?' row':' rows'):'');
1893
+ view?.mount?.();
1753
1894
  bindReadPage(meta,pageArgs,'data-report-next','data-report-page-status',value=>Array.isArray(recordPayload(value)?.rows));
1754
1895
  }
1755
1896
  `;
@@ -1804,9 +1945,9 @@ var WORKFLOW_UI = String.raw`
1804
1945
  (status?'<span class="pill '+tone+'">'+esc(status)+'</span>':'')+'</div>'+body+'</'+tag+'>';
1805
1946
  }
1806
1947
 
1807
- function workflowHeader(labels) {
1808
- return '<thead role="rowgroup"><tr role="row">'+labels.map(label=>
1809
- '<th role="columnheader" scope="col">'+esc(label)+'</th>').join('')+'</tr></thead>';
1948
+ function workflowHeader(labels,sorted=-1) {
1949
+ return '<thead role="rowgroup"><tr role="row">'+labels.map((label,i)=>
1950
+ '<th role="columnheader" scope="col"'+(i===sorted?' aria-sort="descending"':'')+'>'+esc(label)+'</th>').join('')+'</tr></thead>';
1810
1951
  }
1811
1952
 
1812
1953
  function workflowCell(label,html,heading=false) {
@@ -1815,10 +1956,10 @@ var WORKFLOW_UI = String.raw`
1815
1956
  '<span class="workflow-cell-label" aria-hidden="true" data-label="'+esc(label)+'"></span><span>'+html+'</span></'+tag+'>';
1816
1957
  }
1817
1958
 
1818
- function workflowTable(labels,rows,description) {
1959
+ function workflowTable(labels,rows,description,{compact=false,sorted=-1}={}) {
1819
1960
  if(!rows.length)return '';
1820
- return '<div class="workflow-scroll" role="region" aria-label="'+esc(description)+'" tabindex="0">'+
1821
- '<table class="workflow-table workflow-stack" role="table">'+workflowHeader(labels)+'<tbody role="rowgroup">'+
1961
+ return '<div class="'+(compact?'collection-scroll':'workflow-scroll')+'" role="region" aria-label="'+esc(description)+'" tabindex="0">'+
1962
+ '<table class="workflow-table'+(compact?'':' workflow-stack')+'" role="table">'+workflowHeader(labels,sorted)+'<tbody role="rowgroup">'+
1822
1963
  rows.map(row=>'<tr role="row">'+row.map((value,i)=>workflowCell(labels[i],esc(workflowText(value)||'—'),i===0)).join('')+'</tr>').join('')+
1823
1964
  '</tbody></table></div>';
1824
1965
  }
@@ -2303,6 +2444,23 @@ var REPORT_CHART_SCRIPT = String.raw`
2303
2444
  function reportNumber(value) {
2304
2445
  const decimal=nativeReportDecimal(value);return decimal!==null&&Number.isFinite(Number(decimal))?Number(decimal):null;
2305
2446
  }
2447
+ const reportMoneyFormats = new Map();
2448
+ function reportAmount(amount, currency) {
2449
+ const locale = state.host.locale || 'en', key = locale + '/' + (currency || '');
2450
+ if (!reportMoneyFormats.has(key)) {
2451
+ const digits = currency ? new Intl.NumberFormat(locale, {style:'currency', currency}).resolvedOptions().maximumFractionDigits : 2;
2452
+ reportMoneyFormats.set(key, {
2453
+ format: new Intl.NumberFormat(locale, {minimumFractionDigits:digits, maximumFractionDigits:digits}),
2454
+ unit: 10 ** -digits
2455
+ });
2456
+ }
2457
+ const {format, unit} = reportMoneyFormats.get(key);
2458
+ if (Number(amount) !== 0 && Math.abs(Number(amount)) < unit) {
2459
+ return Number(amount) < 0 ? '>' + format.format(-unit) : '<' + format.format(unit);
2460
+ }
2461
+ return format.format(amount);
2462
+ }
2463
+
2306
2464
  function reportMetricPriority(key) {
2307
2465
  const value=key.replaceAll('_','').toLowerCase();
2308
2466
  const order=['spend','costmicros','costinlocalcurrency','costinusd','conversions','conversion','totalinstalls','installs','purchases','clicks','taps','impressions','searchpopularity1to100','searchpopularityingenre','searchpopularity1to5','overallsuccesscount','successcount'];
@@ -2365,8 +2523,8 @@ var REPORT_CHART_SCRIPT = String.raw`
2365
2523
  `;
2366
2524
 
2367
2525
  // src/ui.ts
2368
- var ADPORT_UI_URI = "ui://adport/insight-card-v34.html";
2369
- var ADPORT_SUMMARY_UI_URI = "ui://adport/summary-card-v34.html";
2526
+ var ADPORT_UI_URI = "ui://adport/insight-card-v40.html";
2527
+ var ADPORT_SUMMARY_UI_URI = "ui://adport/summary-card-v40.html";
2370
2528
  var ADPORT_UI_DOMAIN = "https://app.adport.dev";
2371
2529
  var ADPORT_UI_RESOURCE_DOMAINS = [
2372
2530
  ADPORT_UI_DOMAIN,
@@ -2845,7 +3003,7 @@ ${PLANNING_UI}
2845
3003
 
2846
3004
  // src/index.ts
2847
3005
  var PROVIDER_IDS = ["ga4", "gsc", "gtm", "google", "meta", "tiktok", "apple", "microsoft", "reddit", "snapchat", "spotify", "pinterest", "linkedin", "x", "openai"];
2848
- var ADPORT_UI_RESOURCE_URIS = [ADPORT_UI_URI, "ui://adport/insight-card-v33.html", "ui://adport/insight-card-v32.html", "ui://adport/insight-card-v31.html", "ui://adport/insight-card-v30.html", "ui://adport/insight-card-v29.html", "ui://adport/insight-card-v28.html", "ui://adport/insight-card-v27.html", "ui://adport/insight-card-v26.html", "ui://adport/insight-card-v25.html", "ui://adport/insight-card-v24.html", "ui://adport/insight-card-v23.html", "ui://adport/insight-card-v22.html", "ui://adport/insight-card-v21.html", "ui://adport/insight-card-v20.html", "ui://adport/insight-card-v19.html", "ui://adport/insight-card-v18.html", "ui://adport/insight-card-v17.html", "ui://adport/insight-card-v16.html", "ui://adport/insight-card-v15.html", "ui://adport/insight-card-v14.html", "ui://adport/insight-card-v13.html", "ui://adport/insight-card-v12.html", "ui://adport/insight-card-v11.html", "ui://adport/insight-card-v10.html", "ui://adport/insight-card-v9.html", "ui://adport/insight-card-v8.html", "ui://adport/insight-card-v7.html", "ui://adport/insight-card-v6.html", "ui://adport/insight-card-v5.html", "ui://adport/insight-card-v4.html", "ui://adport/insight-card-v3.html", "ui://adport/insight-card-v2.html", ADPORT_SUMMARY_UI_URI, "ui://adport/summary-card-v33.html", "ui://adport/summary-card-v32.html", "ui://adport/summary-card-v30.html"];
3006
+ var ADPORT_UI_RESOURCE_URIS = [ADPORT_UI_URI, "ui://adport/insight-card-v36.html", "ui://adport/insight-card-v35.html", "ui://adport/insight-card-v34.html", "ui://adport/insight-card-v33.html", "ui://adport/insight-card-v32.html", "ui://adport/insight-card-v31.html", "ui://adport/insight-card-v30.html", "ui://adport/insight-card-v29.html", "ui://adport/insight-card-v28.html", "ui://adport/insight-card-v27.html", "ui://adport/insight-card-v26.html", "ui://adport/insight-card-v25.html", "ui://adport/insight-card-v24.html", "ui://adport/insight-card-v23.html", "ui://adport/insight-card-v22.html", "ui://adport/insight-card-v21.html", "ui://adport/insight-card-v20.html", "ui://adport/insight-card-v19.html", "ui://adport/insight-card-v18.html", "ui://adport/insight-card-v17.html", "ui://adport/insight-card-v16.html", "ui://adport/insight-card-v15.html", "ui://adport/insight-card-v14.html", "ui://adport/insight-card-v13.html", "ui://adport/insight-card-v12.html", "ui://adport/insight-card-v11.html", "ui://adport/insight-card-v10.html", "ui://adport/insight-card-v9.html", "ui://adport/insight-card-v8.html", "ui://adport/insight-card-v7.html", "ui://adport/insight-card-v6.html", "ui://adport/insight-card-v5.html", "ui://adport/insight-card-v4.html", "ui://adport/insight-card-v3.html", "ui://adport/insight-card-v2.html", ADPORT_SUMMARY_UI_URI, "ui://adport/summary-card-v36.html", "ui://adport/summary-card-v35.html", "ui://adport/summary-card-v34.html", "ui://adport/summary-card-v33.html", "ui://adport/summary-card-v32.html", "ui://adport/summary-card-v30.html"];
2849
3007
  var DEFAULT_MCP_ICONS = [{
2850
3008
  src: "https://app.adport.dev/icon.svg?brand=orange-dot-v2",
2851
3009
  mimeType: "image/svg+xml",
@@ -3064,4 +3222,4 @@ export {
3064
3222
  createMcpServer,
3065
3223
  runStdioServer
3066
3224
  };
3067
- //# sourceMappingURL=chunk-LLAXR25X.js.map
3225
+ //# sourceMappingURL=chunk-TEP7TOPQ.js.map