@adport/mcp 0.5.2 → 0.6.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-6RBLUIBN.js";
5
+ } from "./chunk-YCSBIOYH.js";
6
6
 
7
7
  // src/bin.ts
8
8
  var runtime = await assembleRuntime(process.argv.includes("--demo") ? { includeMock: true } : {});
@@ -0,0 +1,608 @@
1
+ // src/index.ts
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { z } from "zod";
5
+ import { registerAppResource, registerAppTool, RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server";
6
+ import { AdportError, CredentialStore, createContext } from "@adport/core";
7
+ import { createGoogleModule } from "@adport/provider-google";
8
+ import { createMetaModule } from "@adport/provider-meta";
9
+ import { createTikTokModule } from "@adport/provider-tiktok";
10
+ import { createAppleModule } from "@adport/provider-apple";
11
+ import { createMicrosoftModule } from "@adport/provider-microsoft";
12
+ import { createRedditModule } from "@adport/provider-reddit";
13
+ import { createSnapchatModule } from "@adport/provider-snapchat";
14
+ import { createSpotifyModule } from "@adport/provider-spotify";
15
+ import { createPinterestModule } from "@adport/provider-pinterest";
16
+ import { createLinkedInModule } from "@adport/provider-linkedin";
17
+ import { createXModule } from "@adport/provider-x";
18
+
19
+ // package.json
20
+ var package_default = {
21
+ name: "@adport/mcp",
22
+ version: "0.6.1",
23
+ description: "adport MCP server \u2014 the open control plane for paid media",
24
+ license: "Apache-2.0",
25
+ type: "module",
26
+ main: "./dist/index.js",
27
+ types: "./dist/index.d.ts",
28
+ exports: {
29
+ ".": {
30
+ types: "./dist/index.d.ts",
31
+ import: "./dist/index.js"
32
+ }
33
+ },
34
+ bin: {
35
+ "adport-mcp": "./dist/bin.js"
36
+ },
37
+ files: ["dist"],
38
+ scripts: {
39
+ build: "tsup src/index.ts src/bin.ts --format esm --dts --sourcemap --clean",
40
+ "render:submission-previews": "node scripts/render-submission-previews.mjs",
41
+ test: "vitest run",
42
+ typecheck: "tsc --noEmit",
43
+ clean: "rm -rf dist"
44
+ },
45
+ dependencies: {
46
+ "@adport/core": "workspace:*",
47
+ "@adport/provider-apple": "workspace:*",
48
+ "@adport/provider-google": "workspace:*",
49
+ "@adport/provider-meta": "workspace:*",
50
+ "@adport/provider-microsoft": "workspace:*",
51
+ "@adport/provider-reddit": "workspace:*",
52
+ "@adport/provider-snapchat": "workspace:*",
53
+ "@adport/provider-spotify": "workspace:*",
54
+ "@adport/provider-pinterest": "workspace:*",
55
+ "@adport/provider-linkedin": "workspace:*",
56
+ "@adport/provider-x": "workspace:*",
57
+ "@adport/provider-tiktok": "workspace:*",
58
+ "@modelcontextprotocol/ext-apps": "^1.7.5",
59
+ "@modelcontextprotocol/sdk": "^1.30.0",
60
+ zod: "^4.4.3"
61
+ },
62
+ devDependencies: {
63
+ "@types/node": "^26.1.2",
64
+ tsup: "^8.3.0",
65
+ typescript: "^5.8.0",
66
+ vitest: "^4.1.10"
67
+ }
68
+ };
69
+
70
+ // src/ui.ts
71
+ var ADPORT_UI_URI = "ui://adport/insight-card-v2.html";
72
+ var ADPORT_UI_DOMAIN = "https://app.adport.dev";
73
+ var providerNames = {
74
+ google: "Google Ads",
75
+ meta: "Meta Ads",
76
+ tiktok: "TikTok Ads",
77
+ apple: "Apple Ads",
78
+ microsoft: "Microsoft Advertising",
79
+ reddit: "Reddit Ads",
80
+ snapchat: "Snapchat Ads",
81
+ spotify: "Spotify Ads",
82
+ pinterest: "Pinterest Ads",
83
+ linkedin: "LinkedIn Ads",
84
+ x: "X Ads",
85
+ mock: "Demo",
86
+ demo: "Synthetic demo"
87
+ };
88
+ function viewForTool(name, readOnly) {
89
+ if (name === "accounts_list") return "accounts";
90
+ if (name === "report") return "report";
91
+ if (name === "audit_run" || name === "recommendation_dismiss") return "insights";
92
+ if (!readOnly) return "operation";
93
+ if (name.startsWith("recommendation") || name.startsWith("audit_")) return "insights";
94
+ return void 0;
95
+ }
96
+ function toolTitle(name) {
97
+ if (name === "accounts_list") return "Show connected ad accounts";
98
+ if (name === "report") return "Show advertising performance";
99
+ return name.split("_").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
100
+ }
101
+ function toolInvocationLabels(view) {
102
+ switch (view) {
103
+ case "accounts":
104
+ return { invoking: "Loading ad accounts\u2026", invoked: "Ad accounts ready" };
105
+ case "report":
106
+ return { invoking: "Analyzing performance\u2026", invoked: "Performance ready" };
107
+ // Descriptor labels cover both preview and apply; the card shows the actual result.
108
+ case "operation":
109
+ return { invoking: "Processing change\u2026", invoked: "Change result ready" };
110
+ case "insights":
111
+ return { invoking: "Reviewing opportunities\u2026", invoked: "Opportunities ready" };
112
+ }
113
+ }
114
+ function structuredResult(tool, view, result, approval) {
115
+ const payload = result && typeof result === "object" && !Array.isArray(result) ? result : { value: result };
116
+ return {
117
+ ...payload,
118
+ _adport: {
119
+ tool,
120
+ view,
121
+ providerNames,
122
+ ...approval ? { approval } : {}
123
+ }
124
+ };
125
+ }
126
+ var ADPORT_UI_HTML = String.raw`<!doctype html>
127
+ <html lang="en">
128
+ <head>
129
+ <meta charset="utf-8" />
130
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
131
+ <meta name="color-scheme" content="light dark" />
132
+ <title>Adport insight</title>
133
+ <style>
134
+ :root {
135
+ --ink: var(--color-text-primary, #171717);
136
+ --muted: var(--color-text-secondary, #6f6f73);
137
+ --faint: var(--color-text-tertiary, #949499);
138
+ --paper: var(--color-background-primary, #ffffff);
139
+ --soft: var(--color-background-secondary, #f6f6f4);
140
+ --line: var(--color-border-secondary, rgba(23,23,23,.11));
141
+ --orange: #ff5a1f;
142
+ --green: #16845b;
143
+ --red: #c8392f;
144
+ --amber: #a86500;
145
+ --radius: var(--border-radius-lg, 18px);
146
+ --sans: var(--font-sans, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif);
147
+ --mono: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
148
+ }
149
+ * { box-sizing: border-box }
150
+ html, body { margin: 0; min-width: 0; background: transparent; color: var(--ink); font-family: var(--sans) }
151
+ body { padding: 2px; }
152
+ button { font: inherit }
153
+ .shell { overflow: hidden; border: 1px solid var(--line); border-radius: var(--radius); background: var(--paper); box-shadow: 0 10px 32px rgba(20,20,20,.07) }
154
+ .top { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:14px 16px 10px }
155
+ .brand { display:flex; align-items:center; gap:9px; min-width:0 }
156
+ .dot { width:10px; height:10px; border-radius:99px; background:var(--orange); box-shadow:0 0 0 5px color-mix(in srgb,var(--orange) 12%,transparent) }
157
+ .brand b { font-size:12px; letter-spacing:-.02em }
158
+ .context { color:var(--muted); font-size:11px; text-align:right }
159
+ .content { padding:4px 16px 16px }
160
+ .kpis { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:8px; margin-bottom:15px }
161
+ .kpi { min-width:0; padding:12px; border-radius:13px; background:var(--soft); border:1px solid color-mix(in srgb,var(--line) 70%,transparent) }
162
+ button.kpi { cursor:pointer; color:var(--ink); text-align:left }
163
+ button.kpi[aria-pressed="true"] { border-color:color-mix(in srgb,var(--orange) 65%,var(--line)) }
164
+ .kpi small { display:block; color:var(--faint); font:600 9px/1.2 var(--mono); letter-spacing:.11em; text-transform:uppercase }
165
+ .kpi strong { display:block; overflow:hidden; margin-top:8px; font-size:clamp(17px,3vw,24px); line-height:1; letter-spacing:-.04em; text-overflow:ellipsis }
166
+ .panel { min-width:0; padding:13px; border:1px solid var(--line); border-radius:14px }
167
+ .panel-head { display:flex; align-items:center; justify-content:space-between; gap:12px; margin-bottom:12px }
168
+ .panel-head b { font-size:12px }
169
+ .panel-head span { color:var(--faint); font:500 9px/1 var(--mono); text-transform:uppercase; letter-spacing:.1em }
170
+ .bars { display:grid; gap:9px }
171
+ .bar-row { display:grid; grid-template-columns:minmax(100px,1fr) minmax(60px,2fr) auto; align-items:center; gap:9px; font-size:11px }
172
+ .bar-name { display:flex; align-items:center; gap:7px; min-width:0 }
173
+ .bar-name > span:last-child { overflow:hidden; white-space:nowrap; text-overflow:ellipsis }
174
+ .bar-name .logo { width:22px; height:22px; padding:4px; border-radius:6px }
175
+ .track { height:7px; overflow:hidden; border-radius:99px; background:var(--soft) }
176
+ .fill { height:100%; border-radius:99px; background:linear-gradient(90deg,var(--orange),#ff985e) }
177
+ .tabs { display:flex; gap:6px; overflow:auto; padding-bottom:12px }
178
+ .tabs button { flex:0 0 auto; cursor:pointer; padding:8px 12px; border:1px solid var(--line); border-radius:99px; background:var(--paper); color:var(--muted); font-size:12px }
179
+ .tabs button[aria-pressed="true"] { color:var(--ink); border-color:var(--orange); background:color-mix(in srgb,var(--orange) 8%,var(--paper)) }
180
+ button:focus-visible { outline:2px solid var(--orange); outline-offset:2px }
181
+ .notice { padding:10px 12px; margin:0 0 12px; border-radius:10px; background:var(--soft); color:var(--muted); font-size:12px; line-height:1.45 }
182
+ .bar-value { color:var(--muted); font:600 10px/1 var(--mono); white-space:nowrap }
183
+ .list { display:grid; gap:7px }
184
+ .row { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:10px 11px; border:1px solid var(--line); border-radius:12px }
185
+ .identity { display:flex; align-items:center; gap:10px; min-width:0 }
186
+ .logo { display:grid; place-items:center; flex:0 0 auto; width:29px; height:29px; padding:6px; border:1px solid var(--line); border-radius:9px; color:var(--ink); background:var(--paper); font-weight:800; font-size:10px }
187
+ .logo svg { display:block; width:100%; height:100% }
188
+ .logo.reddit { background:#ff4500 }.logo.linkedin { background:#0a66c2 }.logo.spotify { background:#1db954 }.logo.pinterest { background:#e60023 }.logo.x { background:#111 }.logo.snapchat { background:#fffc00;color:#111 }
189
+ .identity-copy { min-width:0 }
190
+ .identity-copy b, .identity-copy span { display:block; overflow:hidden; white-space:nowrap; text-overflow:ellipsis }
191
+ .identity-copy b { font-size:12px }.identity-copy span { margin-top:3px; color:var(--muted); font-size:10px }
192
+ .pill { flex:0 0 auto; padding:5px 8px; border-radius:99px; color:var(--green); background:color-mix(in srgb,var(--green) 10%,transparent); font:700 9px/1 var(--mono); letter-spacing:.08em; text-transform:uppercase }
193
+ .pill.warn { color:var(--amber); background:color-mix(in srgb,var(--amber) 11%,transparent) }
194
+ .pill.danger { color:var(--red); background:color-mix(in srgb,var(--red) 10%,transparent) }
195
+ .pill.neutral { color:var(--muted); background:var(--soft) }
196
+ .operation-name { margin:2px 0 16px; font-size:14px; line-height:1.4; font-weight:600; overflow-wrap:anywhere }
197
+ .comparison { width:100%; border-collapse:collapse; table-layout:fixed; margin-bottom:12px }
198
+ .comparison th { padding:0 8px 8px; color:var(--muted); font-size:10px; font-weight:500; text-align:left }
199
+ .comparison td { border-top:1px solid var(--line); padding:12px 8px; font-size:14px; overflow-wrap:anywhere }
200
+ .comparison td:first-child { color:var(--muted); font-size:11px }
201
+ .comparison td:last-child { font-weight:600 }
202
+ .comparison .changed { color:var(--orange) }
203
+ .adjustment { margin:8px 0; color:var(--amber); font-size:11px; line-height:1.4 }
204
+ .approval { display:flex; align-items:center; gap:10px; flex-wrap:wrap; margin:12px 0 }
205
+ .approve { cursor:pointer; padding:9px 16px; border:0; border-radius:99px; background:var(--ink); color:var(--paper); font-size:12px; font-weight:700 }
206
+ .approve:disabled { cursor:default; opacity:.55 }
207
+ details { border-top:1px solid var(--line); padding-top:10px; color:var(--muted); font-size:11px; line-height:1.5 }
208
+ summary { cursor:pointer; width:fit-content; padding:3px 0 }
209
+ summary:focus-visible { outline:2px solid var(--orange); outline-offset:3px }
210
+ details p { margin:8px 0; overflow-wrap:anywhere }
211
+ .empty { padding:26px 12px; text-align:center; color:var(--muted); font-size:12px }
212
+ @media (max-width:620px) { .kpis { grid-template-columns:repeat(2,minmax(0,1fr)) }.top,.content { padding-left:12px; padding-right:12px } }
213
+ @media (max-width:420px) { .bar-row { grid-template-columns:minmax(0,1fr) auto; gap:5px }.bar-name { grid-column:1/-1 }.bar-name > span:last-child { white-space:normal }.bars { gap:12px } }
214
+ @media (prefers-reduced-motion:reduce) { * { animation:none!important; transition:none!important } }
215
+ :root[data-theme="dark"] { --ink:#f5f5f3;--muted:#aaa9ad;--faint:#a09fa5;--paper:#171717;--soft:#222220;--line:rgba(255,255,255,.11) }
216
+ @media (prefers-color-scheme:dark) { :root:not([data-theme="light"]) { --ink:#f5f5f3;--muted:#aaa9ad;--faint:#a09fa5;--paper:#171717;--soft:#222220;--line:rgba(255,255,255,.11) } }
217
+ </style>
218
+ </head>
219
+ <body>
220
+ <main id="app" class="shell" aria-live="polite">
221
+ <header class="top"><div class="brand"><span class="dot"></span><b>adport.dev</b></div></header>
222
+ <section class="content"><div class="empty">Loading…</div></section>
223
+ </main>
224
+ <script>
225
+ (() => {
226
+ const app = document.getElementById('app');
227
+ const state = { host: {}, result: null, reportGroup: null, reportMetric: 'spend', approving: false, approvalError: '' };
228
+ const esc = (value) => String(value ?? '').replace(/[&<>"']/g, (c) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
229
+ const arr = (value) => Array.isArray(value) ? value : [];
230
+ const num = (value) => Number.isFinite(Number(value)) ? Number(value) : 0;
231
+ const money = (value, currency, maximumFractionDigits=2) => currency
232
+ ? new Intl.NumberFormat(state.host.locale || 'en', { style:'currency', currency, maximumFractionDigits }).format(num(value))
233
+ : new Intl.NumberFormat(state.host.locale || 'en', { maximumFractionDigits }).format(num(value));
234
+ const compact = (value) => new Intl.NumberFormat(state.host.locale || 'en', { notation:'compact', maximumFractionDigits:1 }).format(num(value));
235
+ const available = (value) => typeof value === 'number' && Number.isFinite(value);
236
+ const total = (rows, key) => rows.length && rows.every(r => available(r.metrics?.[key])) ? rows.reduce((sum,r) => sum+r.metrics[key],0) : null;
237
+ const rowReturn = (row) => {
238
+ const m=row.metrics || {};
239
+ if (available(m.conversion_value)) return m.conversion_value;
240
+ // A report can request ROAS without conversion_value. Weight reported
241
+ // ratios by spend; never average campaign ratios or infer missing revenue.
242
+ const value=available(m.spend) && m.spend>0 && available(m.roas) ? m.spend*m.roas : null;
243
+ return available(value) ? value : null;
244
+ };
245
+ const currencyOf = (row) => typeof row.currency === 'string' && /^[A-Z]{3}$/.test(row.currency) ? row.currency : null;
246
+ const statusOf = (status) => !status || /unknown|unspecified/i.test(status) ? {label:'Status unavailable',tone:'neutral'} : /disabled|removed|inactive|closed|suspended/i.test(status) ? {label:status,tone:'danger'} : /paused|disable$/i.test(status) ? {label:status,tone:'warn'} : /^(enabled|active|approved)$/i.test(status) ? {label:status,tone:''} : {label:status,tone:'neutral'};
247
+ const notices = (data) => [...arr(data.errors).map(e => (e.provider || 'Provider')+': '+(e.message || 'Read failed')), ...arr(data.warnings).map(e => e.message || 'Some metadata is unavailable'), ...(data.truncated ? ['Partial result: row limit reached. Totals and charts cover returned rows only.'] : [])].map(text => '<p class="notice">'+esc(text)+'</p>').join('');
248
+ const providerName = (id, names) => names?.[id] || String(id || 'Provider');
249
+ const initials = (id) => ({snapchat:'S',spotify:'S',pinterest:'P',linkedin:'in',x:'X'}[id] || String(id || '?').slice(0,2).toUpperCase());
250
+ const providerSvg = {
251
+ // Unmodified official Ghost paths, matching cloud/components/snapchat-logo.tsx.
252
+ snapchat:"<svg viewBox=\"0 0 1024 1024\" aria-hidden=\"true\"> <path fill=\"#fff\" d=\"M992.5,756.3c-4.2-13.9-24.3-23.7-24.3-23.7l0,0c-1.9-1-3.6-1.9-5-2.6c-33.5-16.2-63.2-35.7-88.2-57.8 c-20.1-17.8-37.3-37.4-51.1-58.2c-16.9-25.4-24.8-46.6-28.2-58.1c-1.9-7.5-1.6-10.5,0-14.4c1.3-3.3,5.2-6.4,7-7.9 c11.3-8,29.5-19.8,40.7-27c9.7-6.3,18-11.7,22.9-15.1c15.7-11,26.5-22.2,32.8-34.3c8.2-15.6,9.2-32.8,2.8-49.7 c-8.6-22.8-29.9-36.4-57-36.4c-6,0-12.2,0.7-18.4,2c-15.5,3.4-30.2,8.9-42.5,13.7c-0.9,0.4-1.9-0.3-1.8-1.3 c1.3-30.5,2.8-71.5-0.6-110.4c-3-35.2-10.3-64.9-22.1-90.8c-11.9-26-27.4-45.2-39.5-59.1C708.5,112,688.2,92.5,657.6,75 C614.6,50.4,565.6,37.9,512,37.9c-53.5,0-102.4,12.5-145.5,37.1c-32.4,18.5-53.1,39.4-62.5,50.2c-12.1,13.9-27.6,33.1-39.5,59.1 c-11.9,25.9-19.1,55.5-22.1,90.8c-3.4,39.1-2,76.8-0.6,110.4c0,1-0.9,1.7-1.9,1.3c-12.3-4.8-27-10.3-42.5-13.7 c-6.1-1.3-12.3-2-18.4-2c-27,0-48.3,13.6-57,36.4c-6.4,16.9-5.4,34.1,2.8,49.7c6.4,12.1,17.1,23.3,32.8,34.3 c4.8,3.4,13.2,8.8,22.9,15.1c10.9,7.1,28.6,18.6,40,26.5c1.4,1,6.2,4.6,7.7,8.4c1.6,4,1.9,7-0.2,15c-3.5,11.6-11.4,32.6-28,57.5 c-13.8,20.9-31,40.4-51.1,58.2c-25,22.1-54.7,41.6-88.2,57.8c-1.6,0.8-3.5,1.7-5.5,2.9l0,0c0,0-20,10.2-23.8,23.4 c-5.6,19.5,9.3,37.8,24.4,47.6c24.8,16,55,24.6,72.5,29.3c4.9,1.3,9.3,2.5,13.3,3.7c2.5,0.8,8.8,3.2,11.5,6.7 c3.4,4.4,3.8,9.8,5,15.9v0c1.9,10.3,6.2,23,18.9,31.8c14,9.6,31.7,10.3,54.2,11.2c23.5,0.9,52.7,2,86.2,13.1 c15.5,5.1,29.6,13.8,45.8,23.8c34,20.9,76.3,46.9,148.5,46.9c72.3,0,114.9-26.1,149.1-47.1c16.2-9.9,30.1-18.5,45.3-23.5 c33.5-11.1,62.7-12.2,86.2-13.1c22.5-0.9,40.2-1.5,54.2-11.2c13.6-9.4,17.5-23.4,19.3-33.9c1-5.2,1.6-9.9,4.6-13.7 c2.6-3.3,8.4-5.6,11.1-6.5c4.1-1.3,8.7-2.5,13.8-3.9c17.5-4.7,39.5-10.2,66.2-25.3C993.7,789.8,995.9,767.4,992.5,756.3z\" /> <path fill=\"#000\" d=\"M1020.3,745.5c-7.1-19.4-20.7-29.7-36.1-38.3c-2.9-1.7-5.6-3.1-7.8-4.1c-4.6-2.4-9.3-4.7-14-7.1 c-48.1-25.5-85.7-57.7-111.7-95.8c-8.8-12.9-14.9-24.5-19.2-34c-2.2-6.4-2.1-10-0.5-13.3c1.2-2.5,4.4-5.1,6.2-6.4 c8.3-5.5,16.8-11,22.6-14.7c10.3-6.7,18.5-12,23.7-15.6c19.8-13.8,33.6-28.5,42.2-44.9c12.2-23.1,13.7-49.5,4.3-74.3 c-13-34.4-45.6-55.8-85-55.8c-8.2,0-16.5,0.9-24.7,2.7c-2.2,0.5-4.3,1-6.4,1.5c0.4-23.4-0.2-48.4-2.3-72.8 c-7.4-86-37.5-131.1-68.9-167c-13.1-15-35.9-36.9-70.1-56.5C624.9,21.7,570.9,7.9,512,7.9c-58.7,0-112.7,13.8-160.4,41.1 c-34.4,19.6-57.2,41.6-70.2,56.5c-31.4,35.9-61.5,81-68.9,167c-2.1,24.4-2.6,49.4-2.3,72.8c-2.1-0.5-4.3-1-6.4-1.5 c-8.2-1.8-16.6-2.7-24.7-2.7c-39.4,0-72,21.4-85,55.8c-9.4,24.8-7.9,51.2,4.3,74.3c8.6,16.4,22.5,31.1,42.2,44.9 c5.3,3.7,13.4,9,23.7,15.6c5.6,3.6,13.7,8.9,21.7,14.2c1.2,0.8,5.5,4,7,7c1.7,3.4,1.7,7.1-0.8,13.9c-4.2,9.3-10.3,20.7-18.9,33.3 c-25.5,37.3-62,68.9-108.5,94.1c-24.7,13.1-50.3,21.8-61.1,51.2c-8.2,22.2-2.8,47.5,17.9,68.8l0,0c6.8,7.3,15.4,13.8,26.2,19.8 c25.4,14,47,20.9,64,25.6c3,0.9,9.9,3.1,12.9,5.8c7.6,6.6,6.5,16.6,16.6,31.2c6.1,9.1,13.1,15.3,18.9,19.3 c21.1,14.6,44.9,15.5,70.1,16.5c22.7,0.9,48.5,1.9,77.9,11.6c12.2,4,24.9,11.8,39.5,20.8c35.2,21.7,83.5,51.3,164.2,51.3 c80.8,0,129.3-29.8,164.8-51.5c14.6-8.9,27.2-16.7,39-20.6c29.4-9.7,55.2-10.7,77.9-11.6c25.2-1,48.9-1.9,70.1-16.5 c6.6-4.6,15-12.1,21.6-23.5c7.2-12.3,7.1-21,13.9-26.9c2.8-2.4,8.9-4.5,12.2-5.5c17.1-4.7,39-11.6,64.9-25.9 c11.5-6.3,20.4-13.2,27.5-21.1c0.1-0.1,0.2-0.2,0.3-0.3C1023.4,791.7,1028.3,767.2,1020.3,745.5z M948.6,784 c-43.8,24.2-72.9,21.6-95.5,36.1c-19.2,12.4-7.9,39.1-21.8,48.7c-17.2,11.9-67.9-0.8-133.4,20.8c-54,17.9-88.5,69.2-185.8,69.2 c-97.5,0-131-51.1-185.8-69.2c-65.5-21.6-116.3-8.9-133.4-20.8c-13.9-9.6-2.6-36.3-21.8-48.7c-22.6-14.6-51.7-12-95.5-36.1 c-27.9-15.4-12.1-24.9-2.8-29.4c158.6-76.7,183.8-195.3,185-204.2c1.4-10.6,2.9-19-8.8-29.9c-11.3-10.5-61.6-41.6-75.5-51.3 c-23.1-16.1-33.2-32.2-25.7-52c5.2-13.7,18-18.8,31.5-18.8c4.2,0,8.5,0.5,12.6,1.4c25.3,5.5,49.9,18.2,64.1,21.6 c2,0.5,3.7,0.7,5.2,0.7c7.6,0,10.2-3.8,9.7-12.5c-1.6-27.7-5.6-81.7-1.2-132.2c6-69.4,28.4-103.8,55-134.3 c12.8-14.6,72.8-78,187.5-78c115,0,174.7,63.4,187.5,78c26.6,30.4,49,64.8,55,134.3c4.4,50.5,0.6,104.5-1.2,132.2 c-0.6,9.1,2.2,12.5,9.7,12.5c1.5,0,3.3-0.2,5.2-0.7c14.2-3.4,38.8-16.1,64.1-21.6c4.1-0.9,8.4-1.4,12.6-1.4 c13.5,0,26.3,5.2,31.5,18.8c7.5,19.8-2.7,35.9-25.7,52c-13.9,9.7-64.2,40.8-75.5,51.3c-11.7,10.8-10.2,19.2-8.8,29.9 c1.1,8.9,26.4,127.5,185,204.2C960.6,759.1,976.5,768.6,948.6,784z\" /> </svg>",
253
+ google:'<svg viewBox="0 0 24 24"><path fill="#34a853" d="M4 22.93a4 4 0 1 1 0-8 4 4 0 0 1 0 8Z"/><path fill="#4285f4" d="M23.464 16.929 15.463 3.072A4 4 0 0 0 8.534 7.072l8.001 13.857a4 4 0 0 0 6.929-4Z"/><path fill="#fbbc04" d="M7.514 4.844 1.565 15.148A4.5 4.5 0 0 1 4 14.43a4.5 4.5 0 0 1 4.494 4.715l3.217-5.573-3.61-6.25a4 4 0 0 1-.587-2.478Z"/></svg>',
254
+ meta:'<svg viewBox="0 0 24 24"><path fill="#0866ff" d="M6.915 4.03C2.484 4.03 0 9.95 0 14.449c0 3.37 1.276 5.521 4.439 5.521 2.93 0 4.146-2.574 6.628-6.764l.942-1.664 2.335 3.895c1.883 3.15 3.38 4.533 5.53 4.533 2.788 0 4.126-1.93 4.126-5.56 0-5.53-2.73-10.38-6.8-10.38-2.04 0-3.835 1.53-5.173 3.348C10.16 5.01 8.593 4.03 6.915 4.03Zm-.04 2.606c1.55 0 2.445 1.193 3.908 3.025l-1.02 1.566c-2.22 3.41-3.576 6.155-5.323 6.155-1.23 0-2.154-1.075-2.154-2.9 0-3.755 2.088-7.846 4.588-7.846Zm10.2-.553c2.488 0 4.639 4.054 4.639 8.4 0 1.547-.368 2.899-1.839 2.899-1.193 0-2.027-1.42-4.496-5.362l-1.872-3.008c1.12-1.814 2.248-2.929 3.559-2.929Z"/></svg>',
255
+ tiktok:'<svg viewBox="0 0 58 58"><path fill="#2dccd3" d="M25.98 0v37.68c0 4.94-3.55 8.11-7.88 8.11-1.43 0-2.79-.33-3.97-.95 1.5 1.91 3.87 3.01 6.47 3.01 4.32 0 7.87-3.17 7.87-8.11V2.06h6.85A20.3 20.3 0 0 1 34.87 0h-8.89Z"/><path fill="#f1204a" d="M41.73 11.11a17.48 17.48 0 0 1-4.37-9.05h-2.04c1.16 4.23 3.56 7.18 6.41 9.05Zm7.63 11.37a19.31 19.31 0 0 1-11-2.97c3.84 3.84 8.5 5.03 13.5 5.03v-8.82a17.4 17.4 0 0 1-2.5-.37v7.13Z"/><path fill="currentColor" d="M35.32 2.06h-6.85v37.68c0 4.94-3.55 8.11-7.87 8.11-2.6 0-4.97-1.1-6.47-3.01-2.48-1.29-4.19-3.82-4.19-7.16 0-5.71 4.47-8.71 10.42-8.09v-7.68C10.63 21.93 2.49 29.73 2.49 39.4c0 5.16 2.04 9.71 5.32 12.96 2.89 1.97 6.39 3.11 10.15 3.11 8.69 0 17.91-6.38 17.91-18.41V17.45c.8.8 1.63 1.48 2.49 2.06a19.31 19.31 0 0 0 11 2.97v-7.13a16.14 16.14 0 0 1-7.63-4.24c-2.85-1.87-5.25-4.82-6.41-9.05Z"/></svg>',
256
+ apple:'<svg viewBox="0 0 24 24"><path fill="currentColor" d="M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09Zm3.377-3.065C16.372 2.819 16.929 1.403 16.774 0c-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.56-1.701Z"/></svg>',
257
+ microsoft:'<svg viewBox="0 0 24 24"><path fill="#f25022" d="M0 0h11.4v11.4H0Z"/><path fill="#7fba00" d="M12.6 0H24v11.4H12.6Z"/><path fill="#00a4ef" d="M0 12.6h11.4V24H0Z"/><path fill="#ffb900" d="M12.6 12.6H24V24H12.6Z"/></svg>',
258
+ reddit:'<svg viewBox="0 0 24 24"><path fill="#ff4500" d="M12 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0Zm5.01 4.744c.688 0 1.25.561 1.25 1.249a1.25 1.25 0 0 1-2.498.056l-2.597-.547-.8 3.747c1.824.07 3.48.632 4.674 1.488.308-.309.73-.491 1.207-.491.968 0 1.754.786 1.754 1.754 0 .716-.435 1.333-1.01 1.614.028.169.042.342.042.52 0 2.694-3.13 4.87-7.004 4.87-3.874 0-7.004-2.176-7.004-4.87 0-.183.015-.366.043-.534A1.748 1.748 0 0 1 4.028 12c0-.968.786-1.754 1.754-1.754.463 0 .898.196 1.207.49 1.207-.883 2.878-1.43 4.744-1.487l.885-4.182a.342.342 0 0 1 .378-.239l2.906.617a1.214 1.214 0 0 1 1.108-.701Z"/></svg>'
259
+ };
260
+ const logo = (id) => '<span class="logo '+esc(id)+'" aria-hidden="true">'+(providerSvg[id] || esc(initials(id)))+'</span>';
261
+ let syntheticResult = false;
262
+ const chrome = (body, context) => '<header class="top"><div class="brand"><span class="dot"></span><b>adport.dev</b></div><span class="context">'+(syntheticResult?'Synthetic demo · ':'')+esc(context || '')+'</span></header><section class="content">'+body+'</section>';
263
+ function renderAccounts(data, meta) {
264
+ const accounts = arr(data.accounts), errors = arr(data.errors), names = meta.providerNames || {};
265
+ const body = notices(data)+(accounts.length ? '<div class="list">'+accounts.map(a => { const status=statusOf(a.status); return '<div class="row"><div class="identity">'+logo(a.provider)+'<div class="identity-copy"><b>'+esc(a.name || 'Ad account')+'</b><span>'+esc(providerName(a.provider,names))+' · '+esc(a.id)+(a.currency ? ' · '+esc(a.currency) : '')+'</span></div></div><span class="pill '+status.tone+'">'+esc(status.label)+'</span></div>'; }).join('')+'</div>' : '<div class="empty">'+(errors.length ? 'Account inventory could not be fully loaded.' : 'No accessible ad accounts were returned.')+'</div>');
266
+ app.innerHTML = chrome(body, accounts.length+' account'+(accounts.length===1?'':'s'));
267
+ }
268
+ function renderReport(data) {
269
+ const groups = new Map();
270
+ for (const row of arr(data.rows)) {
271
+ const currency=currencyOf(row), key=currency || JSON.stringify([row.provider,row.accountId]);
272
+ if (!groups.has(key)) groups.set(key,{key,currency,label:currency || (row.provider+' · '+row.accountId),rows:[]});
273
+ groups.get(key).rows.push(row);
274
+ }
275
+ const choices=[...groups.values()];
276
+ const selected=groups.get(state.reportGroup) || choices[0];
277
+ const rows=selected?.rows || [], currency=selected?.currency;
278
+ state.reportGroup=selected?.key;
279
+ const tabs=choices.length>1 ? '<div class="tabs" role="group" aria-label="Report currency or account">'+choices.map((g,i)=>'<button data-group="'+i+'" aria-pressed="'+(g===selected)+'">'+esc(g.label)+'</button>').join('')+'</div>' : '';
280
+ const summary=arr(data.summary?.groups).find(group=>group.key===selected?.key)?.metrics;
281
+ const aggregate=key=>summary ? (available(summary[key])?summary[key]:null) : total(rows,key);
282
+ const spend=aggregate('spend'), returns=rows.map(rowReturn);
283
+ const value=returns.length && returns.every(available) ? returns.reduce((sum,value)=>sum+value,0) : null;
284
+ const ratio=summary ? summary.roas : spend>0 && value!==null ? value/spend : null;
285
+ const roas=available(ratio) ? ratio.toFixed(2)+'×' : '—';
286
+ const metric=state.reportMetric, labels={spend:'Spend',clicks:'Clicks',conversions:'Conversions',roas:'ROAS'};
287
+ const metricValue=r=>metric==='roas' ? (available(r.metrics?.conversion_value) && r.metrics?.spend>0 ? r.metrics.conversion_value/r.metrics.spend : r.metrics?.roas) : r.metrics?.[metric];
288
+ const format=value=>metric==='spend'?money(value,currency):metric==='roas'?value.toFixed(2)+'×':compact(value);
289
+ const ranked=[...rows].filter(r=>available(metricValue(r))).sort((a,b)=>metricValue(b)-metricValue(a)).slice(0,6), max=Math.max(1,...ranked.map(metricValue));
290
+ const bars=ranked.length ? ranked.map(r=>'<div class="bar-row"><span class="bar-name" title="'+esc(r.entity?.name || r.entity?.id)+'">'+logo(r.provider)+'<span>'+esc(r.entity?.name || r.entity?.id || 'Entity')+'</span></span><span class="track" aria-hidden="true"><span class="fill" style="display:block;width:'+Math.max(0,metricValue(r)/max*100).toFixed(1)+'%"></span></span><span class="bar-value">'+esc(format(metricValue(r)))+'</span></div>').join('') : '<div class="empty">No '+esc(labels[metric])+' values were returned.</div>';
291
+ const kpi=(key,label,value)=>'<button class="kpi" data-metric="'+key+'" aria-pressed="'+(metric===key)+'" aria-label="Chart '+esc(label)+'"><small>'+esc(label)+'</small><strong>'+esc(value)+'</strong></button>';
292
+ const period=typeof data.date_range==='string' ? data.date_range.replaceAll('_',' ') : data.date_range ? data.date_range.start+' – '+data.date_range.end : 'Selected period';
293
+ const body=notices(data)+tabs+(rows.length ? (!currency?'<p class="notice">Currency unavailable. These values belong to this account only; no cross-account money total is calculated.</p>':'')+'<div class="kpis" role="group" aria-label="Chart metric">'+kpi('spend','Spend',spend===null?'—':money(spend,currency))+kpi('clicks','Clicks',total(rows,'clicks')===null?'—':compact(total(rows,'clicks')))+kpi('conversions','Conversions',total(rows,'conversions')===null?'—':compact(total(rows,'conversions')))+kpi('roas','ROAS',roas)+'</div><div class="panel"><div class="panel-head"><b>'+esc(labels[metric])+'</b><span>Top '+ranked.length+' of '+rows.length+' rows</span></div><div class="bars">'+bars+'</div></div>' : '<div class="empty">'+(arr(data.errors).length?'Report unavailable for the requested providers.':'No rows returned for this period.')+'</div>');
294
+ app.innerHTML=chrome(body,period+(currency?' · '+currency:''));
295
+ app.querySelectorAll('[data-group]').forEach(button=>button.addEventListener('click',()=>{state.reportGroup=choices[Number(button.dataset.group)].key;renderReport(data);}));
296
+ app.querySelectorAll('[data-metric]').forEach(button=>button.addEventListener('click',()=>{state.reportMetric=button.dataset.metric;renderReport(data);}));
297
+ }
298
+ function renderOperation(data, meta) {
299
+ if (meta.tool === 'recommendation_apply' && data.result) data = data.result;
300
+ const preview = data.preview || {}, pending = data.pending_operation_id, applied = data.status === 'applied' || data.applied === true;
301
+ const changes = arr(preview.changes), coercions = arr(preview.coercions), deltas = arr(preview.budgetDeltas);
302
+ // Review amounts must preserve micros; rounded report totals are not suitable for consent.
303
+ const comparisons=deltas.map(v=>{const currency=currencyOf(v);return {label:(v.target || 'Budget')+(currency?' · '+currency:' (account units)'),before:available(v.fromMicros)?money(v.fromMicros/1e6,currency,6):'—',after:available(v.toMicros)?money(v.toMicros/1e6,currency,6):'—'};});
304
+ // Split only explicit field/value arrows. Freeform JSON updates still
305
+ // show the proposed payload, but never claim a previous value.
306
+ for (const change of changes) {
307
+ const match=String(change).match(/^~\s+(?:.+?\s+)?(status|configured_status|bidding_strategy|delivery|bid|dailyBudget\.value|DailyBudget|value)\s*:?\s*(.*?)\s*→\s*(.+)$/i);
308
+ if (match) { const label=match[1].replaceAll('_',' ').replace(/([a-z])([A-Z])/g,'$1 $2');comparisons.push({label:label[0].toUpperCase()+label.slice(1),before:match[2].trim() || '—',after:match[3].trim()}); }
309
+ }
310
+ // Other provider plans still have a concrete change list. Show the
311
+ // proposed effect without pretending we fetched the previous object.
312
+ for (const change of changes.slice(0,12)) {
313
+ const value=String(change).trim();
314
+ if (/^~\s+(?:.+?\s+)?(status|configured_status|bidding_strategy|delivery|bid|dailyBudget\.value|DailyBudget|value)\s*:?\s*.*?\s*→\s*.+$/i.test(value)) continue;
315
+ if (deltas.length && /\b(budget|amount_micros)\b/i.test(value) && /\s*→\s*/.test(value)) continue;
316
+ const kind=value[0];
317
+ comparisons.push({
318
+ label:kind==='+'?'Create':kind==='-'?'Remove':kind==='~'?'Update':'Change',
319
+ before:kind==='+'?'Not present':kind==='-'?value.slice(1).trim():'Not provided',
320
+ after:kind==='-'?'Removed':/^[+~!]\s*/.test(value)?value.replace(/^[+~!]\s*/,''):value,
321
+ });
322
+ }
323
+ if (!comparisons.length && preview.summary) comparisons.push({label:'Proposed change',before:'Not provided',after:String(preview.summary)});
324
+ const title=String(preview.summary || '').match(/"([^"]+)"/)?.[1] || (comparisons.length ? '' : preview.summary);
325
+ const validation=preview.serverValidated===true?'server validated':preview.serverValidated===false?'local preview · not server validated':'validation not reported';
326
+ const table=comparisons.length?'<table class="comparison" aria-label="Before and after"><thead><tr><th scope="col">Change</th><th scope="col">Before</th><th scope="col">After</th></tr></thead><tbody>'+comparisons.map(v=>'<tr><td>'+esc(v.label)+'</td><td>'+esc(v.before)+'</td><td class="'+(v.before!==v.after?'changed':'')+'">'+esc(v.after)+'</td></tr>').join('')+'</tbody></table>':'<p class="notice">No change details were returned. Review the tool response before applying.</p>';
327
+ const approval=meta.approval;
328
+ const canApprove=typeof pending==='string' && pending.length>0 && typeof preview.summary==='string' && preview.summary.trim() && approval?.arguments && typeof approval.arguments==='object' && !Array.isArray(approval.arguments) && typeof meta.tool==='string';
329
+ const action=canApprove?'<div class="approval"><button class="approve" data-approve="true" '+(state.approving?'disabled':'')+'>'+(state.approving?'Applying…':'Approve and apply')+'</button><span class="context">Expires '+esc(data.expires_at || 'soon')+'</span></div>':'';
330
+ const body=(title?'<p class="operation-name">'+esc(title)+'</p>':'')+table+(changes.length>12?'<p class="notice">Showing 12 of '+changes.length+' changes. All changes are in Details.</p>':'')+coercions.map(v=>'<p class="adjustment">'+esc(v)+'</p>').join('')+(state.approvalError?'<p class="notice" role="alert">'+esc(state.approvalError)+'</p>':'')+action+(applied?'<p class="notice">Applied. '+esc(preview.summary || 'The change was submitted.')+'</p>':'')+'<details><summary>Details</summary><p>'+esc(validation)+'</p><p>'+esc(preview.summary || 'No change details returned.')+'</p>'+changes.map(v=>'<p>'+esc(v)+'</p>').join('')+(pending?'<p>Nothing has been changed. Apply requires the matching pending operation token before it expires.</p>':'')+'<p>'+esc(meta.tool || '')+'</p></details>';
331
+ app.innerHTML = chrome(body, applied?'Applied':pending?'Preview · Not applied':'Result');
332
+ if (canApprove) app.querySelectorAll('[data-approve]').forEach(button=>button.addEventListener('click',()=>approve(meta.tool,approval.arguments,pending)));
333
+ }
334
+ const pendingRequests=new Map();
335
+ async function approve(tool,args,pending) {
336
+ if (state.approving || !state.result) return;
337
+ state.approving=true;state.approvalError='';render(state.result);
338
+ const requestId=id++;
339
+ const response=new Promise((resolve,reject)=>{
340
+ const timer=setTimeout(()=>{
341
+ pendingRequests.delete(requestId);
342
+ reject(new Error('No confirmation arrived. The write may have succeeded; check its status before retrying.'));
343
+ },30000);
344
+ pendingRequests.set(requestId,{resolve,reject,timer});
345
+ });
346
+ send({jsonrpc:'2.0',id:requestId,method:'tools/call',params:{name:tool,arguments:{...args,pending_operation_id:pending}}});
347
+ try {
348
+ const result=await response;
349
+ if (!result || result.isError) throw new Error('Adport could not confirm the change. Check its status before retrying.');
350
+ const value=result.structuredContent || result;
351
+ const outcome=tool==='recommendation_apply'?value.result:value;
352
+ if (outcome?.applied!==true || outcome?.status!=='applied') throw new Error('The change was not confirmed as applied. Check its status before retrying.');
353
+ state.approving=false;state.approvalError='';acceptResult(result);
354
+ } catch (error) {
355
+ state.approving=false;state.approvalError=error?.message || 'The change could not be confirmed. Check its status before retrying.';
356
+ render(state.result);
357
+ }
358
+ }
359
+ function renderInsights(data) {
360
+ const items = data.finding ? [data.finding] : arr(data.findings || data.recommendations || data.results || data.entries);
361
+ const body = items.length ? '<div class="list">'+items.slice(0,8).map((item,i)=>'<div class="row"><div class="identity"><span class="logo" style="background:var(--orange)">'+(i+1)+'</span><div class="identity-copy"><b>'+esc(item.title || item.summary || item.rule || 'Opportunity')+'</b><span>'+esc(item.description || item.status || item.severity || 'Review recommended')+'</span></div></div><span class="pill '+(/high|critical/i.test(item.severity || '')?'danger':'')+'">'+esc(item.severity || item.status || 'open')+'</span></div>').join('')+'</div>' : '<div class="empty">No active recommendations were returned.</div>';
362
+ app.innerHTML = chrome(body, items.length+' recommendation'+(items.length===1?'':'s'));
363
+ }
364
+ function render(result) {
365
+ let data = result?.structuredContent || result || {};
366
+ if (!result?.structuredContent && Array.isArray(result?.content)) {
367
+ for (const item of result.content) {
368
+ if (item.type !== 'text') continue;
369
+ try { const parsed = JSON.parse(item.text); if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { data = parsed; break; } } catch {}
370
+ }
371
+ }
372
+ const meta = data._adport || {};
373
+ syntheticResult = data.data_source === 'synthetic';
374
+ if (data.cancelled) {
375
+ app.innerHTML=chrome('<p class="notice">'+esc(data.message || 'The host interrupted this request. Check the tool response before retrying.')+'</p>','Request interrupted');
376
+ return;
377
+ }
378
+ if (result?.isError || data.error) {
379
+ app.innerHTML=chrome('<p class="notice">'+esc(data.message || 'The request could not complete. See the tool response for details.')+'</p>','Request failed');
380
+ return;
381
+ }
382
+ if (meta.view === 'accounts') return renderAccounts(data,meta);
383
+ if (meta.view === 'report') return renderReport(data,meta);
384
+ if (meta.view === 'operation') return renderOperation(data,meta);
385
+ return renderInsights(data,meta);
386
+ }
387
+ function acceptResult(result) {
388
+ if (!result || typeof result !== 'object') return;
389
+ clearTimeout(resultWait);
390
+ // ChatGPT can deliver the same result through both supported bridges.
391
+ // Do not reset an open disclosure when the second copy arrives.
392
+ if (state.result && JSON.stringify(state.result) === JSON.stringify(result)) return;
393
+ state.result = result;
394
+ render(result);
395
+ }
396
+ function receiveGlobals(globals) {
397
+ if (!globals) return;
398
+ const metadata = globals.toolResponseMetadata;
399
+ const envelope = metadata?.mcp_tool_result || metadata?.call_tool_result;
400
+ if (envelope && typeof envelope === 'object') return acceptResult(envelope);
401
+ if (globals.toolOutput && typeof globals.toolOutput === 'object') acceptResult({structuredContent:globals.toolOutput});
402
+ }
403
+ // Some hosts mount an error result's resource but never relay its payload.
404
+ // This is a delivery fallback, not a claim about tool execution or success.
405
+ const resultWait = setTimeout(() => {
406
+ if (!state.result) app.innerHTML=chrome('<p class="notice">The host has not provided a result to this view. Check the tool response in the conversation. This card will update if a result arrives.</p>','Result not received');
407
+ }, 15000);
408
+ const send = (message) => window.parent.postMessage(message,'*');
409
+ const resize = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(() => {
410
+ send({jsonrpc:'2.0',method:'ui/notifications/size-changed',params:{height:Math.ceil(document.body.getBoundingClientRect().height)}});
411
+ });
412
+ let id = 1;
413
+ window.addEventListener('message', (event) => {
414
+ if (event.source !== window.parent) return;
415
+ const message = event.data;
416
+ if (!message || message.jsonrpc !== '2.0') return;
417
+ if (message.id !== undefined && pendingRequests.has(message.id)) {
418
+ const request=pendingRequests.get(message.id);
419
+ pendingRequests.delete(message.id);
420
+ clearTimeout(request.timer);
421
+ if (message.error) request.reject(message.error);
422
+ else request.resolve(message.result);
423
+ return;
424
+ }
425
+ if (message.id === 1 && message.result) {
426
+ state.host = message.result.hostContext || {};
427
+ document.documentElement.dataset.theme = state.host.theme || '';
428
+ send({jsonrpc:'2.0',method:'ui/notifications/initialized'});
429
+ resize?.observe(document.body);
430
+ if (state.result) render(state.result);
431
+ }
432
+ if (message.method === 'ui/notifications/tool-result') acceptResult(message.params);
433
+ if (message.method === 'ui/notifications/tool-cancelled') acceptResult({structuredContent:{cancelled:true,message:message.params?.reason}});
434
+ if (message.method === 'ui/notifications/host-context-changed') {
435
+ const previousLocale = state.host.locale;
436
+ state.host = {...state.host,...message.params};
437
+ document.documentElement.dataset.theme = state.host.theme || '';
438
+ // Size/theme updates must not rebuild the DOM: opening Details changes
439
+ // the iframe height, which some hosts echo back as a context update.
440
+ if (state.result && previousLocale !== state.host.locale) {
441
+ const expanded = app.querySelector('details')?.open || false;
442
+ render(state.result);
443
+ const details = app.querySelector('details');
444
+ if (details) details.open = expanded;
445
+ }
446
+ }
447
+ });
448
+ // The compatibility bridge can hydrate after the iframe has mounted,
449
+ // including full error envelopes in toolResponseMetadata.
450
+ window.addEventListener('openai:set_globals', event => receiveGlobals(event.detail?.globals));
451
+ send({jsonrpc:'2.0',id:id++,method:'ui/initialize',params:{appInfo:{name:'Adport Insight',version:'1.0.0'},appCapabilities:{},protocolVersion:'2026-01-26'}});
452
+ receiveGlobals(window.openai);
453
+ })();
454
+ </script>
455
+ </body>
456
+ </html>`;
457
+
458
+ // src/index.ts
459
+ var PROVIDER_IDS = ["google", "meta", "tiktok", "apple", "microsoft", "reddit", "snapchat", "spotify", "pinterest", "linkedin", "x"];
460
+ var DEFAULT_MCP_ICONS = [{
461
+ src: "https://app.adport.dev/icon.svg?brand=orange-dot-v2",
462
+ mimeType: "image/svg+xml",
463
+ sizes: ["any"]
464
+ }];
465
+ async function assembleRuntime(options = {}) {
466
+ const store = new CredentialStore();
467
+ const modules = [];
468
+ const includeMock = options.includeMock ?? process.env.ADPORT_DEMO === "true";
469
+ if (!includeMock) {
470
+ for (const factory of [createGoogleModule, createMetaModule, createTikTokModule, createAppleModule, createMicrosoftModule, createRedditModule, createSnapchatModule, createSpotifyModule, createPinterestModule, createLinkedInModule, createXModule]) {
471
+ const module = await factory(store);
472
+ if (module) modules.push(module);
473
+ }
474
+ }
475
+ return createContext({ providerModules: modules, includeMock });
476
+ }
477
+ function createMcpServer({ runtime, name = "adport", version = package_default.version, icons = DEFAULT_MCP_ICONS, scopes, scopeDenials, notConnectedMessage, productionOnly = false, uiDomain = ADPORT_UI_DOMAIN }) {
478
+ if (productionOnly && (runtime.dataSource === "synthetic" || runtime.ctx.providers.list().some((provider) => !PROVIDER_IDS.includes(provider.id)) || runtime.registry.list().some((tool) => /^(demo|mock|synthetic)(_|$)/.test(tool.name) || /^(demo|mock|synthetic)$/.test(tool.namespace)))) {
479
+ throw new AdportError("POLICY_VIOLATION", "Demo tools and synthetic runtimes are not available on the production connector.");
480
+ }
481
+ const provenance = (value) => runtime.dataSource === "synthetic" ? { ...value && typeof value === "object" && !Array.isArray(value) ? value : { value }, data_source: "synthetic" } : value;
482
+ const server = new McpServer({ name, version, ...icons ? { icons } : {} });
483
+ registerAppResource(
484
+ server,
485
+ "Adport insight card",
486
+ ADPORT_UI_URI,
487
+ {
488
+ description: "Responsive Adport accounts, performance, recommendations, and guarded-change view.",
489
+ _meta: {
490
+ ui: { domain: uiDomain, prefersBorder: false, csp: { connectDomains: [], resourceDomains: [] } },
491
+ "openai/widgetDomain": ADPORT_UI_DOMAIN
492
+ }
493
+ },
494
+ async () => ({
495
+ contents: [{
496
+ uri: ADPORT_UI_URI,
497
+ mimeType: RESOURCE_MIME_TYPE,
498
+ text: ADPORT_UI_HTML,
499
+ _meta: {
500
+ ui: { domain: uiDomain, prefersBorder: false, csp: { connectDomains: [], resourceDomains: [] } },
501
+ "openai/widgetDomain": ADPORT_UI_DOMAIN
502
+ }
503
+ }]
504
+ })
505
+ );
506
+ for (const tool of runtime.registry.list()) {
507
+ const requiredScope = tool.annotations.readOnly ? "tools:read" : "tools:write";
508
+ const scopeDenial = scopes && !scopes.includes(requiredScope) ? scopeDenials?.[requiredScope] : void 0;
509
+ if (scopes && !scopes.includes(requiredScope) && !scopeDenial) continue;
510
+ const view = viewForTool(tool.name, tool.annotations.readOnly ?? false);
511
+ const labels = view ? toolInvocationLabels(view) : void 0;
512
+ const wrapOutput = !!tool.output && !(tool.output instanceof z.ZodObject);
513
+ const objectOutput = tool.output ? tool.output instanceof z.ZodObject ? tool.output : z.object({ value: tool.output }) : void 0;
514
+ const config = {
515
+ title: toolTitle(tool.name),
516
+ description: scopeDenial ? `${tool.description}
517
+
518
+ Unavailable on the current plan: ${scopeDenial.message}` : tool.description,
519
+ inputSchema: tool.input.shape,
520
+ ...objectOutput ? { outputSchema: objectOutput.extend({
521
+ ...view ? { _adport: z.object({ tool: z.literal(tool.name), view: z.literal(view), providerNames: z.record(z.string(), z.string()), approval: z.object({ arguments: z.record(z.string(), z.unknown()) }).optional() }) } : {},
522
+ ...runtime.dataSource === "synthetic" ? { data_source: z.literal("synthetic") } : {}
523
+ }) } : {},
524
+ annotations: {
525
+ readOnlyHint: tool.annotations.readOnly ?? false,
526
+ destructiveHint: tool.annotations.destructive ?? false,
527
+ openWorldHint: tool.annotations.openWorld ?? false
528
+ }
529
+ };
530
+ const callback = async (args) => {
531
+ if (scopeDenial) {
532
+ const payload = provenance({
533
+ error: scopeDenial.code,
534
+ code: scopeDenial.code,
535
+ message: scopeDenial.message,
536
+ ...scopeDenial.data
537
+ });
538
+ return {
539
+ content: [{
540
+ type: "text",
541
+ text: JSON.stringify(payload, null, 2)
542
+ }],
543
+ // SDK clients validate structuredContent even on isError responses.
544
+ // Errors use JSON text (also consumed by the widget), never a fake
545
+ // success object to satisfy the advertised output schema.
546
+ isError: true
547
+ };
548
+ }
549
+ try {
550
+ const rawResult = await runtime.registry.call(tool.name, args, runtime.ctx);
551
+ const result = provenance(rawResult);
552
+ const structured = provenance(wrapOutput ? { value: rawResult } : rawResult);
553
+ const rawObject = rawResult && typeof rawResult === "object" && !Array.isArray(rawResult) ? rawResult : {};
554
+ const nestedResult = rawObject.result && typeof rawObject.result === "object" && !Array.isArray(rawObject.result) ? rawObject.result : {};
555
+ const pending = rawObject.pending_operation_id ?? nestedResult.pending_operation_id;
556
+ const approval = view === "operation" && typeof pending === "string" && !args.pending_operation_id ? { arguments: { ...args } } : void 0;
557
+ return {
558
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
559
+ ...view ? { structuredContent: structuredResult(tool.name, view, structured, approval) } : tool.output ? { structuredContent: structured } : {}
560
+ };
561
+ } catch (err) {
562
+ const payload = provenance(
563
+ err instanceof AdportError ? { ...err.toJSON(), ...err.code === "NOT_CONNECTED" && notConnectedMessage ? { message: notConnectedMessage } : {} } : {
564
+ error: "INTERNAL",
565
+ // Unexpected exceptions can contain credentials or private paths.
566
+ // Do not imply that a failed response means a write was not applied.
567
+ message: "Adport could not complete this request. If this was a write, check its status before retrying. Contact support if the problem persists."
568
+ }
569
+ );
570
+ return {
571
+ content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
572
+ isError: true
573
+ };
574
+ }
575
+ };
576
+ if (view) {
577
+ registerAppTool(server, tool.name, {
578
+ ...config,
579
+ _meta: {
580
+ ui: { resourceUri: ADPORT_UI_URI, visibility: ["model", "app"] },
581
+ "openai/widgetAccessible": true,
582
+ "openai/outputTemplate": ADPORT_UI_URI,
583
+ "openai/toolInvocation/invoking": labels.invoking,
584
+ "openai/toolInvocation/invoked": labels.invoked
585
+ }
586
+ }, callback);
587
+ } else {
588
+ server.registerTool(tool.name, config, callback);
589
+ }
590
+ }
591
+ return server;
592
+ }
593
+ async function runStdioServer(runtime, version) {
594
+ const server = createMcpServer({ runtime, version });
595
+ await server.connect(new StdioServerTransport());
596
+ console.error(`adport MCP server on stdio (${runtime.registry.list().length} tools, policy: ${runtime.policySource})`);
597
+ if (runtime.ctx.providers.list().length === 0) {
598
+ console.error("No ad providers connected. Run `adport connect <provider>` or restart with `--demo` for synthetic mock data.");
599
+ }
600
+ }
601
+
602
+ export {
603
+ PROVIDER_IDS,
604
+ assembleRuntime,
605
+ createMcpServer,
606
+ runStdioServer
607
+ };
608
+ //# sourceMappingURL=chunk-YCSBIOYH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../package.json","../src/ui.ts"],"sourcesContent":["import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { z } from 'zod';\nimport { registerAppResource, registerAppTool, RESOURCE_MIME_TYPE } from '@modelcontextprotocol/ext-apps/server';\nimport { AdportError, CredentialStore, createContext, type AdportRuntime, type ProviderModule } from '@adport/core';\nimport { createGoogleModule } from '@adport/provider-google';\nimport { createMetaModule } from '@adport/provider-meta';\nimport { createTikTokModule } from '@adport/provider-tiktok';\nimport { createAppleModule } from '@adport/provider-apple';\nimport { createMicrosoftModule } from '@adport/provider-microsoft';\nimport { createRedditModule } from '@adport/provider-reddit';\nimport { createSnapchatModule } from '@adport/provider-snapchat';\nimport { createSpotifyModule } from '@adport/provider-spotify';\nimport { createPinterestModule } from '@adport/provider-pinterest';\nimport { createLinkedInModule } from '@adport/provider-linkedin';\nimport { createXModule } from '@adport/provider-x';\nimport packageJson from '../package.json';\nimport {\n ADPORT_UI_HTML,\n ADPORT_UI_DOMAIN,\n ADPORT_UI_URI,\n structuredResult,\n toolInvocationLabels,\n toolTitle,\n viewForTool,\n} from './ui.js';\n\nexport const PROVIDER_IDS = ['google', 'meta', 'tiktok', 'apple', 'microsoft', 'reddit', 'snapchat', 'spotify', 'pinterest', 'linkedin', 'x'] as const;\n\nconst DEFAULT_MCP_ICONS = [{\n src: 'https://app.adport.dev/icon.svg?brand=orange-dot-v2',\n mimeType: 'image/svg+xml',\n sizes: ['any'],\n}];\n\n/**\n * Standard runtime assembly: real providers whose credentials exist. Mock data\n * is opt-in so a live runtime never silently substitutes synthetic accounts.\n */\nexport interface AssembleRuntimeOptions {\n includeMock?: boolean;\n}\n\nexport async function assembleRuntime(options: AssembleRuntimeOptions = {}): Promise<AdportRuntime> {\n const store = new CredentialStore();\n const modules: ProviderModule[] = [];\n const includeMock = options.includeMock ?? process.env.ADPORT_DEMO === 'true';\n if (!includeMock) {\n for (const factory of [createGoogleModule, createMetaModule, createTikTokModule, createAppleModule, createMicrosoftModule, createRedditModule, createSnapchatModule, createSpotifyModule, createPinterestModule, createLinkedInModule, createXModule]) {\n const module = await factory(store);\n if (module) modules.push(module);\n }\n }\n return createContext({ providerModules: modules, includeMock });\n}\n\nexport interface CreateServerOptions {\n runtime: AdportRuntime;\n name?: string;\n version?: string;\n /** Brand icons advertised to MCP clients during initialization. */\n icons?: Array<{ src: string; mimeType?: string; sizes?: string[] }>;\n /** When set by a remote transport, only register tools authorized by this key. */\n scopes?: readonly string[];\n /**\n * Register tools blocked by a dynamic entitlement and return this structured\n * error when called. Missing credential scopes without a denial stay hidden.\n */\n scopeDenials?: Readonly<Record<string, ToolScopeDenial | undefined>>;\n /** Hosted transports can replace local CLI setup guidance, without changing the error code. */\n notConnectedMessage?: string;\n /** Hosted production must never serve synthetic results or demo tool definitions. */\n productionOnly?: boolean;\n /** Host-specific MCP Apps sandbox domain; OpenAI's widget domain stays independent. */\n uiDomain?: string;\n}\n\nexport interface ToolScopeDenial {\n code: string;\n message: string;\n data?: Record<string, unknown>;\n}\n\n/**\n * Thin adapter: every tool in the shared registry becomes an MCP tool.\n * No tool logic lives here — see the \"one tool-definition layer\" principle.\n */\nexport function createMcpServer({ runtime, name = 'adport', version = packageJson.version, icons = DEFAULT_MCP_ICONS, scopes, scopeDenials, notConnectedMessage, productionOnly = false, uiDomain = ADPORT_UI_DOMAIN }: CreateServerOptions): McpServer {\n if (productionOnly && (runtime.dataSource === 'synthetic'\n || runtime.ctx.providers.list().some(provider => !PROVIDER_IDS.includes(provider.id as typeof PROVIDER_IDS[number]))\n || runtime.registry.list().some(tool => /^(demo|mock|synthetic)(_|$)/.test(tool.name) || /^(demo|mock|synthetic)$/.test(tool.namespace)))) {\n throw new AdportError('POLICY_VIOLATION', 'Demo tools and synthetic runtimes are not available on the production connector.');\n }\n const provenance = (value: unknown): unknown => runtime.dataSource === 'synthetic'\n ? { ...(value && typeof value === 'object' && !Array.isArray(value) ? value : { value }), data_source: 'synthetic' }\n : value;\n const server = new McpServer({ name, version, ...(icons ? { icons } : {}) });\n registerAppResource(\n server,\n 'Adport insight card',\n ADPORT_UI_URI,\n {\n description: 'Responsive Adport accounts, performance, recommendations, and guarded-change view.',\n _meta: {\n ui: { domain: uiDomain, prefersBorder: false, csp: { connectDomains: [], resourceDomains: [] } },\n 'openai/widgetDomain': ADPORT_UI_DOMAIN,\n },\n },\n async () => ({\n contents: [{\n uri: ADPORT_UI_URI,\n mimeType: RESOURCE_MIME_TYPE,\n text: ADPORT_UI_HTML,\n _meta: {\n ui: { domain: uiDomain, prefersBorder: false, csp: { connectDomains: [], resourceDomains: [] } },\n 'openai/widgetDomain': ADPORT_UI_DOMAIN,\n },\n }],\n }),\n );\n for (const tool of runtime.registry.list()) {\n const requiredScope = tool.annotations.readOnly ? 'tools:read' : 'tools:write';\n const scopeDenial = scopes && !scopes.includes(requiredScope) ? scopeDenials?.[requiredScope] : undefined;\n if (scopes && !scopes.includes(requiredScope) && !scopeDenial) continue;\n const view = viewForTool(tool.name, tool.annotations.readOnly ?? false);\n const labels = view ? toolInvocationLabels(view) : undefined;\n // MCP structuredContent must be an object. Preserve legacy raw arrays in\n // text/CLI results, exposing their declared schema under a value envelope.\n const wrapOutput = !!tool.output && !(tool.output instanceof z.ZodObject);\n const objectOutput = tool.output\n ? tool.output instanceof z.ZodObject ? tool.output : z.object({ value: tool.output })\n : undefined;\n const config = {\n title: toolTitle(tool.name),\n description: scopeDenial\n ? `${tool.description}\\n\\nUnavailable on the current plan: ${scopeDenial.message}`\n : tool.description,\n inputSchema: tool.input.shape,\n ...(objectOutput ? { outputSchema: objectOutput.extend({\n ...(view ? { _adport: z.object({ tool: z.literal(tool.name), view: z.literal(view), providerNames: z.record(z.string(), z.string()), approval: z.object({ arguments: z.record(z.string(), z.unknown()) }).optional() }) } : {}),\n ...(runtime.dataSource === 'synthetic' ? { data_source: z.literal('synthetic') } : {}),\n }) } : {}),\n annotations: {\n readOnlyHint: tool.annotations.readOnly ?? false,\n destructiveHint: tool.annotations.destructive ?? false,\n openWorldHint: tool.annotations.openWorld ?? false,\n },\n };\n const callback = async (args: Record<string, unknown>) => {\n if (scopeDenial) {\n const payload = provenance({\n error: scopeDenial.code,\n code: scopeDenial.code,\n message: scopeDenial.message,\n ...scopeDenial.data,\n });\n return {\n content: [{\n type: 'text' as const,\n text: JSON.stringify(payload, null, 2),\n }],\n // SDK clients validate structuredContent even on isError responses.\n // Errors use JSON text (also consumed by the widget), never a fake\n // success object to satisfy the advertised output schema.\n isError: true,\n };\n }\n try {\n const rawResult = await runtime.registry.call(tool.name, args, runtime.ctx);\n const result = provenance(rawResult);\n const structured = provenance(wrapOutput ? { value: rawResult } : rawResult);\n const rawObject = rawResult && typeof rawResult === 'object' && !Array.isArray(rawResult)\n ? rawResult as Record<string, unknown> : {};\n const nestedResult = rawObject.result && typeof rawObject.result === 'object' && !Array.isArray(rawObject.result)\n ? rawObject.result as Record<string, unknown> : {};\n const pending = rawObject.pending_operation_id ?? nestedResult.pending_operation_id;\n const approval = view === 'operation' && typeof pending === 'string' && !args.pending_operation_id\n ? { arguments: { ...args } }\n : undefined;\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],\n ...(view ? { structuredContent: structuredResult(tool.name, view, structured, approval) }\n : tool.output ? { structuredContent: structured as Record<string, unknown> } : {}),\n };\n } catch (err) {\n const payload = provenance(\n err instanceof AdportError\n ? { ...err.toJSON(), ...(err.code === 'NOT_CONNECTED' && notConnectedMessage ? { message: notConnectedMessage } : {}) }\n : {\n error: 'INTERNAL',\n // Unexpected exceptions can contain credentials or private paths.\n // Do not imply that a failed response means a write was not applied.\n message: 'Adport could not complete this request. If this was a write, check its status before retrying. Contact support if the problem persists.',\n });\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(payload, null, 2) }],\n isError: true,\n };\n }\n };\n if (view) {\n registerAppTool(server, tool.name, {\n ...config,\n _meta: {\n ui: { resourceUri: ADPORT_UI_URI, visibility: ['model', 'app'] },\n 'openai/widgetAccessible': true,\n 'openai/outputTemplate': ADPORT_UI_URI,\n 'openai/toolInvocation/invoking': labels!.invoking,\n 'openai/toolInvocation/invoked': labels!.invoked,\n },\n }, callback);\n } else {\n server.registerTool(tool.name, config, callback);\n }\n }\n return server;\n}\n\nexport async function runStdioServer(runtime: AdportRuntime, version?: string): Promise<void> {\n const server = createMcpServer({ runtime, version });\n await server.connect(new StdioServerTransport());\n // stdout is the protocol channel; stderr is for humans.\n console.error(`adport MCP server on stdio (${runtime.registry.list().length} tools, policy: ${runtime.policySource})`);\n if (runtime.ctx.providers.list().length === 0) {\n console.error('No ad providers connected. Run `adport connect <provider>` or restart with `--demo` for synthetic mock data.');\n }\n}\n","{\n \"name\": \"@adport/mcp\",\n \"version\": \"0.6.1\",\n \"description\": \"adport MCP server — the open control plane for paid media\",\n \"license\": \"Apache-2.0\",\n \"type\": \"module\",\n \"main\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n }\n },\n \"bin\": {\n \"adport-mcp\": \"./dist/bin.js\"\n },\n \"files\": [\"dist\"],\n \"scripts\": {\n \"build\": \"tsup src/index.ts src/bin.ts --format esm --dts --sourcemap --clean\",\n \"render:submission-previews\": \"node scripts/render-submission-previews.mjs\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc --noEmit\",\n \"clean\": \"rm -rf dist\"\n },\n \"dependencies\": {\n \"@adport/core\": \"workspace:*\",\n \"@adport/provider-apple\": \"workspace:*\",\n \"@adport/provider-google\": \"workspace:*\",\n \"@adport/provider-meta\": \"workspace:*\",\n \"@adport/provider-microsoft\": \"workspace:*\",\n \"@adport/provider-reddit\": \"workspace:*\",\n \"@adport/provider-snapchat\": \"workspace:*\",\n \"@adport/provider-spotify\": \"workspace:*\",\n \"@adport/provider-pinterest\": \"workspace:*\",\n \"@adport/provider-linkedin\": \"workspace:*\",\n \"@adport/provider-x\": \"workspace:*\",\n \"@adport/provider-tiktok\": \"workspace:*\",\n \"@modelcontextprotocol/ext-apps\": \"^1.7.5\",\n \"@modelcontextprotocol/sdk\": \"^1.30.0\",\n \"zod\": \"^4.4.3\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^26.1.2\",\n \"tsup\": \"^8.3.0\",\n \"typescript\": \"^5.8.0\",\n \"vitest\": \"^4.1.10\"\n }\n}\n","export const ADPORT_UI_URI = 'ui://adport/insight-card-v2.html';\nexport const ADPORT_UI_DOMAIN = 'https://app.adport.dev';\n\nexport type AdportView = 'accounts' | 'report' | 'operation' | 'insights';\n\nconst providerNames: Record<string, string> = {\n google: 'Google Ads',\n meta: 'Meta Ads',\n tiktok: 'TikTok Ads',\n apple: 'Apple Ads',\n microsoft: 'Microsoft Advertising',\n reddit: 'Reddit Ads',\n snapchat: 'Snapchat Ads',\n spotify: 'Spotify Ads',\n pinterest: 'Pinterest Ads',\n linkedin: 'LinkedIn Ads',\n x: 'X Ads',\n mock: 'Demo',\n demo: 'Synthetic demo',\n};\n\nexport function viewForTool(name: string, readOnly: boolean): AdportView | undefined {\n if (name === 'accounts_list') return 'accounts';\n if (name === 'report') return 'report';\n if (name === 'audit_run' || name === 'recommendation_dismiss') return 'insights';\n if (!readOnly) return 'operation';\n if (name.startsWith('recommendation') || name.startsWith('audit_')) return 'insights';\n return undefined;\n}\n\nexport function toolTitle(name: string): string {\n if (name === 'accounts_list') return 'Show connected ad accounts';\n if (name === 'report') return 'Show advertising performance';\n return name\n .split('_')\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(' ');\n}\n\nexport function toolInvocationLabels(view: AdportView): { invoking: string; invoked: string } {\n switch (view) {\n case 'accounts': return { invoking: 'Loading ad accounts…', invoked: 'Ad accounts ready' };\n case 'report': return { invoking: 'Analyzing performance…', invoked: 'Performance ready' };\n // Descriptor labels cover both preview and apply; the card shows the actual result.\n case 'operation': return { invoking: 'Processing change…', invoked: 'Change result ready' };\n case 'insights': return { invoking: 'Reviewing opportunities…', invoked: 'Opportunities ready' };\n }\n}\n\nexport function structuredResult(tool: string, view: AdportView, result: unknown, approval?: { arguments: Record<string, unknown> }): Record<string, unknown> {\n const payload = result && typeof result === 'object' && !Array.isArray(result)\n ? result as Record<string, unknown>\n : { value: result };\n return {\n ...payload,\n _adport: {\n tool,\n view,\n providerNames,\n ...(approval ? { approval } : {}),\n },\n };\n}\n\n/**\n * Self-contained MCP App. It uses the open MCP Apps postMessage protocol and\n * has no network dependencies, which keeps its review CSP intentionally empty.\n */\nexport const ADPORT_UI_HTML = String.raw`<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />\n <meta name=\"color-scheme\" content=\"light dark\" />\n <title>Adport insight</title>\n <style>\n :root {\n --ink: var(--color-text-primary, #171717);\n --muted: var(--color-text-secondary, #6f6f73);\n --faint: var(--color-text-tertiary, #949499);\n --paper: var(--color-background-primary, #ffffff);\n --soft: var(--color-background-secondary, #f6f6f4);\n --line: var(--color-border-secondary, rgba(23,23,23,.11));\n --orange: #ff5a1f;\n --green: #16845b;\n --red: #c8392f;\n --amber: #a86500;\n --radius: var(--border-radius-lg, 18px);\n --sans: var(--font-sans, ui-sans-serif, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif);\n --mono: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);\n }\n * { box-sizing: border-box }\n html, body { margin: 0; min-width: 0; background: transparent; color: var(--ink); font-family: var(--sans) }\n body { padding: 2px; }\n button { font: inherit }\n .shell { overflow: hidden; border: 1px solid var(--line); border-radius: var(--radius); background: var(--paper); box-shadow: 0 10px 32px rgba(20,20,20,.07) }\n .top { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:14px 16px 10px }\n .brand { display:flex; align-items:center; gap:9px; min-width:0 }\n .dot { width:10px; height:10px; border-radius:99px; background:var(--orange); box-shadow:0 0 0 5px color-mix(in srgb,var(--orange) 12%,transparent) }\n .brand b { font-size:12px; letter-spacing:-.02em }\n .context { color:var(--muted); font-size:11px; text-align:right }\n .content { padding:4px 16px 16px }\n .kpis { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:8px; margin-bottom:15px }\n .kpi { min-width:0; padding:12px; border-radius:13px; background:var(--soft); border:1px solid color-mix(in srgb,var(--line) 70%,transparent) }\n button.kpi { cursor:pointer; color:var(--ink); text-align:left }\n button.kpi[aria-pressed=\"true\"] { border-color:color-mix(in srgb,var(--orange) 65%,var(--line)) }\n .kpi small { display:block; color:var(--faint); font:600 9px/1.2 var(--mono); letter-spacing:.11em; text-transform:uppercase }\n .kpi strong { display:block; overflow:hidden; margin-top:8px; font-size:clamp(17px,3vw,24px); line-height:1; letter-spacing:-.04em; text-overflow:ellipsis }\n .panel { min-width:0; padding:13px; border:1px solid var(--line); border-radius:14px }\n .panel-head { display:flex; align-items:center; justify-content:space-between; gap:12px; margin-bottom:12px }\n .panel-head b { font-size:12px }\n .panel-head span { color:var(--faint); font:500 9px/1 var(--mono); text-transform:uppercase; letter-spacing:.1em }\n .bars { display:grid; gap:9px }\n .bar-row { display:grid; grid-template-columns:minmax(100px,1fr) minmax(60px,2fr) auto; align-items:center; gap:9px; font-size:11px }\n .bar-name { display:flex; align-items:center; gap:7px; min-width:0 }\n .bar-name > span:last-child { overflow:hidden; white-space:nowrap; text-overflow:ellipsis }\n .bar-name .logo { width:22px; height:22px; padding:4px; border-radius:6px }\n .track { height:7px; overflow:hidden; border-radius:99px; background:var(--soft) }\n .fill { height:100%; border-radius:99px; background:linear-gradient(90deg,var(--orange),#ff985e) }\n .tabs { display:flex; gap:6px; overflow:auto; padding-bottom:12px }\n .tabs button { flex:0 0 auto; cursor:pointer; padding:8px 12px; border:1px solid var(--line); border-radius:99px; background:var(--paper); color:var(--muted); font-size:12px }\n .tabs button[aria-pressed=\"true\"] { color:var(--ink); border-color:var(--orange); background:color-mix(in srgb,var(--orange) 8%,var(--paper)) }\n button:focus-visible { outline:2px solid var(--orange); outline-offset:2px }\n .notice { padding:10px 12px; margin:0 0 12px; border-radius:10px; background:var(--soft); color:var(--muted); font-size:12px; line-height:1.45 }\n .bar-value { color:var(--muted); font:600 10px/1 var(--mono); white-space:nowrap }\n .list { display:grid; gap:7px }\n .row { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:10px 11px; border:1px solid var(--line); border-radius:12px }\n .identity { display:flex; align-items:center; gap:10px; min-width:0 }\n .logo { display:grid; place-items:center; flex:0 0 auto; width:29px; height:29px; padding:6px; border:1px solid var(--line); border-radius:9px; color:var(--ink); background:var(--paper); font-weight:800; font-size:10px }\n .logo svg { display:block; width:100%; height:100% }\n .logo.reddit { background:#ff4500 }.logo.linkedin { background:#0a66c2 }.logo.spotify { background:#1db954 }.logo.pinterest { background:#e60023 }.logo.x { background:#111 }.logo.snapchat { background:#fffc00;color:#111 }\n .identity-copy { min-width:0 }\n .identity-copy b, .identity-copy span { display:block; overflow:hidden; white-space:nowrap; text-overflow:ellipsis }\n .identity-copy b { font-size:12px }.identity-copy span { margin-top:3px; color:var(--muted); font-size:10px }\n .pill { flex:0 0 auto; padding:5px 8px; border-radius:99px; color:var(--green); background:color-mix(in srgb,var(--green) 10%,transparent); font:700 9px/1 var(--mono); letter-spacing:.08em; text-transform:uppercase }\n .pill.warn { color:var(--amber); background:color-mix(in srgb,var(--amber) 11%,transparent) }\n .pill.danger { color:var(--red); background:color-mix(in srgb,var(--red) 10%,transparent) }\n .pill.neutral { color:var(--muted); background:var(--soft) }\n .operation-name { margin:2px 0 16px; font-size:14px; line-height:1.4; font-weight:600; overflow-wrap:anywhere }\n .comparison { width:100%; border-collapse:collapse; table-layout:fixed; margin-bottom:12px }\n .comparison th { padding:0 8px 8px; color:var(--muted); font-size:10px; font-weight:500; text-align:left }\n .comparison td { border-top:1px solid var(--line); padding:12px 8px; font-size:14px; overflow-wrap:anywhere }\n .comparison td:first-child { color:var(--muted); font-size:11px }\n .comparison td:last-child { font-weight:600 }\n .comparison .changed { color:var(--orange) }\n .adjustment { margin:8px 0; color:var(--amber); font-size:11px; line-height:1.4 }\n .approval { display:flex; align-items:center; gap:10px; flex-wrap:wrap; margin:12px 0 }\n .approve { cursor:pointer; padding:9px 16px; border:0; border-radius:99px; background:var(--ink); color:var(--paper); font-size:12px; font-weight:700 }\n .approve:disabled { cursor:default; opacity:.55 }\n details { border-top:1px solid var(--line); padding-top:10px; color:var(--muted); font-size:11px; line-height:1.5 }\n summary { cursor:pointer; width:fit-content; padding:3px 0 }\n summary:focus-visible { outline:2px solid var(--orange); outline-offset:3px }\n details p { margin:8px 0; overflow-wrap:anywhere }\n .empty { padding:26px 12px; text-align:center; color:var(--muted); font-size:12px }\n @media (max-width:620px) { .kpis { grid-template-columns:repeat(2,minmax(0,1fr)) }.top,.content { padding-left:12px; padding-right:12px } }\n @media (max-width:420px) { .bar-row { grid-template-columns:minmax(0,1fr) auto; gap:5px }.bar-name { grid-column:1/-1 }.bar-name > span:last-child { white-space:normal }.bars { gap:12px } }\n @media (prefers-reduced-motion:reduce) { * { animation:none!important; transition:none!important } }\n :root[data-theme=\"dark\"] { --ink:#f5f5f3;--muted:#aaa9ad;--faint:#a09fa5;--paper:#171717;--soft:#222220;--line:rgba(255,255,255,.11) }\n @media (prefers-color-scheme:dark) { :root:not([data-theme=\"light\"]) { --ink:#f5f5f3;--muted:#aaa9ad;--faint:#a09fa5;--paper:#171717;--soft:#222220;--line:rgba(255,255,255,.11) } }\n </style>\n</head>\n<body>\n <main id=\"app\" class=\"shell\" aria-live=\"polite\">\n <header class=\"top\"><div class=\"brand\"><span class=\"dot\"></span><b>adport.dev</b></div></header>\n <section class=\"content\"><div class=\"empty\">Loading…</div></section>\n </main>\n <script>\n (() => {\n const app = document.getElementById('app');\n const state = { host: {}, result: null, reportGroup: null, reportMetric: 'spend', approving: false, approvalError: '' };\n const esc = (value) => String(value ?? '').replace(/[&<>\"']/g, (c) => ({'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;',\"'\":'&#39;'}[c]));\n const arr = (value) => Array.isArray(value) ? value : [];\n const num = (value) => Number.isFinite(Number(value)) ? Number(value) : 0;\n const money = (value, currency, maximumFractionDigits=2) => currency\n ? new Intl.NumberFormat(state.host.locale || 'en', { style:'currency', currency, maximumFractionDigits }).format(num(value))\n : new Intl.NumberFormat(state.host.locale || 'en', { maximumFractionDigits }).format(num(value));\n const compact = (value) => new Intl.NumberFormat(state.host.locale || 'en', { notation:'compact', maximumFractionDigits:1 }).format(num(value));\n const available = (value) => typeof value === 'number' && Number.isFinite(value);\n const total = (rows, key) => rows.length && rows.every(r => available(r.metrics?.[key])) ? rows.reduce((sum,r) => sum+r.metrics[key],0) : null;\n const rowReturn = (row) => {\n const m=row.metrics || {};\n if (available(m.conversion_value)) return m.conversion_value;\n // A report can request ROAS without conversion_value. Weight reported\n // ratios by spend; never average campaign ratios or infer missing revenue.\n const value=available(m.spend) && m.spend>0 && available(m.roas) ? m.spend*m.roas : null;\n return available(value) ? value : null;\n };\n const currencyOf = (row) => typeof row.currency === 'string' && /^[A-Z]{3}$/.test(row.currency) ? row.currency : null;\n const statusOf = (status) => !status || /unknown|unspecified/i.test(status) ? {label:'Status unavailable',tone:'neutral'} : /disabled|removed|inactive|closed|suspended/i.test(status) ? {label:status,tone:'danger'} : /paused|disable$/i.test(status) ? {label:status,tone:'warn'} : /^(enabled|active|approved)$/i.test(status) ? {label:status,tone:''} : {label:status,tone:'neutral'};\n const notices = (data) => [...arr(data.errors).map(e => (e.provider || 'Provider')+': '+(e.message || 'Read failed')), ...arr(data.warnings).map(e => e.message || 'Some metadata is unavailable'), ...(data.truncated ? ['Partial result: row limit reached. Totals and charts cover returned rows only.'] : [])].map(text => '<p class=\"notice\">'+esc(text)+'</p>').join('');\n const providerName = (id, names) => names?.[id] || String(id || 'Provider');\n const initials = (id) => ({snapchat:'S',spotify:'S',pinterest:'P',linkedin:'in',x:'X'}[id] || String(id || '?').slice(0,2).toUpperCase());\n const providerSvg = {\n // Unmodified official Ghost paths, matching cloud/components/snapchat-logo.tsx.\n snapchat:\"<svg viewBox=\\\"0 0 1024 1024\\\" aria-hidden=\\\"true\\\"> <path fill=\\\"#fff\\\" d=\\\"M992.5,756.3c-4.2-13.9-24.3-23.7-24.3-23.7l0,0c-1.9-1-3.6-1.9-5-2.6c-33.5-16.2-63.2-35.7-88.2-57.8 c-20.1-17.8-37.3-37.4-51.1-58.2c-16.9-25.4-24.8-46.6-28.2-58.1c-1.9-7.5-1.6-10.5,0-14.4c1.3-3.3,5.2-6.4,7-7.9 c11.3-8,29.5-19.8,40.7-27c9.7-6.3,18-11.7,22.9-15.1c15.7-11,26.5-22.2,32.8-34.3c8.2-15.6,9.2-32.8,2.8-49.7 c-8.6-22.8-29.9-36.4-57-36.4c-6,0-12.2,0.7-18.4,2c-15.5,3.4-30.2,8.9-42.5,13.7c-0.9,0.4-1.9-0.3-1.8-1.3 c1.3-30.5,2.8-71.5-0.6-110.4c-3-35.2-10.3-64.9-22.1-90.8c-11.9-26-27.4-45.2-39.5-59.1C708.5,112,688.2,92.5,657.6,75 C614.6,50.4,565.6,37.9,512,37.9c-53.5,0-102.4,12.5-145.5,37.1c-32.4,18.5-53.1,39.4-62.5,50.2c-12.1,13.9-27.6,33.1-39.5,59.1 c-11.9,25.9-19.1,55.5-22.1,90.8c-3.4,39.1-2,76.8-0.6,110.4c0,1-0.9,1.7-1.9,1.3c-12.3-4.8-27-10.3-42.5-13.7 c-6.1-1.3-12.3-2-18.4-2c-27,0-48.3,13.6-57,36.4c-6.4,16.9-5.4,34.1,2.8,49.7c6.4,12.1,17.1,23.3,32.8,34.3 c4.8,3.4,13.2,8.8,22.9,15.1c10.9,7.1,28.6,18.6,40,26.5c1.4,1,6.2,4.6,7.7,8.4c1.6,4,1.9,7-0.2,15c-3.5,11.6-11.4,32.6-28,57.5 c-13.8,20.9-31,40.4-51.1,58.2c-25,22.1-54.7,41.6-88.2,57.8c-1.6,0.8-3.5,1.7-5.5,2.9l0,0c0,0-20,10.2-23.8,23.4 c-5.6,19.5,9.3,37.8,24.4,47.6c24.8,16,55,24.6,72.5,29.3c4.9,1.3,9.3,2.5,13.3,3.7c2.5,0.8,8.8,3.2,11.5,6.7 c3.4,4.4,3.8,9.8,5,15.9v0c1.9,10.3,6.2,23,18.9,31.8c14,9.6,31.7,10.3,54.2,11.2c23.5,0.9,52.7,2,86.2,13.1 c15.5,5.1,29.6,13.8,45.8,23.8c34,20.9,76.3,46.9,148.5,46.9c72.3,0,114.9-26.1,149.1-47.1c16.2-9.9,30.1-18.5,45.3-23.5 c33.5-11.1,62.7-12.2,86.2-13.1c22.5-0.9,40.2-1.5,54.2-11.2c13.6-9.4,17.5-23.4,19.3-33.9c1-5.2,1.6-9.9,4.6-13.7 c2.6-3.3,8.4-5.6,11.1-6.5c4.1-1.3,8.7-2.5,13.8-3.9c17.5-4.7,39.5-10.2,66.2-25.3C993.7,789.8,995.9,767.4,992.5,756.3z\\\" /> <path fill=\\\"#000\\\" d=\\\"M1020.3,745.5c-7.1-19.4-20.7-29.7-36.1-38.3c-2.9-1.7-5.6-3.1-7.8-4.1c-4.6-2.4-9.3-4.7-14-7.1 c-48.1-25.5-85.7-57.7-111.7-95.8c-8.8-12.9-14.9-24.5-19.2-34c-2.2-6.4-2.1-10-0.5-13.3c1.2-2.5,4.4-5.1,6.2-6.4 c8.3-5.5,16.8-11,22.6-14.7c10.3-6.7,18.5-12,23.7-15.6c19.8-13.8,33.6-28.5,42.2-44.9c12.2-23.1,13.7-49.5,4.3-74.3 c-13-34.4-45.6-55.8-85-55.8c-8.2,0-16.5,0.9-24.7,2.7c-2.2,0.5-4.3,1-6.4,1.5c0.4-23.4-0.2-48.4-2.3-72.8 c-7.4-86-37.5-131.1-68.9-167c-13.1-15-35.9-36.9-70.1-56.5C624.9,21.7,570.9,7.9,512,7.9c-58.7,0-112.7,13.8-160.4,41.1 c-34.4,19.6-57.2,41.6-70.2,56.5c-31.4,35.9-61.5,81-68.9,167c-2.1,24.4-2.6,49.4-2.3,72.8c-2.1-0.5-4.3-1-6.4-1.5 c-8.2-1.8-16.6-2.7-24.7-2.7c-39.4,0-72,21.4-85,55.8c-9.4,24.8-7.9,51.2,4.3,74.3c8.6,16.4,22.5,31.1,42.2,44.9 c5.3,3.7,13.4,9,23.7,15.6c5.6,3.6,13.7,8.9,21.7,14.2c1.2,0.8,5.5,4,7,7c1.7,3.4,1.7,7.1-0.8,13.9c-4.2,9.3-10.3,20.7-18.9,33.3 c-25.5,37.3-62,68.9-108.5,94.1c-24.7,13.1-50.3,21.8-61.1,51.2c-8.2,22.2-2.8,47.5,17.9,68.8l0,0c6.8,7.3,15.4,13.8,26.2,19.8 c25.4,14,47,20.9,64,25.6c3,0.9,9.9,3.1,12.9,5.8c7.6,6.6,6.5,16.6,16.6,31.2c6.1,9.1,13.1,15.3,18.9,19.3 c21.1,14.6,44.9,15.5,70.1,16.5c22.7,0.9,48.5,1.9,77.9,11.6c12.2,4,24.9,11.8,39.5,20.8c35.2,21.7,83.5,51.3,164.2,51.3 c80.8,0,129.3-29.8,164.8-51.5c14.6-8.9,27.2-16.7,39-20.6c29.4-9.7,55.2-10.7,77.9-11.6c25.2-1,48.9-1.9,70.1-16.5 c6.6-4.6,15-12.1,21.6-23.5c7.2-12.3,7.1-21,13.9-26.9c2.8-2.4,8.9-4.5,12.2-5.5c17.1-4.7,39-11.6,64.9-25.9 c11.5-6.3,20.4-13.2,27.5-21.1c0.1-0.1,0.2-0.2,0.3-0.3C1023.4,791.7,1028.3,767.2,1020.3,745.5z M948.6,784 c-43.8,24.2-72.9,21.6-95.5,36.1c-19.2,12.4-7.9,39.1-21.8,48.7c-17.2,11.9-67.9-0.8-133.4,20.8c-54,17.9-88.5,69.2-185.8,69.2 c-97.5,0-131-51.1-185.8-69.2c-65.5-21.6-116.3-8.9-133.4-20.8c-13.9-9.6-2.6-36.3-21.8-48.7c-22.6-14.6-51.7-12-95.5-36.1 c-27.9-15.4-12.1-24.9-2.8-29.4c158.6-76.7,183.8-195.3,185-204.2c1.4-10.6,2.9-19-8.8-29.9c-11.3-10.5-61.6-41.6-75.5-51.3 c-23.1-16.1-33.2-32.2-25.7-52c5.2-13.7,18-18.8,31.5-18.8c4.2,0,8.5,0.5,12.6,1.4c25.3,5.5,49.9,18.2,64.1,21.6 c2,0.5,3.7,0.7,5.2,0.7c7.6,0,10.2-3.8,9.7-12.5c-1.6-27.7-5.6-81.7-1.2-132.2c6-69.4,28.4-103.8,55-134.3 c12.8-14.6,72.8-78,187.5-78c115,0,174.7,63.4,187.5,78c26.6,30.4,49,64.8,55,134.3c4.4,50.5,0.6,104.5-1.2,132.2 c-0.6,9.1,2.2,12.5,9.7,12.5c1.5,0,3.3-0.2,5.2-0.7c14.2-3.4,38.8-16.1,64.1-21.6c4.1-0.9,8.4-1.4,12.6-1.4 c13.5,0,26.3,5.2,31.5,18.8c7.5,19.8-2.7,35.9-25.7,52c-13.9,9.7-64.2,40.8-75.5,51.3c-11.7,10.8-10.2,19.2-8.8,29.9 c1.1,8.9,26.4,127.5,185,204.2C960.6,759.1,976.5,768.6,948.6,784z\\\" /> </svg>\",\n google:'<svg viewBox=\"0 0 24 24\"><path fill=\"#34a853\" d=\"M4 22.93a4 4 0 1 1 0-8 4 4 0 0 1 0 8Z\"/><path fill=\"#4285f4\" d=\"M23.464 16.929 15.463 3.072A4 4 0 0 0 8.534 7.072l8.001 13.857a4 4 0 0 0 6.929-4Z\"/><path fill=\"#fbbc04\" d=\"M7.514 4.844 1.565 15.148A4.5 4.5 0 0 1 4 14.43a4.5 4.5 0 0 1 4.494 4.715l3.217-5.573-3.61-6.25a4 4 0 0 1-.587-2.478Z\"/></svg>',\n meta:'<svg viewBox=\"0 0 24 24\"><path fill=\"#0866ff\" d=\"M6.915 4.03C2.484 4.03 0 9.95 0 14.449c0 3.37 1.276 5.521 4.439 5.521 2.93 0 4.146-2.574 6.628-6.764l.942-1.664 2.335 3.895c1.883 3.15 3.38 4.533 5.53 4.533 2.788 0 4.126-1.93 4.126-5.56 0-5.53-2.73-10.38-6.8-10.38-2.04 0-3.835 1.53-5.173 3.348C10.16 5.01 8.593 4.03 6.915 4.03Zm-.04 2.606c1.55 0 2.445 1.193 3.908 3.025l-1.02 1.566c-2.22 3.41-3.576 6.155-5.323 6.155-1.23 0-2.154-1.075-2.154-2.9 0-3.755 2.088-7.846 4.588-7.846Zm10.2-.553c2.488 0 4.639 4.054 4.639 8.4 0 1.547-.368 2.899-1.839 2.899-1.193 0-2.027-1.42-4.496-5.362l-1.872-3.008c1.12-1.814 2.248-2.929 3.559-2.929Z\"/></svg>',\n tiktok:'<svg viewBox=\"0 0 58 58\"><path fill=\"#2dccd3\" d=\"M25.98 0v37.68c0 4.94-3.55 8.11-7.88 8.11-1.43 0-2.79-.33-3.97-.95 1.5 1.91 3.87 3.01 6.47 3.01 4.32 0 7.87-3.17 7.87-8.11V2.06h6.85A20.3 20.3 0 0 1 34.87 0h-8.89Z\"/><path fill=\"#f1204a\" d=\"M41.73 11.11a17.48 17.48 0 0 1-4.37-9.05h-2.04c1.16 4.23 3.56 7.18 6.41 9.05Zm7.63 11.37a19.31 19.31 0 0 1-11-2.97c3.84 3.84 8.5 5.03 13.5 5.03v-8.82a17.4 17.4 0 0 1-2.5-.37v7.13Z\"/><path fill=\"currentColor\" d=\"M35.32 2.06h-6.85v37.68c0 4.94-3.55 8.11-7.87 8.11-2.6 0-4.97-1.1-6.47-3.01-2.48-1.29-4.19-3.82-4.19-7.16 0-5.71 4.47-8.71 10.42-8.09v-7.68C10.63 21.93 2.49 29.73 2.49 39.4c0 5.16 2.04 9.71 5.32 12.96 2.89 1.97 6.39 3.11 10.15 3.11 8.69 0 17.91-6.38 17.91-18.41V17.45c.8.8 1.63 1.48 2.49 2.06a19.31 19.31 0 0 0 11 2.97v-7.13a16.14 16.14 0 0 1-7.63-4.24c-2.85-1.87-5.25-4.82-6.41-9.05Z\"/></svg>',\n apple:'<svg viewBox=\"0 0 24 24\"><path fill=\"currentColor\" d=\"M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09Zm3.377-3.065C16.372 2.819 16.929 1.403 16.774 0c-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.56-1.701Z\"/></svg>',\n microsoft:'<svg viewBox=\"0 0 24 24\"><path fill=\"#f25022\" d=\"M0 0h11.4v11.4H0Z\"/><path fill=\"#7fba00\" d=\"M12.6 0H24v11.4H12.6Z\"/><path fill=\"#00a4ef\" d=\"M0 12.6h11.4V24H0Z\"/><path fill=\"#ffb900\" d=\"M12.6 12.6H24V24H12.6Z\"/></svg>',\n reddit:'<svg viewBox=\"0 0 24 24\"><path fill=\"#ff4500\" d=\"M12 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0Zm5.01 4.744c.688 0 1.25.561 1.25 1.249a1.25 1.25 0 0 1-2.498.056l-2.597-.547-.8 3.747c1.824.07 3.48.632 4.674 1.488.308-.309.73-.491 1.207-.491.968 0 1.754.786 1.754 1.754 0 .716-.435 1.333-1.01 1.614.028.169.042.342.042.52 0 2.694-3.13 4.87-7.004 4.87-3.874 0-7.004-2.176-7.004-4.87 0-.183.015-.366.043-.534A1.748 1.748 0 0 1 4.028 12c0-.968.786-1.754 1.754-1.754.463 0 .898.196 1.207.49 1.207-.883 2.878-1.43 4.744-1.487l.885-4.182a.342.342 0 0 1 .378-.239l2.906.617a1.214 1.214 0 0 1 1.108-.701Z\"/></svg>'\n };\n const logo = (id) => '<span class=\"logo '+esc(id)+'\" aria-hidden=\"true\">'+(providerSvg[id] || esc(initials(id)))+'</span>';\n let syntheticResult = false;\n const chrome = (body, context) => '<header class=\"top\"><div class=\"brand\"><span class=\"dot\"></span><b>adport.dev</b></div><span class=\"context\">'+(syntheticResult?'Synthetic demo · ':'')+esc(context || '')+'</span></header><section class=\"content\">'+body+'</section>';\n function renderAccounts(data, meta) {\n const accounts = arr(data.accounts), errors = arr(data.errors), names = meta.providerNames || {};\n const body = notices(data)+(accounts.length ? '<div class=\"list\">'+accounts.map(a => { const status=statusOf(a.status); return '<div class=\"row\"><div class=\"identity\">'+logo(a.provider)+'<div class=\"identity-copy\"><b>'+esc(a.name || 'Ad account')+'</b><span>'+esc(providerName(a.provider,names))+' · '+esc(a.id)+(a.currency ? ' · '+esc(a.currency) : '')+'</span></div></div><span class=\"pill '+status.tone+'\">'+esc(status.label)+'</span></div>'; }).join('')+'</div>' : '<div class=\"empty\">'+(errors.length ? 'Account inventory could not be fully loaded.' : 'No accessible ad accounts were returned.')+'</div>');\n app.innerHTML = chrome(body, accounts.length+' account'+(accounts.length===1?'':'s'));\n }\n function renderReport(data) {\n const groups = new Map();\n for (const row of arr(data.rows)) {\n const currency=currencyOf(row), key=currency || JSON.stringify([row.provider,row.accountId]);\n if (!groups.has(key)) groups.set(key,{key,currency,label:currency || (row.provider+' · '+row.accountId),rows:[]});\n groups.get(key).rows.push(row);\n }\n const choices=[...groups.values()];\n const selected=groups.get(state.reportGroup) || choices[0];\n const rows=selected?.rows || [], currency=selected?.currency;\n state.reportGroup=selected?.key;\n const tabs=choices.length>1 ? '<div class=\"tabs\" role=\"group\" aria-label=\"Report currency or account\">'+choices.map((g,i)=>'<button data-group=\"'+i+'\" aria-pressed=\"'+(g===selected)+'\">'+esc(g.label)+'</button>').join('')+'</div>' : '';\n const summary=arr(data.summary?.groups).find(group=>group.key===selected?.key)?.metrics;\n const aggregate=key=>summary ? (available(summary[key])?summary[key]:null) : total(rows,key);\n const spend=aggregate('spend'), returns=rows.map(rowReturn);\n const value=returns.length && returns.every(available) ? returns.reduce((sum,value)=>sum+value,0) : null;\n const ratio=summary ? summary.roas : spend>0 && value!==null ? value/spend : null;\n const roas=available(ratio) ? ratio.toFixed(2)+'×' : '—';\n const metric=state.reportMetric, labels={spend:'Spend',clicks:'Clicks',conversions:'Conversions',roas:'ROAS'};\n const metricValue=r=>metric==='roas' ? (available(r.metrics?.conversion_value) && r.metrics?.spend>0 ? r.metrics.conversion_value/r.metrics.spend : r.metrics?.roas) : r.metrics?.[metric];\n const format=value=>metric==='spend'?money(value,currency):metric==='roas'?value.toFixed(2)+'×':compact(value);\n const ranked=[...rows].filter(r=>available(metricValue(r))).sort((a,b)=>metricValue(b)-metricValue(a)).slice(0,6), max=Math.max(1,...ranked.map(metricValue));\n const bars=ranked.length ? ranked.map(r=>'<div class=\"bar-row\"><span class=\"bar-name\" title=\"'+esc(r.entity?.name || r.entity?.id)+'\">'+logo(r.provider)+'<span>'+esc(r.entity?.name || r.entity?.id || 'Entity')+'</span></span><span class=\"track\" aria-hidden=\"true\"><span class=\"fill\" style=\"display:block;width:'+Math.max(0,metricValue(r)/max*100).toFixed(1)+'%\"></span></span><span class=\"bar-value\">'+esc(format(metricValue(r)))+'</span></div>').join('') : '<div class=\"empty\">No '+esc(labels[metric])+' values were returned.</div>';\n const kpi=(key,label,value)=>'<button class=\"kpi\" data-metric=\"'+key+'\" aria-pressed=\"'+(metric===key)+'\" aria-label=\"Chart '+esc(label)+'\"><small>'+esc(label)+'</small><strong>'+esc(value)+'</strong></button>';\n const period=typeof data.date_range==='string' ? data.date_range.replaceAll('_',' ') : data.date_range ? data.date_range.start+' – '+data.date_range.end : 'Selected period';\n const body=notices(data)+tabs+(rows.length ? (!currency?'<p class=\"notice\">Currency unavailable. These values belong to this account only; no cross-account money total is calculated.</p>':'')+'<div class=\"kpis\" role=\"group\" aria-label=\"Chart metric\">'+kpi('spend','Spend',spend===null?'—':money(spend,currency))+kpi('clicks','Clicks',total(rows,'clicks')===null?'—':compact(total(rows,'clicks')))+kpi('conversions','Conversions',total(rows,'conversions')===null?'—':compact(total(rows,'conversions')))+kpi('roas','ROAS',roas)+'</div><div class=\"panel\"><div class=\"panel-head\"><b>'+esc(labels[metric])+'</b><span>Top '+ranked.length+' of '+rows.length+' rows</span></div><div class=\"bars\">'+bars+'</div></div>' : '<div class=\"empty\">'+(arr(data.errors).length?'Report unavailable for the requested providers.':'No rows returned for this period.')+'</div>');\n app.innerHTML=chrome(body,period+(currency?' · '+currency:''));\n app.querySelectorAll('[data-group]').forEach(button=>button.addEventListener('click',()=>{state.reportGroup=choices[Number(button.dataset.group)].key;renderReport(data);}));\n app.querySelectorAll('[data-metric]').forEach(button=>button.addEventListener('click',()=>{state.reportMetric=button.dataset.metric;renderReport(data);}));\n }\n function renderOperation(data, meta) {\n if (meta.tool === 'recommendation_apply' && data.result) data = data.result;\n const preview = data.preview || {}, pending = data.pending_operation_id, applied = data.status === 'applied' || data.applied === true;\n const changes = arr(preview.changes), coercions = arr(preview.coercions), deltas = arr(preview.budgetDeltas);\n // Review amounts must preserve micros; rounded report totals are not suitable for consent.\n const comparisons=deltas.map(v=>{const currency=currencyOf(v);return {label:(v.target || 'Budget')+(currency?' · '+currency:' (account units)'),before:available(v.fromMicros)?money(v.fromMicros/1e6,currency,6):'—',after:available(v.toMicros)?money(v.toMicros/1e6,currency,6):'—'};});\n // Split only explicit field/value arrows. Freeform JSON updates still\n // show the proposed payload, but never claim a previous value.\n for (const change of changes) {\n const match=String(change).match(/^~\\s+(?:.+?\\s+)?(status|configured_status|bidding_strategy|delivery|bid|dailyBudget\\.value|DailyBudget|value)\\s*:?\\s*(.*?)\\s*→\\s*(.+)$/i);\n if (match) { const label=match[1].replaceAll('_',' ').replace(/([a-z])([A-Z])/g,'$1 $2');comparisons.push({label:label[0].toUpperCase()+label.slice(1),before:match[2].trim() || '—',after:match[3].trim()}); }\n }\n // Other provider plans still have a concrete change list. Show the\n // proposed effect without pretending we fetched the previous object.\n for (const change of changes.slice(0,12)) {\n const value=String(change).trim();\n if (/^~\\s+(?:.+?\\s+)?(status|configured_status|bidding_strategy|delivery|bid|dailyBudget\\.value|DailyBudget|value)\\s*:?\\s*.*?\\s*→\\s*.+$/i.test(value)) continue;\n if (deltas.length && /\\b(budget|amount_micros)\\b/i.test(value) && /\\s*→\\s*/.test(value)) continue;\n const kind=value[0];\n comparisons.push({\n label:kind==='+'?'Create':kind==='-'?'Remove':kind==='~'?'Update':'Change',\n before:kind==='+'?'Not present':kind==='-'?value.slice(1).trim():'Not provided',\n after:kind==='-'?'Removed':/^[+~!]\\s*/.test(value)?value.replace(/^[+~!]\\s*/,''):value,\n });\n }\n if (!comparisons.length && preview.summary) comparisons.push({label:'Proposed change',before:'Not provided',after:String(preview.summary)});\n const title=String(preview.summary || '').match(/\"([^\"]+)\"/)?.[1] || (comparisons.length ? '' : preview.summary);\n const validation=preview.serverValidated===true?'server validated':preview.serverValidated===false?'local preview · not server validated':'validation not reported';\n const table=comparisons.length?'<table class=\"comparison\" aria-label=\"Before and after\"><thead><tr><th scope=\"col\">Change</th><th scope=\"col\">Before</th><th scope=\"col\">After</th></tr></thead><tbody>'+comparisons.map(v=>'<tr><td>'+esc(v.label)+'</td><td>'+esc(v.before)+'</td><td class=\"'+(v.before!==v.after?'changed':'')+'\">'+esc(v.after)+'</td></tr>').join('')+'</tbody></table>':'<p class=\"notice\">No change details were returned. Review the tool response before applying.</p>';\n const approval=meta.approval;\n const canApprove=typeof pending==='string' && pending.length>0 && typeof preview.summary==='string' && preview.summary.trim() && approval?.arguments && typeof approval.arguments==='object' && !Array.isArray(approval.arguments) && typeof meta.tool==='string';\n const action=canApprove?'<div class=\"approval\"><button class=\"approve\" data-approve=\"true\" '+(state.approving?'disabled':'')+'>'+(state.approving?'Applying…':'Approve and apply')+'</button><span class=\"context\">Expires '+esc(data.expires_at || 'soon')+'</span></div>':'';\n const body=(title?'<p class=\"operation-name\">'+esc(title)+'</p>':'')+table+(changes.length>12?'<p class=\"notice\">Showing 12 of '+changes.length+' changes. All changes are in Details.</p>':'')+coercions.map(v=>'<p class=\"adjustment\">'+esc(v)+'</p>').join('')+(state.approvalError?'<p class=\"notice\" role=\"alert\">'+esc(state.approvalError)+'</p>':'')+action+(applied?'<p class=\"notice\">Applied. '+esc(preview.summary || 'The change was submitted.')+'</p>':'')+'<details><summary>Details</summary><p>'+esc(validation)+'</p><p>'+esc(preview.summary || 'No change details returned.')+'</p>'+changes.map(v=>'<p>'+esc(v)+'</p>').join('')+(pending?'<p>Nothing has been changed. Apply requires the matching pending operation token before it expires.</p>':'')+'<p>'+esc(meta.tool || '')+'</p></details>';\n app.innerHTML = chrome(body, applied?'Applied':pending?'Preview · Not applied':'Result');\n if (canApprove) app.querySelectorAll('[data-approve]').forEach(button=>button.addEventListener('click',()=>approve(meta.tool,approval.arguments,pending)));\n }\n const pendingRequests=new Map();\n async function approve(tool,args,pending) {\n if (state.approving || !state.result) return;\n state.approving=true;state.approvalError='';render(state.result);\n const requestId=id++;\n const response=new Promise((resolve,reject)=>{\n const timer=setTimeout(()=>{\n pendingRequests.delete(requestId);\n reject(new Error('No confirmation arrived. The write may have succeeded; check its status before retrying.'));\n },30000);\n pendingRequests.set(requestId,{resolve,reject,timer});\n });\n send({jsonrpc:'2.0',id:requestId,method:'tools/call',params:{name:tool,arguments:{...args,pending_operation_id:pending}}});\n try {\n const result=await response;\n if (!result || result.isError) throw new Error('Adport could not confirm the change. Check its status before retrying.');\n const value=result.structuredContent || result;\n const outcome=tool==='recommendation_apply'?value.result:value;\n if (outcome?.applied!==true || outcome?.status!=='applied') throw new Error('The change was not confirmed as applied. Check its status before retrying.');\n state.approving=false;state.approvalError='';acceptResult(result);\n } catch (error) {\n state.approving=false;state.approvalError=error?.message || 'The change could not be confirmed. Check its status before retrying.';\n render(state.result);\n }\n }\n function renderInsights(data) {\n const items = data.finding ? [data.finding] : arr(data.findings || data.recommendations || data.results || data.entries);\n const body = items.length ? '<div class=\"list\">'+items.slice(0,8).map((item,i)=>'<div class=\"row\"><div class=\"identity\"><span class=\"logo\" style=\"background:var(--orange)\">'+(i+1)+'</span><div class=\"identity-copy\"><b>'+esc(item.title || item.summary || item.rule || 'Opportunity')+'</b><span>'+esc(item.description || item.status || item.severity || 'Review recommended')+'</span></div></div><span class=\"pill '+(/high|critical/i.test(item.severity || '')?'danger':'')+'\">'+esc(item.severity || item.status || 'open')+'</span></div>').join('')+'</div>' : '<div class=\"empty\">No active recommendations were returned.</div>';\n app.innerHTML = chrome(body, items.length+' recommendation'+(items.length===1?'':'s'));\n }\n function render(result) {\n let data = result?.structuredContent || result || {};\n if (!result?.structuredContent && Array.isArray(result?.content)) {\n for (const item of result.content) {\n if (item.type !== 'text') continue;\n try { const parsed = JSON.parse(item.text); if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { data = parsed; break; } } catch {}\n }\n }\n const meta = data._adport || {};\n syntheticResult = data.data_source === 'synthetic';\n if (data.cancelled) {\n app.innerHTML=chrome('<p class=\"notice\">'+esc(data.message || 'The host interrupted this request. Check the tool response before retrying.')+'</p>','Request interrupted');\n return;\n }\n if (result?.isError || data.error) {\n app.innerHTML=chrome('<p class=\"notice\">'+esc(data.message || 'The request could not complete. See the tool response for details.')+'</p>','Request failed');\n return;\n }\n if (meta.view === 'accounts') return renderAccounts(data,meta);\n if (meta.view === 'report') return renderReport(data,meta);\n if (meta.view === 'operation') return renderOperation(data,meta);\n return renderInsights(data,meta);\n }\n function acceptResult(result) {\n if (!result || typeof result !== 'object') return;\n clearTimeout(resultWait);\n // ChatGPT can deliver the same result through both supported bridges.\n // Do not reset an open disclosure when the second copy arrives.\n if (state.result && JSON.stringify(state.result) === JSON.stringify(result)) return;\n state.result = result;\n render(result);\n }\n function receiveGlobals(globals) {\n if (!globals) return;\n const metadata = globals.toolResponseMetadata;\n const envelope = metadata?.mcp_tool_result || metadata?.call_tool_result;\n if (envelope && typeof envelope === 'object') return acceptResult(envelope);\n if (globals.toolOutput && typeof globals.toolOutput === 'object') acceptResult({structuredContent:globals.toolOutput});\n }\n // Some hosts mount an error result's resource but never relay its payload.\n // This is a delivery fallback, not a claim about tool execution or success.\n const resultWait = setTimeout(() => {\n if (!state.result) app.innerHTML=chrome('<p class=\"notice\">The host has not provided a result to this view. Check the tool response in the conversation. This card will update if a result arrives.</p>','Result not received');\n }, 15000);\n const send = (message) => window.parent.postMessage(message,'*');\n const resize = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(() => {\n send({jsonrpc:'2.0',method:'ui/notifications/size-changed',params:{height:Math.ceil(document.body.getBoundingClientRect().height)}});\n });\n let id = 1;\n window.addEventListener('message', (event) => {\n if (event.source !== window.parent) return;\n const message = event.data;\n if (!message || message.jsonrpc !== '2.0') return;\n if (message.id !== undefined && pendingRequests.has(message.id)) {\n const request=pendingRequests.get(message.id);\n pendingRequests.delete(message.id);\n clearTimeout(request.timer);\n if (message.error) request.reject(message.error);\n else request.resolve(message.result);\n return;\n }\n if (message.id === 1 && message.result) {\n state.host = message.result.hostContext || {};\n document.documentElement.dataset.theme = state.host.theme || '';\n send({jsonrpc:'2.0',method:'ui/notifications/initialized'});\n resize?.observe(document.body);\n if (state.result) render(state.result);\n }\n if (message.method === 'ui/notifications/tool-result') acceptResult(message.params);\n if (message.method === 'ui/notifications/tool-cancelled') acceptResult({structuredContent:{cancelled:true,message:message.params?.reason}});\n if (message.method === 'ui/notifications/host-context-changed') {\n const previousLocale = state.host.locale;\n state.host = {...state.host,...message.params};\n document.documentElement.dataset.theme = state.host.theme || '';\n // Size/theme updates must not rebuild the DOM: opening Details changes\n // the iframe height, which some hosts echo back as a context update.\n if (state.result && previousLocale !== state.host.locale) {\n const expanded = app.querySelector('details')?.open || false;\n render(state.result);\n const details = app.querySelector('details');\n if (details) details.open = expanded;\n }\n }\n });\n // The compatibility bridge can hydrate after the iframe has mounted,\n // including full error envelopes in toolResponseMetadata.\n window.addEventListener('openai:set_globals', event => receiveGlobals(event.detail?.globals));\n send({jsonrpc:'2.0',id:id++,method:'ui/initialize',params:{appInfo:{name:'Adport Insight',version:'1.0.0'},appCapabilities:{},protocolVersion:'2026-01-26'}});\n receiveGlobals(window.openai);\n })();\n </script>\n</body>\n</html>`;\n"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,SAAS;AAClB,SAAS,qBAAqB,iBAAiB,0BAA0B;AACzE,SAAS,aAAa,iBAAiB,qBAA8D;AACrG,SAAS,0BAA0B;AACnC,SAAS,wBAAwB;AACjC,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAClC,SAAS,6BAA6B;AACtC,SAAS,0BAA0B;AACnC,SAAS,4BAA4B;AACrC,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AACtC,SAAS,4BAA4B;AACrC,SAAS,qBAAqB;;;ACf9B;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,SAAW;AAAA,EACX,MAAQ;AAAA,EACR,MAAQ;AAAA,EACR,OAAS;AAAA,EACT,S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C,EAAG,IACpH;AAAA,YACA,OAAO;AAAA;AAAA;AAAA,YAGP,SAAS;AAAA,UACX;AAAA,QAAC;AACL,eAAO;AAAA,UACL,SAAS,CAAC,EAAE,MAAM,QAAiB,MAAM,KAAK,UAAU,SAAS,MAAM,CAAC,EAAE,CAAC;AAAA,UAC3E,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AACA,QAAI,MAAM;AACR,sBAAgB,QAAQ,KAAK,MAAM;AAAA,QACjC,GAAG;AAAA,QACH,OAAO;AAAA,UACL,IAAI,EAAE,aAAa,eAAe,YAAY,CAAC,SAAS,KAAK,EAAE;AAAA,UAC/D,2BAA2B;AAAA,UAC3B,yBAAyB;AAAA,UACzB,kCAAkC,OAAQ;AAAA,UAC1C,iCAAiC,OAAQ;AAAA,QAC3C;AAAA,MACF,GAAG,QAAQ;AAAA,IACb,OAAO;AACL,aAAO,aAAa,KAAK,MAAM,QAAQ,QAAQ;AAAA,IACjD;AAAA,EACF;AACA,SAAO;AACT;AAEA,eAAsB,eAAe,SAAwB,SAAiC;AAC5F,QAAM,SAAS,gBAAgB,EAAE,SAAS,QAAQ,CAAC;AACnD,QAAM,OAAO,QAAQ,IAAI,qBAAqB,CAAC;AAE/C,UAAQ,MAAM,+BAA+B,QAAQ,SAAS,KAAK,EAAE,MAAM,mBAAmB,QAAQ,YAAY,GAAG;AACrH,MAAI,QAAQ,IAAI,UAAU,KAAK,EAAE,WAAW,GAAG;AAC7C,YAAQ,MAAM,8GAA8G;AAAA,EAC9H;AACF;","names":[]}
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import { AdportRuntime } from '@adport/core';
3
3
 
4
- declare const PROVIDER_IDS: readonly ["google", "meta", "tiktok", "apple", "microsoft", "reddit"];
4
+ declare const PROVIDER_IDS: readonly ["google", "meta", "tiktok", "apple", "microsoft", "reddit", "snapchat", "spotify", "pinterest", "linkedin", "x"];
5
5
  /**
6
6
  * Standard runtime assembly: real providers whose credentials exist. Mock data
7
7
  * is opt-in so a live runtime never silently substitutes synthetic accounts.
@@ -14,12 +14,36 @@ interface CreateServerOptions {
14
14
  runtime: AdportRuntime;
15
15
  name?: string;
16
16
  version?: string;
17
+ /** Brand icons advertised to MCP clients during initialization. */
18
+ icons?: Array<{
19
+ src: string;
20
+ mimeType?: string;
21
+ sizes?: string[];
22
+ }>;
23
+ /** When set by a remote transport, only register tools authorized by this key. */
24
+ scopes?: readonly string[];
25
+ /**
26
+ * Register tools blocked by a dynamic entitlement and return this structured
27
+ * error when called. Missing credential scopes without a denial stay hidden.
28
+ */
29
+ scopeDenials?: Readonly<Record<string, ToolScopeDenial | undefined>>;
30
+ /** Hosted transports can replace local CLI setup guidance, without changing the error code. */
31
+ notConnectedMessage?: string;
32
+ /** Hosted production must never serve synthetic results or demo tool definitions. */
33
+ productionOnly?: boolean;
34
+ /** Host-specific MCP Apps sandbox domain; OpenAI's widget domain stays independent. */
35
+ uiDomain?: string;
36
+ }
37
+ interface ToolScopeDenial {
38
+ code: string;
39
+ message: string;
40
+ data?: Record<string, unknown>;
17
41
  }
