@adport/mcp 0.13.1 → 0.13.2

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-TEP7TOPQ.js";
5
+ } from "./chunk-NWNTOUFX.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.13.1",
25
+ version: "0.13.2",
26
26
  description: "adport MCP server \u2014 the open control plane for paid media",
27
27
  license: "Apache-2.0",
28
28
  type: "module",
@@ -989,10 +989,11 @@ var CREATIVE_UI_SCRIPT = String.raw`
989
989
  };
990
990
  const unique=values=>[...new Set(arr(values).filter(value=>typeof value==='string'&&value.trim()))];
991
991
  return creatives.map(creative=>{
992
- const name=creative.name || 'Untitled creative',status=statusOf(creative.status);
992
+ const name=creative.name || 'Untitled creative',delivery=creative.deliveryStatus || creative.status;
993
+ const status=statusOf(delivery==='ADSET_PAUSED'?'Ad set paused':delivery==='CAMPAIGN_PAUSED'?'Campaign paused':delivery);
993
994
  const destination=arr(creative.landing_urls).map(value=>safeUrl(value)).find(Boolean);
994
995
  const headline=unique(creative.headlines).filter(text=>text!==name).join(' · '),copy=unique(creative.descriptions).filter(text=>text!==name&&text!==headline).join('\n');
995
- const active=/^(active|enabled|ready|approved)$/i.test(creative.status || '');
996
+ const active=/^(active|enabled|ready|approved)$/i.test(delivery || '');
996
997
  return '<article class="creative-card" data-media-id="'+esc(creative.id)+'"><div class="creative-heading">'+(providerSvg[creative.provider]?logo(creative.provider):'')+'<span class="creative-name" title="'+esc(name)+'">'+esc(name)+'</span>'+(menuFor?menuFor(creative):'')+'</div>'+mediaView(creative)+'<div class="creative-copy">'+(headline?'<strong title="'+esc(headline)+'">'+esc(headline)+'</strong>':'')+(copy?'<p title="'+esc(copy)+'">'+esc(copy)+'</p>':'')+'</div><div class="creative-footer"><span class="creative-status'+(active?' creative-status-active':'')+'">'+esc(status.label)+'</span>'+(destination?'<a class="creative-destination" href="'+esc(destination.href)+'" target="_blank" rel="noopener noreferrer">'+esc(destination.hostname.replace(/^www\./,''))+'</a>':'')+'</div></article>';
997
998
  }).join('');
998
999
  }
@@ -1042,6 +1043,19 @@ var PROVIDER_GALLERY_UI = String.raw`
1042
1043
  let providerGallery=null;
1043
1044
  const galleryStable=value=>JSON.stringify((function sort(v){return Array.isArray(v)?v.map(sort):object(v)?Object.fromEntries(Object.entries(v).sort(([a],[b])=>a.localeCompare(b)).map(([k,item])=>[k,sort(item)])):v;})(value));
1044
1045
  const galleryItemKey=item=>[item.provider,item.account_id,item.id].join(':');
