sceneview-mcp 4.0.15 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,915 @@
1
+ /**
2
+ * MCP Apps widget registry — the SceneView 3D viewer served inline by hosts
3
+ * such as ChatGPT (Apps SDK / Plugins Directory), Claude, and any MCP Apps
4
+ * aware client.
5
+ *
6
+ * The wire contract (MCP Apps extension, `io.modelcontextprotocol/ui`):
7
+ *
8
+ * 1. The widget HTML is an MCP resource with a `ui://` URI
9
+ * (`ui://widget/3d-viewer.html`) and the mime type
10
+ * `text/html;profile=mcp-app`. Hosts fetch it via `resources/read` when
11
+ * a tool declaration or result points at it.
12
+ * 2. The tool (`view_3d_model`, see `tools/definitions.ts`) carries
13
+ * `_meta.ui.resourceUri` on its DECLARATION so the host can prefetch the
14
+ * widget from `tools/list` alone, and again on the RESULT next to a
15
+ * `structuredContent` payload the widget renders.
16
+ * 3. Inside the sandboxed iframe the widget reads the payload from the MCP
17
+ * Apps bridge (`ui/notifications/tool-result` over `postMessage`), falls
18
+ * back to ChatGPT's `window.openai.toolOutput` / legacy
19
+ * `window.openai.structuredContent`, and finally to query-string
20
+ * parameters so the page can be opened directly for a manual preview.
21
+ *
22
+ * The renderer is **SceneView.js + Filament.js**, the same WebGL2/WASM stack
23
+ * that powers `sceneview-web` and the sceneview.github.io playground. Using a
24
+ * generic third-party viewer here would defeat the purpose of a SceneView
25
+ * listing, so the script tags are pinned to the released SDK version.
26
+ *
27
+ * This file used to live in the hosted gateway (`mcp-gateway/src/mcp/widgets.ts`,
28
+ * deleted 2026-08-31). It now ships inside the npm package so the stdio server
29
+ * and the Streamable HTTP server (`http.ts`) serve the exact same widget.
30
+ */
31
+ import { LATEST_SCENEVIEW_RELEASE, PACKAGE_VERSION } from "./generated/version.js";
32
+ /** Canonical MCP Apps mime type for widget resources. */
33
+ export const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";
34
+ /**
35
+ * Extension identifier under which MCP Apps is negotiated (SEP-1724, `ext-apps`
36
+ * spec 2026-01-26).
37
+ *
38
+ * MCP Apps is an *extension*, not core protocol: a party that never names it in
39
+ * `capabilities.extensions` has, as far as the other side can tell, no widget
40
+ * support at all. Declaring the widget resource and hanging `_meta.ui` off tool
41
+ * declarations is necessary but not sufficient — the extension has to be
42
+ * advertised, or a spec-following host has no reason to look for either (#3192).
43
+ */
44
+ export const UI_EXTENSION_ID = "io.modelcontextprotocol/ui";
45
+ /**
46
+ * The settings SceneView advertises under
47
+ * `capabilities.extensions["io.modelcontextprotocol/ui"]`.
48
+ *
49
+ * A fresh object every call: the value is spread into handshake results that
50
+ * callers are free to mutate, and a shared array would let one of them corrupt
51
+ * every later handshake.
52
+ */
53
+ export function uiExtensionSettings() {
54
+ return { mimeTypes: [MCP_APP_MIME_TYPE] };
55
+ }
56
+ /**
57
+ * Reads the peer's MCP Apps settings out of a `capabilities` object, or `null`
58
+ * when it declared none.
59
+ *
60
+ * `null` means "did not say", NOT "does not support": hosts predating the
61
+ * extension framework (ChatGPT today, which drives the widget off the
62
+ * `openai/*` `_meta` keys) declare nothing and still render widgets. Callers
63
+ * must treat `null` as unknown and keep their pre-extension behaviour — see
64
+ * `serveWidgetsTo`.
65
+ */
66
+ export function readUiExtension(capabilities) {
67
+ if (!capabilities || typeof capabilities !== "object")
68
+ return null;
69
+ const extensions = capabilities.extensions;
70
+ if (!extensions || typeof extensions !== "object")
71
+ return null;
72
+ const settings = extensions[UI_EXTENSION_ID];
73
+ if (!settings || typeof settings !== "object")
74
+ return null;
75
+ const mimeTypes = settings.mimeTypes;
76
+ return {
77
+ mimeTypes: Array.isArray(mimeTypes) ? mimeTypes.filter((m) => typeof m === "string") : [],
78
+ };
79
+ }
80
+ /**
81
+ * Whether to attach widget pointers for a peer that declared `settings`.
82
+ *
83
+ * The spec asks servers to check client capabilities before advertising
84
+ * UI-enabled tools and to degrade to text otherwise. The only case that
85
+ * degrades here is the one the client stated itself: it negotiated MCP Apps
86
+ * *and* listed mime types that exclude ours. Silence stays permissive, because
87
+ * the live ChatGPT listing is silent and withholding the pointer from it would
88
+ * turn a spec conformance fix into an outage.
89
+ *
90
+ * An explicit `mimeTypes: []` counts as silence, deliberately (#3485): the
91
+ * spec makes `mimeTypes` REQUIRED, so an empty one is a malformed declaration
92
+ * rather than a stated refusal, and reading a malformed declaration as "render
93
+ * nothing" would dark-ship the widget on a client bug. Pinned by a test in
94
+ * `widgets.test.ts` so the choice cannot drift silently.
95
+ */
96
+ export function serveWidgetsTo(settings) {
97
+ if (!settings)
98
+ return true;
99
+ if (settings.mimeTypes.length === 0)
100
+ return true;
101
+ return settings.mimeTypes.includes(MCP_APP_MIME_TYPE);
102
+ }
103
+ /** Resource URI of the 3D viewer widget (`ui://widget/<name>.html` convention). */
104
+ export const WIDGET_3D_VIEWER_URI = "ui://widget/3d-viewer.html";
105
+ /**
106
+ * MCP Apps `_meta.ui` block attached to the widget resource. `csp` is what the
107
+ * host uses to build the iframe's Content-Security-Policy:
108
+ *
109
+ * - `resourceDomains` — where `<script>`, styles, fonts and images may load
110
+ * from (SceneView.js, Filament.js and the neutral IBL all live on
111
+ * sceneview.github.io).
112
+ * - `connectDomains` — where `fetch`/XHR may go: the model URLs users are
113
+ * most likely to pass (SceneView sample assets, raw GitHub, model-viewer's
114
+ * public GLBs, Sketchfab downloads, jsDelivr) plus the AR camera API.
115
+ */
116
+ export const WIDGET_UI_META = {
117
+ prefersBorder: true,
118
+ csp: {
119
+ resourceDomains: ["https://sceneview.github.io"],
120
+ connectDomains: [
121
+ "https://sceneview.github.io",
122
+ "https://raw.githubusercontent.com",
123
+ "https://modelviewer.dev",
124
+ "https://media.sketchfab.com",
125
+ "https://cdn.jsdelivr.net",
126
+ "https://arcamera-api.mcp-tools-lab.workers.dev",
127
+ ],
128
+ },
129
+ };
130
+ /**
131
+ * Full `_meta` for the widget resource: the MCP Apps `ui` block plus the
132
+ * OpenAI Apps SDK spellings of the same two facts, for hosts that still read
133
+ * the legacy keys. Both describe one policy, so they are derived from
134
+ * `WIDGET_UI_META` rather than written twice.
135
+ */
136
+ export const WIDGET_RESOURCE_META = {
137
+ ui: WIDGET_UI_META,
138
+ "openai/widgetPrefersBorder": WIDGET_UI_META.prefersBorder,
139
+ "openai/widgetCSP": {
140
+ resource_domains: WIDGET_UI_META.csp.resourceDomains,
141
+ connect_domains: WIDGET_UI_META.csp.connectDomains,
142
+ },
143
+ };
144
+ const CDN_BASE = "https://sceneview.github.io";
145
+ const FILAMENT_JS_URL = `${CDN_BASE}/js/filament/filament.js?v=${LATEST_SCENEVIEW_RELEASE}`;
146
+ const SCENEVIEW_JS_URL = `${CDN_BASE}/js/sceneview.js?v=${LATEST_SCENEVIEW_RELEASE}`;
147
+ /**
148
+ * The compiled SceneView KMP core, loaded by the widget ONLY to convert a `.3mf` to GLB
149
+ * (`sceneview.threeMfToGlb`) — never to render, which stays `sceneview.js` + the site's own
150
+ * Filament build. Fetched lazily, so a GLB preview never pays for it (#3482).
151
+ */
152
+ const SCENEVIEW_WEB_URL = `${CDN_BASE}/js/sceneview-web.js?v=${LATEST_SCENEVIEW_RELEASE}`;
153
+ const NEUTRAL_IBL_URL = `${CDN_BASE}/environments/neutral_ibl.ktx`;
154
+ /**
155
+ * qrcode-generator 1.4.4 (MIT, © 2009 Kazuhiko Arase), the copy SceneView already vendors for
156
+ * the website's scan-to-open QR (`website-static/js/qrcode-vendor.js`). Served from the same
157
+ * origin as every other widget script, so the CSP needs no new domain, and fetched lazily on a
158
+ * desktop-sized viewport only: a phone never downloads it. The QR is drawn in the browser —
159
+ * no QR image service ever sees the link.
160
+ */
161
+ const QRCODE_JS_URL = `${CDN_BASE}/js/qrcode-vendor.js?v=${LATEST_SCENEVIEW_RELEASE}`;
162
+ /**
163
+ * AR Model Viewer's universal link for a remote model (`ar.sceneview.dev/open?url=`). A phone
164
+ * with the app opens the model in AR; anything else gets a SceneView-rendered page with the
165
+ * store badges (and a QR on desktop). The worker reads only `url`, `unit` and `name` and ignores
166
+ * any other parameter, which is what makes the `utm_source` tag below harmless.
167
+ */
168
+ export const AR_OPEN_URL = "https://ar.sceneview.dev/open";
169
+ /**
170
+ * The widget's link builder, as JavaScript source. It is interpolated verbatim into the widget
171
+ * script AND evaluated by `widgets.test.ts`, so the tests exercise the exact code the host runs
172
+ * (the widget is plain browser JS, not a module the tests could import).
173
+ *
174
+ * `null` — no AR action — for anything the phone could not fetch: `http:`, `data:` and `blob:`
175
+ * URLs (a `blob:` exists only inside this iframe), unparsable strings, and URLs longer than the
176
+ * 1024 characters the `/open` route accepts.
177
+ */
178
+ export const OPEN_IN_AR_JS = `function openInArUrl(modelUrl, source) {
179
+ if (typeof modelUrl !== "string" || modelUrl.length > 1024) return null;
180
+ var parsed;
181
+ try { parsed = new URL(modelUrl); } catch (e) { return null; }
182
+ if (parsed.protocol !== "https:") return null;
183
+ return "${AR_OPEN_URL}?url=" + encodeURIComponent(modelUrl) +
184
+ "&utm_source=" + encodeURIComponent(source);
185
+ }`;
186
+ /**
187
+ * The 3D model viewer widget served at `ui://widget/3d-viewer.html`.
188
+ *
189
+ * Reads a `structuredContent` payload of shape
190
+ * { modelUrl: string, title?: string, autoRotate?: boolean, ar?: boolean,
191
+ * alt?: string, posterUrl?: string }
192
+ * from, in order: the MCP Apps bridge, `window.openai.toolOutput`,
193
+ * `window.openai.structuredContent`, then the query string.
194
+ *
195
+ * With no `modelUrl` from any source the widget shows a placeholder with the
196
+ * SceneView mark, so it never renders as an empty box.
197
+ */
198
+ export const WIDGET_3D_VIEWER_HTML = `<!DOCTYPE html>
199
+ <html lang="en">
200
+ <head>
201
+ <meta charset="UTF-8" />
202
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
203
+ <title>SceneView 3D Viewer</title>
204
+ <style>
205
+ /* Colour tokens from DESIGN.md, light first. The host picks the theme
206
+ (MCP Apps \`hostContext.theme\`, ChatGPT \`window.openai.theme\`) and
207
+ the script mirrors it onto <html data-theme>; without one the OS
208
+ preference applies. The 3D stage stays dark in both themes — DESIGN.md
209
+ \`stage-background-embedded\` — so everything drawn over it (loader,
210
+ placeholder, the AR action) is styled for a dark ground. */
211
+ :root {
212
+ color-scheme: light;
213
+ --sv-surface: #ffffff;
214
+ --sv-on-surface: #1a1a2e;
215
+ --sv-on-surface-dim: #3d4654;
216
+ --sv-on-surface-faint: #5c6370;
217
+ --sv-outline-subtle: #ebedf0;
218
+ --sv-chip: #f1f3f5;
219
+ --sv-link: #005bc1;
220
+ --sv-primary: #005bc1;
221
+ --sv-primary-hover: #0050aa;
222
+ --sv-on-primary: #ffffff;
223
+ --sv-card: #ffffff;
224
+ --sv-stage: #0b0f16;
225
+ }
226
+ @media (prefers-color-scheme: dark) {
227
+ :root:not([data-theme="light"]) {
228
+ color-scheme: dark;
229
+ --sv-surface: #0d1117;
230
+ --sv-on-surface: #f3f4f6;
231
+ --sv-on-surface-dim: #a4abb7;
232
+ --sv-on-surface-faint: #6b7280;
233
+ --sv-outline-subtle: #21262d;
234
+ --sv-chip: #21262d;
235
+ --sv-link: #a4c1ff;
236
+ --sv-primary: #a4c1ff;
237
+ --sv-primary-hover: #b8d0ff;
238
+ --sv-on-primary: #0d1117;
239
+ --sv-card: #232a39;
240
+ --sv-stage: linear-gradient(180deg, #0d1117 0%, #161b22 100%);
241
+ }
242
+ }
243
+ :root[data-theme="dark"] {
244
+ color-scheme: dark;
245
+ --sv-surface: #0d1117;
246
+ --sv-on-surface: #f3f4f6;
247
+ --sv-on-surface-dim: #a4abb7;
248
+ --sv-on-surface-faint: #6b7280;
249
+ --sv-outline-subtle: #21262d;
250
+ --sv-chip: #21262d;
251
+ --sv-link: #a4c1ff;
252
+ --sv-primary: #a4c1ff;
253
+ --sv-primary-hover: #b8d0ff;
254
+ --sv-on-primary: #0d1117;
255
+ --sv-card: #232a39;
256
+ --sv-stage: linear-gradient(180deg, #0d1117 0%, #161b22 100%);
257
+ }
258
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
259
+ html, body { height: 100%; }
260
+ body {
261
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
262
+ background: var(--sv-surface);
263
+ color: var(--sv-on-surface);
264
+ overflow: hidden;
265
+ }
266
+ #stage {
267
+ width: 100%;
268
+ height: 100vh;
269
+ min-height: 400px;
270
+ display: flex;
271
+ flex-direction: column;
272
+ background: var(--sv-surface);
273
+ }
274
+ #header {
275
+ flex: 0 0 auto;
276
+ padding: 12px 16px 8px;
277
+ display: flex;
278
+ align-items: center;
279
+ gap: 8px;
280
+ border-bottom: 1px solid var(--sv-outline-subtle);
281
+ }
282
+ #header strong { font-size: 0.95rem; font-weight: 600; }
283
+ #brand {
284
+ font-size: 0.75rem;
285
+ color: var(--sv-on-surface-dim);
286
+ margin-left: auto;
287
+ white-space: nowrap;
288
+ }
289
+ #brand a { color: var(--sv-link); text-decoration: none; }
290
+ #canvas-wrap {
291
+ flex: 1 1 auto;
292
+ position: relative;
293
+ width: 100%;
294
+ min-height: 0;
295
+ background: var(--sv-stage);
296
+ }
297
+ #canvas {
298
+ display: block;
299
+ width: 100%;
300
+ height: 100%;
301
+ background: transparent;
302
+ transition: opacity 0.4s ease;
303
+ }
304
+ #placeholder, #loader, #error {
305
+ position: absolute;
306
+ inset: 0;
307
+ display: flex;
308
+ align-items: center;
309
+ justify-content: center;
310
+ flex-direction: column;
311
+ gap: 12px;
312
+ padding: 40px 24px;
313
+ text-align: center;
314
+ color: #a4abb7;
315
+ pointer-events: none;
316
+ background: var(--sv-stage);
317
+ }
318
+ [hidden] { display: none !important; }
319
+ #loader .spinner {
320
+ width: 28px;
321
+ height: 28px;
322
+ border: 3px solid #30363d;
323
+ border-top-color: #a4c1ff;
324
+ border-radius: 50%;
325
+ animation: spin 0.8s linear infinite;
326
+ }
327
+ @keyframes spin { to { transform: rotate(360deg); } }
328
+ #error { color: #ffb4ab; }
329
+ #placeholder svg { opacity: 0.5; }
330
+ #footer {
331
+ flex: 0 0 auto;
332
+ padding: 6px 16px;
333
+ font-size: 0.7rem;
334
+ color: var(--sv-on-surface-faint);
335
+ border-top: 1px solid var(--sv-outline-subtle);
336
+ display: flex;
337
+ gap: 12px;
338
+ }
339
+ .pill {
340
+ background: var(--sv-chip);
341
+ color: var(--sv-on-surface-dim);
342
+ padding: 2px 8px;
343
+ border-radius: 4px;
344
+ font-size: 0.7rem;
345
+ }
346
+
347
+ /* ── Open in AR ──────────────────────────────────────────────────────
348
+ A phone gets one pill button. A desktop-sized viewport (\`.wide\`)
349
+ also gets a QR code of the same link, because AR happens on the
350
+ phone in a pocket, not on the monitor. */
351
+ #ar {
352
+ position: absolute;
353
+ left: 12px;
354
+ right: 12px;
355
+ bottom: 12px;
356
+ z-index: 1;
357
+ display: flex;
358
+ justify-content: center;
359
+ pointer-events: none;
360
+ }
361
+ #ar-card { pointer-events: auto; display: flex; align-items: center; gap: 12px; }
362
+ #ar-open {
363
+ display: inline-flex;
364
+ align-items: center;
365
+ justify-content: center;
366
+ gap: 8px;
367
+ min-height: 44px;
368
+ padding: 10px 20px;
369
+ border-radius: 9999px;
370
+ background: var(--sv-primary);
371
+ color: var(--sv-on-primary);
372
+ font-family: inherit;
373
+ font-size: 0.875rem;
374
+ font-weight: 600;
375
+ line-height: 1.2;
376
+ text-decoration: none;
377
+ white-space: nowrap;
378
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);
379
+ transition: transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), background-color 0.15s ease;
380
+ }
381
+ #ar-open:hover { background: var(--sv-primary-hover); }
382
+ #ar-open:active { transform: scale(0.97); }
383
+ #ar-open:focus-visible { outline: 2px solid #ffffff; outline-offset: 3px; }
384
+ #ar-open svg { flex: 0 0 auto; }
385
+ #ar .long, #ar-qr, #ar-scan { display: none; }
386
+ #ar.wide .long { display: inline; }
387
+ #ar.wide.has-qr { justify-content: flex-end; }
388
+ #ar.wide.has-qr #ar-card {
389
+ padding: 12px;
390
+ border-radius: 16px;
391
+ background: var(--sv-card);
392
+ color: var(--sv-on-surface);
393
+ box-shadow: 0 4px 16px rgba(0, 0, 0, 0.35);
394
+ }
395
+ #ar.wide.has-qr #ar-qr {
396
+ display: block;
397
+ width: 104px;
398
+ height: 104px;
399
+ padding: 6px;
400
+ border-radius: 8px;
401
+ background: #ffffff;
402
+ }
403
+ #ar-qr svg { display: block; width: 100%; height: 100%; shape-rendering: crispEdges; }
404
+ #ar.wide.has-qr #ar-scan { display: flex; flex-direction: column; gap: 4px; }
405
+ #ar-copy { display: flex; flex-direction: column; align-items: flex-start; gap: 10px; }
406
+ #ar-scan strong { font-size: 0.875rem; font-weight: 600; }
407
+ #ar-scan span { font-size: 0.75rem; color: var(--sv-on-surface-dim); }
408
+ #ar.wide.has-qr #ar-open { min-height: 36px; padding: 8px 14px; font-size: 0.8rem; box-shadow: none; }
409
+ </style>
410
+ <script src="${FILAMENT_JS_URL}"></script>
411
+ <script src="${SCENEVIEW_JS_URL}"></script>
412
+ </head>
413
+ <body>
414
+ <div id="stage">
415
+ <div id="header">
416
+ <strong id="title">SceneView 3D Viewer</strong>
417
+ <span id="brand">Powered by <a href="https://sceneview.github.io" target="_blank" rel="noopener">SceneView</a></span>
418
+ </div>
419
+ <div id="canvas-wrap">
420
+ <canvas id="canvas" style="opacity:0" role="img" aria-label="3D model"></canvas>
421
+ <div id="loader"><div class="spinner"></div><div>Loading SceneView renderer…</div></div>
422
+ <div id="placeholder" hidden>
423
+ <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
424
+ <path d="M12 2 4 6v12l8 4 8-4V6l-8-4Z"/>
425
+ <path d="m4 6 8 4 8-4"/>
426
+ <path d="M12 22V10"/>
427
+ </svg>
428
+ <div>No 3D model URL provided</div>
429
+ <div style="font-size:0.8rem">Pass <code style="background:#21262d;padding:2px 6px;border-radius:3px">modelUrl</code> in structuredContent or as a query parameter.</div>
430
+ </div>
431
+ <div id="error" hidden>
432
+ <div>Could not load model</div>
433
+ <div id="error-detail" style="font-size:0.75rem;color:#a4abb7"></div>
434
+ </div>
435
+ <div id="ar" hidden>
436
+ <div id="ar-card">
437
+ <div id="ar-qr" role="img" aria-label="QR code: scan with your phone to open this model in AR"></div>
438
+ <div id="ar-copy">
439
+ <div id="ar-scan"><strong>See it in your room</strong><span>Scan with your phone's camera</span></div>
440
+ <a id="ar-open" href="${AR_OPEN_URL}" target="_blank" rel="noopener">
441
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
442
+ <path d="M3 7V5a2 2 0 0 1 2-2h2M17 3h2a2 2 0 0 1 2 2v2M21 17v2a2 2 0 0 1-2 2h-2M7 21H5a2 2 0 0 1-2-2v-2"/>
443
+ <path d="m12 7 4.5 2.5v5L12 17l-4.5-2.5v-5L12 7Z"/>
444
+ <path d="m7.5 9.5 4.5 2.5 4.5-2.5M12 12v5"/>
445
+ </svg>
446
+ <span>Open in AR<span class="long"> on your phone</span></span>
447
+ </a>
448
+ </div>
449
+ </div>
450
+ </div>
451
+ </div>
452
+ <div id="footer">
453
+ <span class="pill" id="format">GLB</span>
454
+ <span class="pill" id="engine">Filament.js · WebGL2 · WASM</span>
455
+ <span style="margin-left:auto" id="hint">Drag to orbit · Scroll to zoom</span>
456
+ </div>
457
+ </div>
458
+ <script>
459
+ (function () {
460
+ var WIDGET_VERSION = "${PACKAGE_VERSION}";
461
+ var IBL_URL = "${NEUTRAL_IBL_URL}";
462
+ // The 3MF converter (#3482), fetched only when a payload needs it.
463
+ var CONVERTER_URL = "${SCENEVIEW_WEB_URL}";
464
+
465
+ var titleEl = document.getElementById("title");
466
+ var loader = document.getElementById("loader");
467
+ var canvas = document.getElementById("canvas");
468
+ var placeholder = document.getElementById("placeholder");
469
+ var errorEl = document.getElementById("error");
470
+ var errorDetail = document.getElementById("error-detail");
471
+ var formatEl = document.getElementById("format");
472
+
473
+ // What is on screen right now, and the payload waiting for the renderer.
474
+ var rendered = null;
475
+ var pending = null;
476
+ var viewer = null;
477
+
478
+ // ── Payload sources, in priority order ───────────────────────────────
479
+ //
480
+ // 1. MCP Apps bridge: the host posts JSON-RPC over postMessage. The
481
+ // tool result arrives as \`ui/notifications/tool-result\` carrying the
482
+ // same \`structuredContent\` the tool returned.
483
+ // 2. ChatGPT Apps SDK: \`window.openai.toolOutput\` (current) and
484
+ // \`window.openai.structuredContent\` (legacy, pre-MCP-Apps hosts).
485
+ // 3. Query string (\`?modelUrl=…\`) for direct preview outside any host.
486
+
487
+ function normalise(sc) {
488
+ if (!sc || typeof sc !== "object") return null;
489
+ if (typeof sc.modelUrl !== "string" || !sc.modelUrl) return null;
490
+ return sc;
491
+ }
492
+
493
+ function post(message) {
494
+ try { window.parent.postMessage(message, "*"); } catch (e) { /* no host */ }
495
+ }
496
+
497
+ var INIT_ID = 1;
498
+ // Requests this widget sent to the host after the handshake, by id.
499
+ var nextRequestId = INIT_ID + 1;
500
+ var awaiting = {};
501
+ // What the host said about itself in the \`ui/initialize\` result:
502
+ // null until it answers, which also means "not an MCP Apps host yet".
503
+ var hostCapabilities = null;
504
+
505
+ function request(method, params, onDone) {
506
+ var id = nextRequestId++;
507
+ awaiting[id] = onDone;
508
+ post({ jsonrpc: "2.0", id: id, method: method, params: params });
509
+ }
510
+
511
+ window.addEventListener("message", function (event) {
512
+ var msg = event.data;
513
+ if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0") return;
514
+ if (msg.method === "ui/notifications/tool-result" && msg.params) {
515
+ var data = normalise(msg.params.structuredContent);
516
+ if (data) render(data);
517
+ return;
518
+ }
519
+ if (msg.method === "ui/notifications/host-context-changed" && msg.params) {
520
+ applyTheme(msg.params.theme);
521
+ return;
522
+ }
523
+ if (msg.id === INIT_ID && (msg.result || msg.error)) {
524
+ var init = msg.result;
525
+ if (init && typeof init === "object") {
526
+ var caps = init.hostCapabilities;
527
+ hostCapabilities = caps && typeof caps === "object" ? caps : {};
528
+ applyTheme(init.hostContext && init.hostContext.theme);
529
+ }
530
+ post({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
531
+ return;
532
+ }
533
+ if (typeof msg.id === "number" && awaiting[msg.id]) {
534
+ var done = awaiting[msg.id];
535
+ delete awaiting[msg.id];
536
+ done(!msg.error && !(msg.result && msg.result.isError));
537
+ }
538
+ });
539
+ if (window.parent && window.parent !== window) {
540
+ post({
541
+ jsonrpc: "2.0",
542
+ id: INIT_ID,
543
+ method: "ui/initialize",
544
+ params: {
545
+ protocolVersion: "2026-01-26",
546
+ appInfo: { name: "sceneview-3d-viewer", version: WIDGET_VERSION },
547
+ appCapabilities: {},
548
+ },
549
+ });
550
+ }
551
+
552
+ function fromOpenAI() {
553
+ try {
554
+ var o = window.openai;
555
+ if (!o) return null;
556
+ return normalise(o.toolOutput) || normalise(o.structuredContent) || null;
557
+ } catch (e) { return null; }
558
+ }
559
+ window.addEventListener("openai:set_globals", function () {
560
+ var data = fromOpenAI();
561
+ if (data) render(data);
562
+ applyTheme(window.openai && window.openai.theme);
563
+ });
564
+
565
+ function fromQuery() {
566
+ var p = new URLSearchParams(location.search);
567
+ var modelUrl = p.get("modelUrl") || p.get("src");
568
+ if (!modelUrl) return null;
569
+ return {
570
+ modelUrl: modelUrl,
571
+ title: p.get("title") || undefined,
572
+ autoRotate: p.get("autoRotate") !== "false",
573
+ alt: p.get("alt") || undefined,
574
+ };
575
+ }
576
+
577
+ // ── UI helpers ───────────────────────────────────────────────────────
578
+
579
+ // Trim, cap length, and de-dupe accidental repetition like
580
+ // "Ferrari F40Ferrari F40" caused by stacked navigations during preview.
581
+ function cleanTitle(raw) {
582
+ if (!raw) return "";
583
+ var s = String(raw).trim();
584
+ if (s.length > 60) s = s.slice(0, 60);
585
+ var half = Math.floor(s.length / 2);
586
+ if (half > 0 && s.slice(0, half) === s.slice(half, half * 2)) {
587
+ s = s.slice(0, half).trim();
588
+ }
589
+ return s;
590
+ }
591
+
592
+ // The host's theme wins over the OS preference; anything but the two
593
+ // known values leaves the CSS \`prefers-color-scheme\` fallback in charge.
594
+ function applyTheme(theme) {
595
+ if (theme === "light" || theme === "dark") {
596
+ document.documentElement.setAttribute("data-theme", theme);
597
+ }
598
+ }
599
+ try { applyTheme(window.openai && window.openai.theme); } catch (e) { /* no host */ }
600
+
601
+ // ── Open in AR ───────────────────────────────────────────────────────
602
+ //
603
+ // One link, three ways to follow it, in order: ChatGPT's
604
+ // \`openai.openExternal\`, the MCP Apps \`ui/open-link\` request, and
605
+ // the anchor's own \`target="_blank"\` for any other host. A desktop-sized
606
+ // viewport also gets a QR code of the same link.
607
+
608
+ var QRCODE_JS_URL = "${QRCODE_JS_URL}";
609
+ var arEl = document.getElementById("ar");
610
+ var arOpen = document.getElementById("ar-open");
611
+ var arQr = document.getElementById("ar-qr");
612
+ var arLink = null;
613
+ var wideQuery = window.matchMedia
614
+ ? window.matchMedia("(min-width: 600px) and (hover: hover) and (pointer: fine)")
615
+ : null;
616
+
617
+ ${OPEN_IN_AR_JS}
618
+
619
+ // Which assistant sent the visitor, for the store's acquisition report.
620
+ function linkSource() {
621
+ return window.openai ? "chatgpt" : "claude";
622
+ }
623
+
624
+ function updateArAction(data) {
625
+ arLink = data.ar === false ? null : openInArUrl(data.modelUrl, linkSource());
626
+ arEl.classList.remove("has-qr");
627
+ arQr.textContent = "";
628
+ if (!arLink) { arEl.hidden = true; return; }
629
+ arOpen.href = arLink;
630
+ arEl.hidden = false;
631
+ updateLayout();
632
+ }
633
+
634
+ function updateLayout() {
635
+ var wide = !!(wideQuery && wideQuery.matches);
636
+ arEl.classList.toggle("wide", wide);
637
+ if (wide && arLink && !arEl.classList.contains("has-qr")) drawQr(arLink);
638
+ }
639
+ if (wideQuery) {
640
+ if (wideQuery.addEventListener) wideQuery.addEventListener("change", updateLayout);
641
+ else if (wideQuery.addListener) wideQuery.addListener(updateLayout);
642
+ }
643
+
644
+ var qrScriptPromise = null;
645
+ function loadQrEncoder() {
646
+ if (!qrScriptPromise) {
647
+ qrScriptPromise = new Promise(function (resolve, reject) {
648
+ var el = document.createElement("script");
649
+ el.src = QRCODE_JS_URL;
650
+ el.onload = function () { resolve(); };
651
+ el.onerror = function () { reject(new Error("could not load the QR encoder")); };
652
+ document.head.appendChild(el);
653
+ });
654
+ }
655
+ return qrScriptPromise;
656
+ }
657
+
658
+ // A failure leaves the button on its own, which still works.
659
+ function drawQr(link) {
660
+ loadQrEncoder().then(function () {
661
+ if (link !== arLink || typeof window.qrcode !== "function") return;
662
+ var qr = window.qrcode(0, "M");
663
+ qr.addData(link);
664
+ qr.make();
665
+ arQr.innerHTML = qr.createSvgTag({ scalable: true, margin: 0 });
666
+ arEl.classList.add("has-qr");
667
+ }).catch(function () { /* button only */ });
668
+ }
669
+
670
+ arOpen.addEventListener("click", function (event) {
671
+ if (!arLink) { event.preventDefault(); return; }
672
+ var link = arLink;
673
+ var openai = window.openai;
674
+ if (openai && typeof openai.openExternal === "function") {
675
+ event.preventDefault();
676
+ try { openai.openExternal({ href: link }); } catch (e) { window.open(link, "_blank", "noopener"); }
677
+ return;
678
+ }
679
+ // An MCP Apps host that answered the handshake. \`openLinks\` is asked
680
+ // for even when the host did not declare it — an undeclared but
681
+ // working \`ui/open-link\` beats an anchor the iframe sandbox may block
682
+ // — and a refusal falls back to a plain new window. Only a host that
683
+ // explicitly set it falsy is left to the anchor.
684
+ if (hostCapabilities && (!("openLinks" in hostCapabilities) || hostCapabilities.openLinks)) {
685
+ event.preventDefault();
686
+ request("ui/open-link", { url: link }, function (ok) {
687
+ if (!ok) window.open(link, "_blank", "noopener");
688
+ });
689
+ }
690
+ // Otherwise the anchor itself opens the link in a new tab.
691
+ });
692
+
693
+ function showError(msg) {
694
+ loader.hidden = true;
695
+ placeholder.hidden = true;
696
+ canvas.style.opacity = "0";
697
+ errorDetail.textContent = msg;
698
+ errorEl.hidden = false;
699
+ }
700
+
701
+ function showPlaceholder() {
702
+ loader.hidden = true;
703
+ errorEl.hidden = true;
704
+ canvas.style.opacity = "0";
705
+ placeholder.hidden = false;
706
+ }
707
+
708
+ function notifyReady() {
709
+ try {
710
+ if (window.openai && typeof window.openai.notifyReady === "function") {
711
+ window.openai.notifyReady();
712
+ } else {
713
+ post({ type: "mcp-app/ready" });
714
+ }
715
+ } catch (e) { /* swallow */ }
716
+ }
717
+
718
+ // ── Rendering ────────────────────────────────────────────────────────
719
+
720
+ function render(data) {
721
+ if (rendered && rendered.modelUrl === data.modelUrl) return;
722
+ pending = data;
723
+ placeholder.hidden = true;
724
+ errorEl.hidden = true;
725
+ loader.hidden = false;
726
+ titleEl.textContent = cleanTitle(data.title) || "SceneView 3D Viewer";
727
+ // Before the model loads, and whether or not it does: a file this
728
+ // browser cannot draw may still open in the app.
729
+ updateArAction(data);
730
+ canvas.setAttribute("aria-label", data.alt || data.title || "3D model");
731
+ var ext = (data.modelUrl.split("?")[0].split(".").pop() || "GLB").toUpperCase();
732
+ formatEl.textContent = ext === "GLTF" ? "glTF" : ext;
733
+ whenSceneViewReady(function () { start(data); });
734
+ }
735
+
736
+ // ── 3MF (#3482) ──────────────────────────────────────────────────────
737
+ //
738
+ // ChatGPT emits a \`.3mf\` when it turns a drawing into a printable model.
739
+ // The conversion is NOT reimplemented here: \`sceneview-web.js\` is the
740
+ // compiled SceneView KMP core, the same \`ThreeMfLoader\` Android runs,
741
+ // exposed as \`sceneview.threeMfToGlb(bytes)\`. It is loaded lazily and
742
+ // only for that call, so a GLB preview never downloads it.
743
+
744
+ var threeMfScriptPromise = null;
745
+ function loadThreeMfConverter() {
746
+ if (!threeMfScriptPromise) {
747
+ threeMfScriptPromise = new Promise(function (resolve, reject) {
748
+ var el = document.createElement("script");
749
+ el.src = CONVERTER_URL;
750
+ el.onload = function () { resolve(); };
751
+ el.onerror = function () { reject(new Error("could not load the 3MF converter")); };
752
+ document.head.appendChild(el);
753
+ });
754
+ }
755
+ return threeMfScriptPromise;
756
+ }
757
+
758
+ /** \`PK\\x03\\x04\` — the ZIP magic every 3MF starts with. Four bytes, no parse. */
759
+ function looksLikeZip(buffer) {
760
+ if (!buffer || buffer.byteLength < 4) return false;
761
+ var b = new Uint8Array(buffer, 0, 4);
762
+ return b[0] === 0x50 && b[1] === 0x4b && b[2] === 0x03 && b[3] === 0x04;
763
+ }
764
+
765
+ /**
766
+ * The URL the renderer should load: a \`blob:\` GLB for a 3MF, or the URL
767
+ * unchanged for anything else.
768
+ *
769
+ * Only a \`.3mf\` URL — or one with no recognised model extension, which is
770
+ * what a generated-file link usually looks like — is fetched and sniffed
771
+ * here. A \`.glb\` / \`.gltf\` goes straight through, so the common case
772
+ * still costs exactly one download, and a glTF keeps resolving its own
773
+ * external buffers and textures against its own URL.
774
+ */
775
+ function resolveModelUrl(url) {
776
+ var path = String(url).split("?")[0].split("#")[0].toLowerCase();
777
+ var isThreeMfUrl = /.3mf$/.test(path);
778
+ var isKnownGltf = /.(glb|gltf)$/.test(path);
779
+ if (!isThreeMfUrl && isKnownGltf) return Promise.resolve(url);
780
+
781
+ return fetch(url)
782
+ .then(function (r) {
783
+ if (!r.ok) throw new Error("HTTP " + r.status + " loading the model");
784
+ var type = (r.headers.get("content-type") || "").toLowerCase();
785
+ return r.arrayBuffer().then(function (buffer) {
786
+ return { buffer: buffer, isThreeMfType: type.indexOf("model/3mf") !== -1 };
787
+ });
788
+ })
789
+ .then(function (payload) {
790
+ if (!looksLikeZip(payload.buffer) && !payload.isThreeMfType) return url;
791
+ return loadThreeMfConverter().then(function () {
792
+ if (!window.sceneview || typeof window.sceneview.threeMfToGlb !== "function") {
793
+ throw new Error("the 3MF converter did not load");
794
+ }
795
+ if (!window.sceneview.isThreeMf(payload.buffer)) {
796
+ if (isThreeMfUrl) throw new Error("this file is not a readable 3MF");
797
+ return url;
798
+ }
799
+ var glb = window.sceneview.threeMfToGlb(payload.buffer);
800
+ formatEl.textContent = "3MF";
801
+ return URL.createObjectURL(new Blob([glb], { type: "model/gltf-binary" }));
802
+ });
803
+ });
804
+ }
805
+
806
+ function start(data) {
807
+ if (pending !== data) return; // superseded by a newer payload
808
+ resolveModelUrl(data.modelUrl).then(function (url) {
809
+ if (pending !== data) return; // superseded while the 3MF was converting
810
+ startWith(data, url);
811
+ }).catch(fail);
812
+ }
813
+
814
+ function startWith(data, url) {
815
+ if (viewer && typeof viewer.loadModel === "function") {
816
+ viewer.loadModel(url).then(function () { reveal(data); }).catch(fail);
817
+ return;
818
+ }
819
+ SceneView.modelViewer(canvas, url, {
820
+ backgroundColor: [0, 0, 0, 0],
821
+ // Match the sceneview.github.io playground hero settings.
822
+ lightIntensity: 150000,
823
+ fov: 35,
824
+ // An absolute IBL URL: a relative one resolves against the host's
825
+ // sandbox origin, 404s, and leaves PBR materials almost black.
826
+ iblUrl: IBL_URL,
827
+ }).then(function (v) {
828
+ viewer = v;
829
+ reveal(data);
830
+ }).catch(fail);
831
+ }
832
+
833
+ function reveal(data) {
834
+ rendered = data;
835
+ pending = null;
836
+ loader.hidden = true;
837
+ canvas.style.opacity = "1";
838
+ if (data.autoRotate === false && viewer && viewer.setAutoRotate) {
839
+ viewer.setAutoRotate(false);
840
+ } else if (viewer && viewer.setAutoRotate) {
841
+ viewer.setAutoRotate(true);
842
+ }
843
+ notifyReady();
844
+ }
845
+
846
+ function fail(err) {
847
+ pending = null;
848
+ showError((err && err.message) || String(err));
849
+ }
850
+
851
+ // SceneView.js registers its global after Filament's WASM ready
852
+ // promise, so poll briefly for it before deciding the CDN failed.
853
+ var readyCallbacks = [];
854
+ var polling = false;
855
+ function whenSceneViewReady(cb) {
856
+ if (typeof SceneView !== "undefined" && SceneView.modelViewer) { cb(); return; }
857
+ readyCallbacks.push(cb);
858
+ if (polling) return;
859
+ polling = true;
860
+ var tries = 0;
861
+ var maxTries = 60; // ~6 s at 100 ms intervals
862
+ var timer = setInterval(function () {
863
+ tries++;
864
+ if (typeof SceneView !== "undefined" && SceneView.modelViewer) {
865
+ clearInterval(timer);
866
+ var cbs = readyCallbacks; readyCallbacks = [];
867
+ cbs.forEach(function (fn) { fn(); });
868
+ } else if (tries >= maxTries) {
869
+ clearInterval(timer);
870
+ polling = false;
871
+ readyCallbacks = [];
872
+ showError("Timed out loading SceneView.js + Filament.js from the CDN.");
873
+ }
874
+ }, 100);
875
+ }
876
+
877
+ // ── Boot ─────────────────────────────────────────────────────────────
878
+ var initial = fromOpenAI() || fromQuery();
879
+ if (initial) {
880
+ render(initial);
881
+ } else {
882
+ // Give the MCP Apps bridge a moment to deliver the tool result before
883
+ // declaring that no model was provided.
884
+ setTimeout(function () {
885
+ if (!rendered && !pending) showPlaceholder();
886
+ }, 4000);
887
+ }
888
+ })();
889
+ </script>
890
+ </body>
891
+ </html>`;
892
+ const WIDGETS = {
893
+ [WIDGET_3D_VIEWER_URI]: {
894
+ name: "SceneView 3D Viewer",
895
+ description: "MCP Apps widget: interactive SceneView.js + Filament.js viewer for a GLB / glTF model, rendered inline by the host when `view_3d_model` is called.",
896
+ html: WIDGET_3D_VIEWER_HTML,
897
+ },
898
+ };
899
+ /** Every widget resource, in `resources/list` shape. */
900
+ export function listWidgetResources() {
901
+ return Object.entries(WIDGETS).map(([uri, w]) => ({
902
+ uri,
903
+ name: w.name,
904
+ description: w.description,
905
+ mimeType: MCP_APP_MIME_TYPE,
906
+ _meta: WIDGET_RESOURCE_META,
907
+ }));
908
+ }
909
+ /** Contents for a widget URI in `resources/read` shape, or `null` if unknown. */
910
+ export function readWidgetResource(uri) {
911
+ const w = WIDGETS[uri];
912
+ if (!w)
913
+ return null;
914
+ return { uri, mimeType: MCP_APP_MIME_TYPE, text: w.html, _meta: WIDGET_RESOURCE_META };
915
+ }