18
42
  /**
19
43
  * Thin adapter: every tool in the shared registry becomes an MCP tool.
20
44
  * No tool logic lives here — see the "one tool-definition layer" principle.
21
45
  */
22
- declare function createMcpServer({ runtime, name, version }: CreateServerOptions): McpServer;
46
+ declare function createMcpServer({ runtime, name, version, icons, scopes, scopeDenials, notConnectedMessage, productionOnly, uiDomain }: CreateServerOptions): McpServer;
23
47
  declare function runStdioServer(runtime: AdportRuntime, version?: string): Promise<void>;
24
48
 
25
- export { type AssembleRuntimeOptions, type CreateServerOptions, PROVIDER_IDS, assembleRuntime, createMcpServer, runStdioServer };
49
+ export { type AssembleRuntimeOptions, type CreateServerOptions, PROVIDER_IDS, type ToolScopeDenial, assembleRuntime, createMcpServer, runStdioServer };
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  assembleRuntime,
4
4
  createMcpServer,
5
5
  runStdioServer
6
- } from "./chunk-6RBLUIBN.js";
6
+ } from "./chunk-YCSBIOYH.js";
7
7
  export {
8
8
  PROVIDER_IDS,
9
9
  assembleRuntime,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adport/mcp",
3
- "version": "0.5.2",
3
+ "version": "0.6.1",
4
4
  "description": "adport MCP server — the open control plane for paid media",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -19,15 +19,21 @@
19
19
  "dist"
20
20
  ],