1046
+ function galleryItems(data,meta) {
1047
+ const creatives=arr(data.creatives);
1048
+ if(meta.tool!=='meta_list_ads' || !Array.isArray(data.ads)) return creatives;
1049
+ const delivery=new Map();
1050
+ for(const ad of data.ads) {
1051
+ if(typeof ad?.effective_status==='string' && ad.effective_status && typeof ad.account_id==='string' && typeof ad.id==='string')
1052
+ delivery.set(galleryItemKey({provider:'meta',account_id:ad.account_id,id:ad.id}),ad.effective_status);
1053
+ }
1054
+ return creatives.map(item=>{
1055
+ const status=delivery.get(galleryItemKey(item));
1056
+ return status?{...item,deliveryStatus:status}:item;
1057
+ });
1058
+ }
1045
1059
  function galleryScope(meta) {
1046
1060
  const args={...meta.refresh?.arguments};delete args[meta.pagination?.cursorInput];
1047
1061
  return galleryStable({tool:meta.tool,provider:meta.provider,account:meta.accountId,project:meta.context?.project_id,filters:args});
@@ -1080,12 +1094,12 @@ var PROVIDER_GALLERY_UI = String.raw`
1080
1094
  bindGalleryCard(card,gallery);
1081
1095
  }
1082
1096
  function renderProviderGallery(data,meta) {
1083
- const previous=providerGallery,previousWrite=previous?.meta.capabilities?.can_write,retain=previous && previous.scope===galleryScope(meta) && app.querySelector('[data-provider-gallery]');
1097
+ const previous=providerGallery,previousWrite=previous?.meta.capabilities?.can_write,retain=meta.accountId && previous && previous.scope===galleryScope(meta) && app.querySelector('[data-provider-gallery]');
1084
1098
  if(!retain) providerGallery={scope:galleryScope(meta),data,meta,items:new Map(),sources:new Map(),seen:new Set(),busy:null,review:null};
1085
1099
  const gallery=providerGallery;gallery.data=data;gallery.meta=meta;
1086
1100
  if(!retain) app.innerHTML=chrome('<div data-provider-notes></div><div class="creative-grid" data-provider-gallery role="region" aria-label="Creative previews" tabindex="0"></div><div data-provider-pages></div>','');
1087
1101
  const root=app.querySelector('[data-provider-gallery]');
1088
- for(const item of arr(data.creatives)) {
1102
+ for(const item of galleryItems(data,meta)) {
1089
1103
  const key=galleryItemKey(item);gallery.sources.set(key,meta.refresh?.arguments);if(gallery.items.has(key)) {const old=gallery.items.get(key);if(galleryStable(old)!==galleryStable(item) || previousWrite!==meta.capabilities?.can_write) {const card=[...root.querySelectorAll('[data-creative-key]')].find(node=>node.dataset.creativeKey===key);gallery.items.set(key,item);if(card) {if(meta.capabilities?.can_write!==true) card.querySelector('[data-creative-editor]')?.remove();updateGalleryCard(card,old,item,gallery);}}continue;}
1090
1104
  gallery.items.set(key,item);
1091
1105
  const template=document.createElement('template');template.innerHTML=creativeCards([item],galleryMenu);const card=template.content.firstElementChild;card.dataset.creativeKey=key;root.append(card);bindGalleryCard(card,gallery);bindCreativeErrors(card);
@@ -1093,7 +1107,8 @@ var PROVIDER_GALLERY_UI = String.raw`
1093
1107
  root.querySelector('.empty')?.remove();if(!gallery.items.size) root.innerHTML='<div class="empty">No creatives to preview.</div>';
1094
1108
  root.classList.toggle('creative-grid-single',gallery.items.size===1);
1095
1109
  app.querySelector('[data-provider-notes]').innerHTML=notices({...data,truncated:false});
1096
- state.result={structuredContent:{...data,creatives:[...gallery.items.values()],_adport:meta}};renderProviderPages();
1110
+ if(meta.accountId) state.result={structuredContent:{...data,creatives:[...gallery.items.values()],_adport:meta}};
1111
+ renderProviderPages();
1097
1112
  }