21
21
  "dependencies": {
22
- "@modelcontextprotocol/sdk": "^1.12.0",
22
+ "@modelcontextprotocol/ext-apps": "^1.7.5",
23
+ "@modelcontextprotocol/sdk": "^1.30.0",
23
24
  "zod": "^4.4.3",
24
- "@adport/provider-google": "0.5.2",
25
- "@adport/provider-microsoft": "0.5.2",
26
- "@adport/provider-meta": "0.5.2",
27
- "@adport/core": "0.5.2",
28
- "@adport/provider-tiktok": "0.5.2",
29
- "@adport/provider-reddit": "0.5.2",
30
- "@adport/provider-apple": "0.5.2"
25
+ "@adport/core": "0.6.1",
26
+ "@adport/provider-apple": "0.6.1",
27
+ "@adport/provider-google": "0.6.1",
28
+ "@adport/provider-meta": "0.6.1",
29
+ "@adport/provider-microsoft": "0.6.1",
30
+ "@adport/provider-reddit": "0.6.1",
31
+ "@adport/provider-snapchat": "0.6.1",
32
+ "@adport/provider-pinterest": "0.6.1",
33
+ "@adport/provider-spotify": "0.6.1",
34
+ "@adport/provider-linkedin": "0.6.1",
35
+ "@adport/provider-tiktok": "0.6.1",
36
+ "@adport/provider-x": "0.6.1"
31
37
  },