1098
1113
  function renderProviderPages(message='') {
1099
1114
  const gallery=providerGallery,area=app.querySelector('[data-provider-pages]');if(!gallery || !area) return;
@@ -1167,7 +1182,7 @@ var PROVIDER_GALLERY_UI = String.raw`
1167
1182
  gallery.busy={kind:'refresh',tool:gallery.meta.tool,args};renderProviderPages();
1168
1183
  try {
1169
1184
  const response=await callTool(gallery.meta.tool,args,60000),value=galleryPageValue(response,gallery,args);if(providerGallery!==gallery) return;
1170
- const updated=value.creatives.find(item=>galleryItemKey(item)===review.key);
1185
+ const updated=galleryItems(value,value._adport).find(item=>galleryItemKey(item)===review.key);
1171
1186
  if(!updated && !(phase==='applied' && review.kind==='remove')) throw new Error('The edited creative is outside this page. Ask your assistant for a fresh view.');
1172
1187
  if(!updated) {
1173
1188
  gallery.items.delete(review.key);gallery.sources.delete(review.key);card?.remove();gallery.seen.clear();
@@ -1244,13 +1259,6 @@ var OPERATION_UI_SCRIPT = String.raw`
1244
1259
  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
1245
1260
  ${OPERATION_RECONCILIATION_UI}
1246
1261
  const human = value => String(value).replace(/([a-z])([A-Z])/g,'$1 $2').replace(/[_.]/g,' ').replace(/^./,c=>c.toUpperCase());
1247
- function resultData(result) {
1248
- if (result?.structuredContent && typeof result.structuredContent === 'object') return result.structuredContent;
1249
- for (const item of arr(result?.content)) {
1250
- if (item.type === 'text') { try { const value=JSON.parse(item.text),data=object(value)?value:{value};return result._meta?.adport?{...data,_adport:result._meta.adport}:data; } catch {} }
1251
- }
1252
- return Array.isArray(result)?{value:result}:result || {};
1253
- }
1254
1262
  function dataFields(value, prefix='', depth=0) {
1255
1263
  if (!object(value) || depth>8) return [];
1256
1264
  return Object.entries(value).filter(([key])=>!['_adport','data_source','pending_operation_id'].includes(key)).flatMap(([key,item])=>{
@@ -1431,7 +1439,7 @@ var OPERATION_UI_SCRIPT = String.raw`
1431
1439
  else send({jsonrpc:'2.0',id:id++,method:'ui/update-model-context',params:{structuredContent:{adport_operation:facts}}});
1432
1440
  }
1433
1441
  function renderFailure(data,meta,isWrite) {
1434
- const phase=errorPhase(data),title=phase==='expired'?'Preview expired':phase==='blocked'?'Action blocked':isWrite?'Outcome unconfirmed':'Request failed';
1442
+ const phase=errorPhase(data),title=phase==='expired'?'Preview expired':phase==='blocked'?'Action blocked':isWrite?'Outcome unconfirmed':data.error==='UNREADABLE_TOOL_RESULT'?'Result unreadable':'Request failed';
1435
1443
  app.innerHTML=chrome(operationHeader(title,meta.accountId,meta.provider)+'<p class="operation-note" role="alert">'+esc(data.message || (isWrite?'Check the result before retrying.':'See the tool response for details.'))+'</p>'+(!['expired','blocked'].includes(phase) && isWrite?'<p class="operation-note">Check the current state before retrying.</p>':'')+'<details><summary>Details</summary><pre>'+esc(JSON.stringify(data,null,2))+'</pre></details>','');
1436
1444
  }
1437
1445
  `;
@@ -1467,9 +1475,12 @@ var APPLE_REPORT_UI_SCRIPT = String.raw`
1467
1475
  const fields=[['Spend',appleReportMoney(metrics.localSpend)],['Taps',taps===null?'—':taps.toLocaleString(state.host.locale||'en')],['Installs',installs===null?'—':installs.toLocaleString(state.host.locale||'en')],['CPI',installs===0?'—':appleReportMoney(metrics.totalAvgCPI)]];
1468
1476
  return '<dl class="record-fields apple-report-metrics">'+fields.map(([label,value])=>'<div><dt>'+esc(label)+'</dt><dd>'+esc(value)+'</dd></div>').join('')+'</dl>';
1469
1477
  }
1478
+ function appleEntityName(metadata) {
1479
+ return [metadata?.searchTermText,metadata?.text,metadata?.name,metadata?.keyword?.text].find(value=>typeof value==='string' && value.trim()) ?? String(metadata?.id ?? '');
1480
+ }
1470
1481
  function appleReportRow(row,index) {
1471
1482
  const metadata=object(row?.metadata)?row.metadata:{},keyword=object(metadata.keyword)?metadata.keyword:{};
1472
- const name=[metadata.searchTermText,metadata.text,metadata.name,keyword.text].find(value=>typeof value==='string'&&value.trim()) ?? (metadata.id!==undefined?String(metadata.id):'Unnamed result '+(index+1));
1483
+ const name=appleEntityName(metadata) || 'Unnamed result '+(index+1);
1473
1484
  const status=[metadata.displayStatus,metadata.systemStatus,metadata.status].find(value=>typeof value==='string'&&value);
1474
1485
  const dimensions=['countryOrRegion','countryCode','adminArea','locality','deviceClass','ageRange','gender'].flatMap(key=>typeof metadata[key]==='string'&&metadata[key]?[metadata[key]]:[]);
1475
1486
  const matchType=metadata.matchType||keyword.matchType;
@@ -1479,8 +1490,8 @@ var APPLE_REPORT_UI_SCRIPT = String.raw`
1479
1490
  return '<article class="record-row"><div class="record-heading"><strong>'+esc(name)+'</strong>'+(status?'<span>'+esc(human(status.toLowerCase()))+'</span>':'')+'</div>'+(dimensions.length?'<p class="apple-report-dimensions">'+dimensions.map(esc).join(' · ')+'</p>':'')+(hasTotals||!periods.length?appleReportMetrics(row?.totalMetrics):'')+breakdown+'</article>';
1480
1491
  }
1481
1492
  function appleChartRecord(row,index,metrics=row?.totalMetrics) {
1482
- const metadata=object(row?.metadata)?row.metadata:{},keyword=object(metadata.keyword)?metadata.keyword:{};
1483
- const name=[metadata.searchTermText,metadata.text,metadata.name,keyword.text].find(value=>typeof value==='string'&&value.trim())??String(metadata.id??'Unnamed result '+(index+1));
1493
+ const metadata=object(row?.metadata)?row.metadata:{};
1494
+ const name=appleEntityName(metadata) || 'Unnamed result '+(index+1);
1484
1495
  const context=['countryOrRegion','countryCode','deviceClass','ageRange','gender'].flatMap(key=>typeof metadata[key]==='string'?[metadata[key]]:[]);
1485
1496
  const fields=[['spend','Spend',metrics?.localSpend?.amount,appleReportMoney(metrics?.localSpend),currencyOf(metrics?.localSpend||{})||'Account units'],['taps','Taps',metrics?.taps,appleReportNumber(metrics?.taps)===null?'—':String(metrics.taps),''],['installs','Installs',metrics?.totalInstalls,appleReportNumber(metrics?.totalInstalls)===null?'—':String(metrics.totalInstalls),'']].map(([key,label,raw,display,unit])=>({key,label,value:appleReportNumber(raw),display,unit}));
1486
1497
  for(const [key,raw] of Object.entries(metrics||{}))if(!['localSpend','taps','totalInstalls','date'].includes(key)) {
@@ -1489,10 +1500,13 @@ var APPLE_REPORT_UI_SCRIPT = String.raw`
1489
1500
  }
1490
1501
  return {name,context:typeof metrics?.date==='string'&&!reportDate(metrics.date)?[...context,metrics.date]:context,series:[name,...context].join(' · '),date:reportDate(metrics?.date),fields};
1491
1502
  }
1492
- function appleReportOverview(metrics) {
1503
+ function appleReportOverview(metrics,entityName) {
1493
1504
  if(!object(metrics))return '';
1494
1505
  const taps=appleReportNumber(metrics.taps),installs=appleReportNumber(metrics.totalInstalls);
1495
- return '<div class="report-overview apple-report-total" aria-label="Report total"><div><small>Total spend</small><strong>'+esc(appleReportMoney(metrics.localSpend))+'</strong></div><dl><div><dt>Taps</dt><dd>'+esc(taps??'—')+'</dd></div><div><dt>Installs</dt><dd>'+esc(installs??'—')+'</dd></div>'+(installs>0&&object(metrics.totalAvgCPI)?'<div><dt>CPI</dt><dd>'+esc(appleReportMoney(metrics.totalAvgCPI))+'</dd></div>':'')+'</dl></div>';
1506
+ if(taps===null && installs===null && appleReportNumber(metrics.localSpend?.amount)===null)return '';
1507
+ const grandTotal=entityName===undefined,label=grandTotal?'Report total':'Returned row metrics';
1508
+ const spend=grandTotal?'Total spend':entityName?'Spend · '+entityName:'Spend for this row';
1509
+ return '<div class="report-overview'+(grandTotal?' apple-report-total':'')+'" aria-label="'+label+'"><div><small>'+esc(spend)+'</small><strong>'+esc(appleReportMoney(metrics.localSpend))+'</strong></div><dl><div><dt>Taps</dt><dd>'+esc(taps??'—')+'</dd></div><div><dt>Installs</dt><dd>'+esc(installs??'—')+'</dd></div>'+(installs>0&&object(metrics.totalAvgCPI)?'<div><dt>CPI</dt><dd>'+esc(appleReportMoney(metrics.totalAvgCPI))+'</dd></div>':'')+'</dl></div>';
1496
1510
  }
1497
1511
  function renderAppleReport(data,meta) {
1498
1512
  const payload=recordPayload(data),hasRows=object(payload)&&Array.isArray(payload.rows),rows=hasRows?payload.rows:[];
@@ -1500,7 +1514,8 @@ var APPLE_REPORT_UI_SCRIPT = String.raw`
1500
1514
  const grandTotal=payload?.summary?.grandTotal;
1501
1515
  // Use Apple's explicit total, which can cover more rows than this page.
1502
1516
  // Never sum breakdowns, average CPIs, or mix currencies in the widget.
1503
- const summary=rows.length?appleReportOverview(grandTotal):'';
1517
+ const single=rows.length===1?rows[0]:null;
1518
+ const summary=rows.length?appleReportOverview(grandTotal) || (single?appleReportOverview(single.totalMetrics,appleEntityName(single.metadata)):''):'';
1504
1519
  const pagination=data.pagination,offset=pagination?.offset,count=pagination?.totalCount;
1505
1520
  const page=rows.length&&Number.isSafeInteger(offset)&&offset>=0&&Number.isSafeInteger(count)&&count>=offset+rows.length&&(offset>0||count>rows.length)?'<p class="apple-report-page">Showing '+(offset+1)+'–'+(offset+Math.min(rows.length,1000))+' of '+count+' results</p>':'';
1506
1521
  const clean={...data};delete clean._adport;
@@ -2495,14 +2510,17 @@ var REPORT_CHART_SCRIPT = String.raw`
2495
2510
  return '<section class="report-chart" data-report-chart><div class="report-chart-head"><b>'+esc(title)+'</b>'+(unit?'<span>'+esc(unit)+'</span>':'')+'</div>'+body+(!trend&&model.returned>shown.length?'<p class="report-chart-foot">'+shown.length+' of '+model.returned+' returned rows · all rows in Details</p>':trend&&model.returned>points.length?'<p class="report-chart-foot">'+points.length+' of '+model.returned+' dated observations · all data in Details</p>':'')+'</section>';
2496
2511
  }).join('')+(groups.size>4?'<p class="report-chart-foot">Showing four units. All returned values are in Details.</p>':'');
2497
2512
  return {html,mount:()=>{
2498
- const elements=[...app.querySelectorAll('[data-native-line]')];
2513
+ const elements=[...app.querySelectorAll('[data-native-line]')],widths=new Map();
2499
2514
  const draw=()=>elements.forEach(element=>{
2500
2515
  if(element.isConnected===false)return;
2501
2516
  const model=models[Number(element.dataset.nativeLine)];if(!model)return;
2517
+ const width=Math.max(240,Math.floor(element.getBoundingClientRect?.().width||480));
2518
+ if(widths.get(element)===width)return;
2519
+ widths.set(element,width);
2502
2520
  const series=new Map();for(const point of model.points){const name=point.series||point.name;if(!series.has(name))series.set(name,[]);series.get(name).push(point);}
2503
2521
  const chosen=[...series.entries()].slice(0,3),valid=chosen.flatMap(([,points])=>points).filter(point=>available(point.value));
2504
2522
  if(!valid.length){element.innerHTML='<p class="operation-note">No complete dated values were returned.</p>';return;}
2505
- const width=Math.max(240,Math.floor(element.getBoundingClientRect?.().width||480)),height=178,left=46,right=12,top=12,bottom=30;
2523
+ const height=178,left=46,right=12,top=12,bottom=30;
2506
2524
  const dates=[...new Set(model.points.map(point=>point.date))].sort(),start=Date.parse(dates[0]),end=Date.parse(dates.at(-1)),span=Math.max(86400000,end-start);
2507
2525
  const max=Math.max(1e-100,...valid.map(point=>point.value)),min=Math.min(0,...valid.map(point=>point.value)),range=max-min||1;
2508
2526
  const x=date=>left+(Date.parse(date)-start)/span*(width-left-right),y=value=>top+(max-value)/range*(height-top-bottom);
@@ -2515,7 +2533,7 @@ var REPORT_CHART_SCRIPT = String.raw`
2515
2533
  return '<path d="'+line+'" fill="none" stroke="'+colors[index]+'" stroke-width="2" stroke-dasharray="'+dashes[index]+'"/>'+sorted.filter(point=>available(point.value)).map(point=>'<circle cx="'+x(point.date)+'" cy="'+y(point.value)+'" r="3" fill="'+colors[index]+'" tabindex="0"><title>'+esc(pretty(name)+' · '+point.date+' · '+point.display)+'</title></circle>').join('');
2516
2534
  }).join('');
2517
2535
  const axis=value=>new Intl.NumberFormat(state.host.locale||'en',{notation:Math.abs(value)>=1000?'compact':'standard',maximumFractionDigits:3}).format(value);
2518
- element.innerHTML='<svg viewBox="0 0 '+width+' '+height+'" role="img" aria-label="'+esc(model.label+' over reported dates')+'"><line class="chart-grid" x1="'+left+'" x2="'+(width-right)+'" y1="'+(height-bottom)+'" y2="'+(height-bottom)+'"/><text x="'+(left-8)+'" y="'+(top+4)+'" text-anchor="end">'+esc(axis(max))+'</text><text x="'+(left-8)+'" y="'+(height-bottom)+'" text-anchor="end">'+esc(axis(min))+'</text>'+paths+labels+'</svg>'+(chosen.length>1?'<div class="report-legend">'+chosen.map(([name],index)=>'<span><i style="border-color:'+colors[index]+';border-top-style:'+(index?'dashed':'solid')+'"></i>'+esc(pretty(name))+'</span>').join('')+'</div>':'')+(series.size>3?'<p class="report-chart-foot">3 of '+series.size+' series · all series in Details</p>':'');
2536
+ element.innerHTML='<svg height="'+height+'" viewBox="0 0 '+width+' '+height+'" role="img" aria-label="'+esc(model.label+' over reported dates')+'"><line class="chart-grid" x1="'+left+'" x2="'+(width-right)+'" y1="'+(height-bottom)+'" y2="'+(height-bottom)+'"/><text x="'+(left-8)+'" y="'+(top+4)+'" text-anchor="end">'+esc(axis(max))+'</text><text x="'+(left-8)+'" y="'+(height-bottom)+'" text-anchor="end">'+esc(axis(min))+'</text>'+paths+labels+'</svg>'+(chosen.length>1?'<div class="report-legend">'+chosen.map(([name],index)=>'<span><i style="border-color:'+colors[index]+';border-top-style:'+(index?'dashed':'solid')+'"></i>'+esc(pretty(name))+'</span>').join('')+'</div>':'')+(series.size>3?'<p class="report-chart-foot">3 of '+series.size+' series · all series in Details</p>':'');
2519
2537
  });
2520
2538
  draw();if(typeof ResizeObserver!=='undefined'&&models.some(model=>model.trend)){trendResize=new ResizeObserver(draw);elements.forEach(element=>trendResize.observe(element));}
2521
2539
  }};
@@ -2523,8 +2541,8 @@ var REPORT_CHART_SCRIPT = String.raw`
2523
2541
  `;
2524
2542
 
2525
2543
  // src/ui.ts
2526
- var ADPORT_UI_URI = "ui://adport/insight-card-v40.html";
2527
- var ADPORT_SUMMARY_UI_URI = "ui://adport/summary-card-v40.html";
2544
+ var ADPORT_UI_URI = "ui://adport/insight-card-v41.html";
2545
+ var ADPORT_SUMMARY_UI_URI = "ui://adport/summary-card-v41.html";
2528
2546
  var ADPORT_UI_DOMAIN = "https://app.adport.dev";
2529
2547
  var ADPORT_UI_RESOURCE_DOMAINS = [
2530
2548
  ADPORT_UI_DOMAIN,
@@ -2860,6 +2878,44 @@ ${NATIVE_REPORT_UI_SCRIPT}
2860
2878
  ${REPORT_CHART_SCRIPT}
2861
2879
  ${INSIGHT_UI_SCRIPT}
2862
2880
  ${TREND_UI_SCRIPT}
2881
+ function isToolResult(value) {
2882
+ return object(value) && (Object.hasOwn(value,'structuredContent') || Array.isArray(value.content) && value.content.every(block=>typeof block?.type==='string'))
2883
+ && Object.keys(value).every(key=>['content','structuredContent','_meta','isError'].includes(key));
2884
+ }
2885
+ function textPayload(content) {
2886
+ const blocks=arr(content).filter(block=>block?.type==='text' && typeof block.text==='string');
2887
+ for (const block of blocks) {
2888
+ try { return JSON.parse(block.text); } catch {}
2889
+ }
2890
+ if (blocks.length===1 && content.length===1) {
2891
+ const text=blocks[0].text, first=text.trimStart()[0];
2892
+ if (first==='{' || first==='[') return {error:'UNREADABLE_TOOL_RESULT',message:'The widget could not read the complete tool response. Check the result in the conversation.'};
2893
+ return {message:text};
2894
+ }
2895
+ }
2896
+ function normalizeToolResult(input,hostMeta) {
2897
+ let value=input, envelopeMeta, isError=false, fromText=false;
2898
+ // A host can forward a complete CallToolResult inside another text block.
2899
+ // Stop at the provider payload, including its own result, content or copy.
2900
+ for (let depth=0;depth<8 && isToolResult(value);depth++) {
2901
+ isError ||= value.isError===true;
2902
+ envelopeMeta ??= value._meta?.adport;
2903
+ fromText=value.structuredContent==null;
2904
+ const next=fromText?textPayload(value.content):value.structuredContent;
2905
+ if (next===undefined) break;
2906
+ value=next;
2907
+ }
2908
+ const data=object(value)?value:{value};
2909
+ const meta=hostMeta ?? (fromText?undefined:data._adport) ?? envelopeMeta;
2910
+ let structuredContent=data;
2911
+ if (meta!==data._adport) {
2912
+ structuredContent={...data};
2913
+ if (meta) structuredContent._adport=meta;
2914
+ else delete structuredContent._adport;
2915
+ }
2916
+ return {structuredContent,...(isError?{isError:true}:{})};
2917
+ }
2918
+ function resultData(result) { return result?.structuredContent ?? {}; }
2863
2919
  async function callTool(tool,parameters,timeoutMs=30000) {
2864
2920
  const requestId=id++;
2865
2921
  return new Promise((resolve,reject)=>{
@@ -2870,7 +2926,7 @@ ${TREND_UI_SCRIPT}
2870
2926
  const request=pendingRequests.get(requestId);if (request) {clearTimeout(request.timer);pendingRequests.delete(requestId);request.resolve(result);}
2871
2927
  },error=>{const request=pendingRequests.get(requestId);if (request) {clearTimeout(request.timer);pendingRequests.delete(requestId);request.reject(error);}});
2872
2928
  } else send({jsonrpc:'2.0',id:requestId,method:'tools/call',params:{name:tool,arguments:parameters}});
2873
- });
2929
+ }).then(result=>result==null?result:normalizeToolResult(result));
2874
2930
  }