32
38
  "devDependencies": {
33
39
  "@types/node": "^26.1.2",
@@ -37,6 +43,7 @@
37
43
  },
38
44
  "scripts": {
39
45
  "build": "tsup src/index.ts src/bin.ts --format esm --dts --sourcemap --clean",
46
+ "render:submission-previews": "node scripts/render-submission-previews.mjs",
40
47
  "test": "vitest run",
41
48
  "typecheck": "tsc --noEmit",
42
49
  "clean": "rm -rf dist"
@@ -1,114 +0,0 @@
1
- // src/index.ts
2
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
- import { AdportError, CredentialStore, createContext } from "@adport/core";
5
- import { createGoogleModule } from "@adport/provider-google";
6
- import { createMetaModule } from "@adport/provider-meta";
7
- import { createTikTokModule } from "@adport/provider-tiktok";
8
- import { createAppleModule } from "@adport/provider-apple";
9
- import { createMicrosoftModule } from "@adport/provider-microsoft";
10
- import { createRedditModule } from "@adport/provider-reddit";
11
-
12
- // package.json
13
- var package_default = {
14
- name: "@adport/mcp",
15
- version: "0.5.2",
16
- description: "adport MCP server \u2014 the open control plane for paid media",
17
- license: "Apache-2.0",
18
- type: "module",
19
- main: "./dist/index.js",
20
- types: "./dist/index.d.ts",
21
- exports: {
22
- ".": {
23
- types: "./dist/index.d.ts",
24
- import: "./dist/index.js"
25
- }
26
- },
27
- bin: {
28
- "adport-mcp": "./dist/bin.js"
29
- },
30
- files: ["dist"],
31
- scripts: {
32
- build: "tsup src/index.ts src/bin.ts --format esm --dts --sourcemap --clean",
33
- test: "vitest run",
34
- typecheck: "tsc --noEmit",
35
- clean: "rm -rf dist"
36
- },
37
- dependencies: {
38
- "@adport/core": "workspace:*",
39
- "@adport/provider-apple": "workspace:*",
40
- "@adport/provider-google": "workspace:*",
41
- "@adport/provider-meta": "workspace:*",
42
- "@adport/provider-microsoft": "workspace:*",
43
- "@adport/provider-reddit": "workspace:*",
44
- "@adport/provider-tiktok": "workspace:*",
45
- "@modelcontextprotocol/sdk": "^1.12.0",
46
- zod: "^4.4.3"
47
- },
48
- devDependencies: {
49
- "@types/node": "^26.1.2",
50
- tsup: "^8.3.0",
51
- typescript: "^5.8.0",
52
- vitest: "^4.1.10"
53
- }
54
- };
55
-
56
- // src/index.ts
57
- var PROVIDER_IDS = ["google", "meta", "tiktok", "apple", "microsoft", "reddit"];
58
- async function assembleRuntime(options = {}) {
59
- const store = new CredentialStore();
60
- const modules = [];
61
- const includeMock = options.includeMock ?? process.env.ADPORT_DEMO === "true";
62
- if (!includeMock) {
63
- for (const factory of [createGoogleModule, createMetaModule, createTikTokModule, createAppleModule, createMicrosoftModule, createRedditModule]) {
64
- const module = await factory(store);
65
- if (module) modules.push(module);
66
- }
67
- }
68
- return createContext({ providerModules: modules, includeMock });
69
- }
70
- function createMcpServer({ runtime, name = "adport", version = package_default.version }) {
71
- const server = new McpServer({ name, version });
72
- for (const tool of runtime.registry.list()) {
73
- server.registerTool(
74
- tool.name,
75
- {
76
- description: tool.description,
77
- inputSchema: tool.input.shape,
78
- annotations: {
79
- readOnlyHint: tool.annotations.readOnly ?? false,
80
- destructiveHint: tool.annotations.destructive ?? false
81
- }
82
- },
83
- async (args) => {
84
- try {
85
- const result = await runtime.registry.call(tool.name, args, runtime.ctx);
86
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
87
- } catch (err) {
88
- const payload = err instanceof AdportError ? err.toJSON() : { error: "INTERNAL", message: err instanceof Error ? err.message : String(err) };
89
- return {
90
- content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
91
- isError: true
92
- };
93
- }
94
- }
95
- );
96
- }
97
- return server;
98
- }
99
- async function runStdioServer(runtime, version) {
100
- const server = createMcpServer({ runtime, version });
101
- await server.connect(new StdioServerTransport());
102
- console.error(`adport MCP server on stdio (${runtime.registry.list().length} tools, policy: ${runtime.policySource})`);
103
- if (runtime.ctx.providers.list().length === 0) {
104
- console.error("No ad providers connected. Run `adport connect <provider>` or restart with `--demo` for synthetic mock data.");
105
- }
106
- }
107
-
108
- export {
109
- PROVIDER_IDS,
110
- assembleRuntime,
111
- createMcpServer,
112
- runStdioServer
113
- };
114
- //# sourceMappingURL=chunk-6RBLUIBN.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts","../package.json"],"sourcesContent":["import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { AdportError, CredentialStore, createContext, type AdportRuntime, type ProviderModule } from '@adport/core';\nimport { createGoogleModule } from '@adport/provider-google';\nimport { createMetaModule } from '@adport/provider-meta';\nimport { createTikTokModule } from '@adport/provider-tiktok';\nimport { createAppleModule } from '@adport/provider-apple';\nimport { createMicrosoftModule } from '@adport/provider-microsoft';\nimport { createRedditModule } from '@adport/provider-reddit';\nimport packageJson from '../package.json';\n\nexport const PROVIDER_IDS = ['google', 'meta', 'tiktok', 'apple', 'microsoft', 'reddit'] as const;\n\n/**\n * Standard runtime assembly: real providers whose credentials exist. Mock data\n * is opt-in so a live runtime never silently substitutes synthetic accounts.\n */\nexport interface AssembleRuntimeOptions {\n includeMock?: boolean;\n}\n\nexport async function assembleRuntime(options: AssembleRuntimeOptions = {}): Promise<AdportRuntime> {\n const store = new CredentialStore();\n const modules: ProviderModule[] = [];\n const includeMock = options.includeMock ?? process.env.ADPORT_DEMO === 'true';\n if (!includeMock) {\n for (const factory of [createGoogleModule, createMetaModule, createTikTokModule, createAppleModule, createMicrosoftModule, createRedditModule]) {\n const module = await factory(store);\n if (module) modules.push(module);\n }\n }\n return createContext({ providerModules: modules, includeMock });\n}\n\nexport interface CreateServerOptions {\n runtime: AdportRuntime;\n name?: string;\n version?: string;\n}\n\n/**\n * Thin adapter: every tool in the shared registry becomes an MCP tool.\n * No tool logic lives here — see the \"one tool-definition layer\" principle.\n */\nexport function createMcpServer({ runtime, name = 'adport', version = packageJson.version }: CreateServerOptions): McpServer {\n const server = new McpServer({ name, version });\n for (const tool of runtime.registry.list()) {\n server.registerTool(\n tool.name,\n {\n description: tool.description,\n inputSchema: tool.input.shape,\n annotations: {\n readOnlyHint: tool.annotations.readOnly ?? false,\n destructiveHint: tool.annotations.destructive ?? false,\n },\n },\n async (args: Record<string, unknown>) => {\n try {\n const result = await runtime.registry.call(tool.name, args, runtime.ctx);\n return { content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }] };\n } catch (err) {\n const payload =\n err instanceof AdportError\n ? err.toJSON()\n : { error: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(payload, null, 2) }],\n isError: true,\n };\n }\n },\n );\n }\n return server;\n}\n\nexport async function runStdioServer(runtime: AdportRuntime, version?: string): Promise<void> {\n const server = createMcpServer({ runtime, version });\n await server.connect(new StdioServerTransport());\n // stdout is the protocol channel; stderr is for humans.\n console.error(`adport MCP server on stdio (${runtime.registry.list().length} tools, policy: ${runtime.policySource})`);\n if (runtime.ctx.providers.list().length === 0) {\n console.error('No ad providers connected. Run `adport connect <provider>` or restart with `--demo` for synthetic mock data.');\n }\n}\n","{\n \"name\": \"@adport/mcp\",\n \"version\": \"0.5.2\",\n \"description\": \"adport MCP server — the open control plane for paid media\",\n \"license\": \"Apache-2.0\",\n \"type\": \"module\",\n \"main\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n }\n },\n \"bin\": {\n \"adport-mcp\": \"./dist/bin.js\"\n },\n \"files\": [\"dist\"],\n \"scripts\": {\n \"build\": \"tsup src/index.ts src/bin.ts --format esm --dts --sourcemap --clean\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc --noEmit\",\n \"clean\": \"rm -rf dist\"\n },\n \"dependencies\": {\n \"@adport/core\": \"workspace:*\",\n \"@adport/provider-apple\": \"workspace:*\",\n \"@adport/provider-google\": \"workspace:*\",\n \"@adport/provider-meta\": \"workspace:*\",\n \"@adport/provider-microsoft\": \"workspace:*\",\n \"@adport/provider-reddit\": \"workspace:*\",\n \"@adport/provider-tiktok\": \"workspace:*\",\n \"@modelcontextprotocol/sdk\": \"^1.12.0\",\n \"zod\": \"^4.4.3\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^26.1.2\",\n \"tsup\": \"^8.3.0\",\n \"typescript\": \"^5.8.0\",\n \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