2875
2931
  ${MEDIA_UPLOAD_UI}
2876
2932
  ${MEDIA_LIBRARY_UI}
@@ -2878,11 +2934,27 @@ ${CREATIVE_UI_SCRIPT}
2878
2934
  ${PROVIDER_GALLERY_UI}
2879
2935
  ${WORKFLOW_UI}
2880
2936
  ${PLANNING_UI}
2937
+ function readPresentation(data) {
2938
+ // Some hosts forward only the public text result. These views need no
2939
+ // account scope, pagination arguments or write capability to display it.
2940
+ const name=state.host.toolInfo?.tool?.name, tool=typeof name==='string'?name.split('__').pop():undefined;
2941
+ if ((!tool || tool==='meta_list_ads') && Array.isArray(data.ads) && Array.isArray(data.creatives) &&
2942
+ data.creatives.every(item=>item?.provider==='meta' && typeof item.id==='string' && typeof item.account_id==='string')) {
2943
+ return {tool:'meta_list_ads',view:'creatives',provider:'meta'};
2944
+ }
2945
+ const rows=data.result?.rows;
2946
+ const appleMetrics=metrics=>object(metrics?.localSpend) && (Object.hasOwn(metrics,'taps') || Object.hasOwn(metrics,'totalInstalls'));
2947
+ if (Array.isArray(rows) && (tool==='apple_report' || !tool && (appleMetrics(data.result.summary?.grandTotal) ||
2948
+ rows.some(row=>appleMetrics(row?.totalMetrics) || arr(row?.granularMetrics).some(appleMetrics))))) {
2949
+ return {tool:'apple_report',view:'records',provider:'apple'};
2950
+ }
2951
+ return {};
2952
+ }
2881
2953
  function render(result) {
2882
2954
  cancelHold();clearTimeout(expiryTimer);trendResize?.disconnect();
2883
2955
  let data=resultData(result);
2884
2956
  if (!object(data)) data={value:data};
2885
- const meta = data._adport || {};
2957
+ const meta = data._adport || readPresentation(data);
2886
2958
  recordPages=null;
2887
2959
  if(providerGallery && meta.view!=='creatives' && (!providerGallery.review || meta.view!=='operation' || meta.tool!==providerGallery.review.tool || meta.accountId!==providerGallery.meta.accountId || meta.context?.project_id!==providerGallery.meta.context?.project_id)) providerGallery=null;
2888
2960
  syntheticResult = data.data_source === 'synthetic';
@@ -2921,12 +2993,13 @@ ${PLANNING_UI}
2921
2993
  hostResults.add(fingerprint);
2922
2994
  if (hostResults.size>16) hostResults.delete(hostResults.values().next().value);
2923
2995
  }
2924
- function acceptResult(result,local=false) {
2925
- if (!result || typeof result !== 'object') return;
2996
+ function acceptResult(input,local=false,hostMeta) {
2997
+ if (input==null) return;
2998
+ const result=normalizeToolResult(input,hostMeta);
2926
2999
  const incoming=resultData(result);
2927
3000
  if(!local && (providerGalleryIgnoreEcho(incoming) || mediaLibraryIgnoreEcho(incoming) || recordPagesIgnoreEcho(incoming) || readPageIgnoreEcho(incoming) || distributionIgnoreEcho(incoming))) return;
2928
- if(!local && (app.querySelector('[data-media-gallery]') && uploads.items.length>0 && ['media_prepare_upload','media_finalize_upload','media_get'].includes(incoming?._adport?.tool || result._meta?.adport?.tool) || mediaLibrary?.loading && incoming?._adport?.tool==='media_list' && mediaLibraryProject(incoming,incoming._adport)===mediaLibrary.project)) return;
2929
- const fingerprint=JSON.stringify(incoming);
3001
+ if(!local && (app.querySelector('[data-media-gallery]') && uploads.items.length>0 && ['media_prepare_upload','media_finalize_upload','media_get'].includes(incoming?._adport?.tool) || mediaLibrary?.loading && incoming?._adport?.tool==='media_list' && mediaLibraryProject(incoming,incoming._adport)===mediaLibrary.project)) return;
3002
+ const fingerprint=(result.isError?'error:':'')+JSON.stringify(incoming);
2930
3003
  // Host state updates can echo an old tool result after a local edit/apply.
2931
3004
  if (!local && state.hasLocalResult && hostResults.has(fingerprint)) return;
2932
3005
  if (local) state.hasLocalResult=true;
@@ -2943,8 +3016,7 @@ ${PLANNING_UI}
2943
3016
  if (!globals) return;
2944
3017
  const metadata = globals.toolResponseMetadata;
2945
3018
  const envelope = metadata?.mcp_tool_result || metadata?.call_tool_result;
2946
- if (envelope && typeof envelope === 'object') return acceptResult(envelope);
2947
- if (globals.toolOutput && typeof globals.toolOutput === 'object') acceptResult({structuredContent:{...globals.toolOutput,...(metadata?.adport?{_adport:metadata.adport}:{})}});
3019
+ acceptResult(object(envelope)?envelope:globals.toolOutput,false,metadata?.adport);
2948
3020
  }
2949
3021
  // Some hosts mount an error result's resource but never relay its payload.
2950
3022
  // This is a delivery fallback, not a claim about tool execution or success.
@@ -2978,12 +3050,12 @@ ${PLANNING_UI}
2978
3050
  if (message.method === 'ui/notifications/tool-result') acceptResult(message.params);
2979
3051
  if (message.method === 'ui/notifications/tool-cancelled') acceptResult({structuredContent:{cancelled:true,message:message.params?.reason}});
2980
3052
  if (message.method === 'ui/notifications/host-context-changed') {
2981
- const previousLocale = state.host.locale;
3053
+ const previousHost = state.host;
2982
3054
  state.host = {...state.host,...message.params};
2983
3055
  document.documentElement.dataset.theme = state.host.theme || '';
2984
3056
  // Size/theme updates must not rebuild the DOM: opening Details changes
2985
3057
  // the iframe height, which some hosts echo back as a context update.
2986
- if (state.result && previousLocale !== state.host.locale) {
3058
+ if (state.result && (previousHost.locale!==state.host.locale || !resultData(state.result)._adport && previousHost.toolInfo?.tool?.name!==state.host.toolInfo?.tool?.name)) {
2987
3059
  const expanded = app.querySelector('details')?.open || false;
2988
3060
  render(state.result);
2989
3061
  const details = app.querySelector('details');
@@ -3003,7 +3075,7 @@ ${PLANNING_UI}
3003
3075
 
3004
3076
  // src/index.ts
3005
3077
  var PROVIDER_IDS = ["ga4", "gsc", "gtm", "google", "meta", "tiktok", "apple", "microsoft", "reddit", "snapchat", "spotify", "pinterest", "linkedin", "x", "openai"];
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"];
3078
+ var ADPORT_UI_RESOURCE_URIS = [ADPORT_UI_URI, "ui://adport/insight-card-v40.html", "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-v40.html", "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"];
3007
3079
  var DEFAULT_MCP_ICONS = [{
3008
3080
  src: "https://app.adport.dev/icon.svg?brand=orange-dot-v2",
3009
3081
  mimeType: "image/svg+xml",
@@ -3222,4 +3294,4 @@ export {
3222
3294
  createMcpServer,
3223
3295
  runStdioServer
3224
3296
  };
3225
- //# sourceMappingURL=chunk-TEP7TOPQ.js.map
3297
+ //# sourceMappingURL=chunk-NWNTOUFX.js.map