@mostra/plugin-mcp-app 0.0.0-stage → 0.17.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.
package/dist/index.js ADDED
@@ -0,0 +1,464 @@
1
+ import { defineExporter } from "@mostra/contract-exporter";
2
+ import { APP_PAGE_MAX_CHARS, MCP_APP_MIME_TYPE, mcpAppUri } from "@mostra/protocol";
3
+ import { rolldown } from "rolldown";
4
+ import { HOST_TOKENS } from "@mostra/themes";
5
+ //#region src/bundle.ts
6
+ /** The media types of the files a page may name, by extension; anything else is octet-stream. */
7
+ const MEDIA_TYPES = {
8
+ ".png": "image/png",
9
+ ".jpg": "image/jpeg",
10
+ ".jpeg": "image/jpeg",
11
+ ".gif": "image/gif",
12
+ ".webp": "image/webp",
13
+ ".avif": "image/avif",
14
+ ".svg": "image/svg+xml",
15
+ ".ico": "image/x-icon",
16
+ ".bmp": "image/bmp",
17
+ ".mp3": "audio/mpeg",
18
+ ".wav": "audio/wav",
19
+ ".ogg": "audio/ogg",
20
+ ".mp4": "video/mp4",
21
+ ".webm": "video/webm",
22
+ ".json": "application/json",
23
+ ".txt": "text/plain",
24
+ ".csv": "text/csv",
25
+ ".css": "text/css",
26
+ ".js": "text/javascript",
27
+ ".wasm": "application/wasm",
28
+ ".woff": "font/woff",
29
+ ".woff2": "font/woff2",
30
+ ".ttf": "font/ttf",
31
+ ".otf": "font/otf"
32
+ };
33
+ /** Font files, which a chat host's default policy never loads (no `font-src`, VERIFIED_FACTS). */
34
+ const FONT_EXTENSIONS = [
35
+ ".woff",
36
+ ".woff2",
37
+ ".ttf",
38
+ ".otf",
39
+ ".eot"
40
+ ];
41
+ /** The extension of a path, lower case, with its dot. */
42
+ function extensionOf(path) {
43
+ const name = path.slice(path.lastIndexOf("/") + 1);
44
+ const dot = name.lastIndexOf(".");
45
+ return dot <= 0 ? "" : name.slice(dot).toLowerCase();
46
+ }
47
+ /** A file as a `data:` URL. */
48
+ function dataUrl(path, bytes) {
49
+ return `data:${MEDIA_TYPES[extensionOf(path)] ?? "application/octet-stream"};base64,${Buffer.from(bytes).toString("base64")}`;
50
+ }
51
+ /** The client build of a version's file tree, by URL path. */
52
+ async function clientFiles(files) {
53
+ const paths = /* @__PURE__ */ new Set();
54
+ for (const path of await files.list()) if (path.startsWith("client/")) paths.add(path.slice(6));
55
+ return {
56
+ paths,
57
+ read: (urlPath) => files.read(`client${urlPath}`)
58
+ };
59
+ }
60
+ /** The characters a quoted URL path may hold, so a replacement never runs into code around it. */
61
+ const QUOTED_PATH = /(["'`])(\/[A-Za-z0-9._~\-/@%+]+)\1/g;
62
+ /**
63
+ * Replaces each quoted URL path of a build file (`"/assets/logo-H.png"`) with its `data:` URL.
64
+ * Only exact quoted paths of files the build holds change, never text that merely contains one.
65
+ */
66
+ async function inlineQuotedPaths(code, client, skip) {
67
+ const found = /* @__PURE__ */ new Map();
68
+ for (const match of code.matchAll(QUOTED_PATH)) {
69
+ const path = match[2];
70
+ if (!client.paths.has(path) || skip(path) || found.has(path)) continue;
71
+ found.set(path, dataUrl(path, await client.read(path)));
72
+ }
73
+ if (found.size === 0) return {
74
+ code,
75
+ inlined: []
76
+ };
77
+ return {
78
+ code: code.replace(QUOTED_PATH, (whole, quote, path) => {
79
+ const url = found.get(path);
80
+ return url === void 0 ? whole : `${quote}${url}${quote}`;
81
+ }),
82
+ inlined: [...found.keys()]
83
+ };
84
+ }
85
+ /** Resolves an import of a build module (`./chunk-H.js`, `/assets/x.js`) to its URL path. */
86
+ function resolveUrlPath(specifier, importer) {
87
+ if (specifier.startsWith("/")) return new URL(specifier, "http://page.invalid").pathname;
88
+ if (specifier.startsWith("./") || specifier.startsWith("../")) return new URL(specifier, `http://page.invalid${importer ?? "/"}`).pathname;
89
+ }
90
+ /** The prefix rolldown sees build modules under, so no path of this machine is ever read. */
91
+ const MODULE_PREFIX = "\0mostra-client:";
92
+ /**
93
+ * Bundles the build's module `entry` (a URL path) and everything it imports into one ES module.
94
+ * Every module comes from the version's file tree: an import outside it (a bare specifier, a URL)
95
+ * throws, since a built page imports only its own chunks.
96
+ */
97
+ async function bundleEntry(entry, client, skipInline) {
98
+ const modules = [];
99
+ const inlined = /* @__PURE__ */ new Set();
100
+ const build = await rolldown({
101
+ input: `${MODULE_PREFIX}${entry}`,
102
+ treeshake: false,
103
+ logLevel: "silent",
104
+ plugins: [{
105
+ name: "mostra-client",
106
+ resolveId(specifier, importer) {
107
+ const from = importer?.startsWith(MODULE_PREFIX) ? importer.slice(15) : void 0;
108
+ const target = specifier.startsWith(MODULE_PREFIX) ? specifier.slice(15) : resolveUrlPath(specifier, from);
109
+ if (target === void 0 || !client.paths.has(target)) throw new Error(`the build's module ${from ?? entry} imports ${JSON.stringify(specifier)}, which isn't a file of the build`);
110
+ return `${MODULE_PREFIX}${target}`;
111
+ },
112
+ async load(id) {
113
+ if (!id.startsWith(MODULE_PREFIX)) return null;
114
+ const path = id.slice(15);
115
+ modules.push(path);
116
+ const done = await inlineQuotedPaths(new TextDecoder().decode(await client.read(path)).replace(/\n\/\/# sourceMappingURL=[^\n]*\s*$/, "\n"), client, (urlPath) => {
117
+ if (skipInline(urlPath)) return true;
118
+ return extensionOf(urlPath) === ".js" || extensionOf(urlPath) === ".map";
119
+ });
120
+ for (const path of done.inlined) inlined.add(path);
121
+ return {
122
+ code: done.code,
123
+ moduleType: "js"
124
+ };
125
+ }
126
+ }]
127
+ });
128
+ try {
129
+ const { output } = await build.generate({
130
+ format: "es",
131
+ codeSplitting: false,
132
+ sourcemap: false,
133
+ comments: { legal: false }
134
+ });
135
+ const chunk = output.find((item) => item.type === "chunk");
136
+ if (chunk?.type !== "chunk") throw new Error("re-bundling produced no module");
137
+ return {
138
+ code: chunk.code,
139
+ modules,
140
+ inlined: [...inlined]
141
+ };
142
+ } finally {
143
+ await build.close();
144
+ }
145
+ }
146
+ //#endregion
147
+ //#region src/page.ts
148
+ /** Escapes text for HTML content and attribute values. */
149
+ function escapeHtml(text) {
150
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
151
+ }
152
+ /**
153
+ * A stylesheet's text inside `<style>`, where `</style` would end it: written `<\/style`, which
154
+ * CSS reads as the same text (`\/` is `/`), in a string, a comment or anywhere else.
155
+ */
156
+ function styleText(css) {
157
+ return css.replace(/<\/(style)/gi, "<\\/$1");
158
+ }
159
+ /**
160
+ * The page's own code, run without its text ever going through the HTML parser (review findings
161
+ * Opus 11, Fable 12): rewriting `<\/script`, `<script` or `<!--` is right in a string and wrong in
162
+ * code (`i<scriptCount`), and only a JavaScript tokenizer could tell them apart. So the module
163
+ * travels as base64, which has no `<`, in an inert element, and {@link MODULE_BOOTSTRAP}, Mostra's
164
+ * own few lines, decodes it and gives it to a module script as its `textContent`: the code runs
165
+ * byte for byte as built. MCP Apps' default policy allows inline scripts (`'unsafe-inline'`).
166
+ */
167
+ const MODULE_BOOTSTRAP = [
168
+ "(function () {",
169
+ " var native = window.fetch;",
170
+ " if (typeof native === \"function\") {",
171
+ " window.fetch = function (input, init) {",
172
+ " var url = typeof input === \"string\" ? input : input && (input.href || input.url);",
173
+ " var comma = typeof url === \"string\" && url.slice(0, 5) === \"data:\" ? url.indexOf(\",\") : -1;",
174
+ " if (comma === -1) return native.apply(this, arguments);",
175
+ " var head = url.slice(5, comma);",
176
+ " var payload = url.slice(comma + 1);",
177
+ " var encoded = /;base64$/i.test(head);",
178
+ " var type = head.replace(/;base64$/i, \"\") || \"text/plain;charset=US-ASCII\";",
179
+ " var data;",
180
+ " if (encoded) {",
181
+ " var raw = atob(payload);",
182
+ " data = new Uint8Array(raw.length);",
183
+ " for (var j = 0; j !== raw.length; j++) data[j] = raw.charCodeAt(j);",
184
+ " } else data = new TextEncoder().encode(decodeURIComponent(payload));",
185
+ " return Promise.resolve(new Response(data, { headers: { \"content-type\": type } }));",
186
+ " };",
187
+ " }",
188
+ " var carrier = document.getElementById(\"mostra-module\");",
189
+ " if (carrier === null) return;",
190
+ " var binary = atob((carrier.textContent || \"\").trim());",
191
+ " var bytes = new Uint8Array(binary.length);",
192
+ " for (var i = 0; i !== binary.length; i++) bytes[i] = binary.charCodeAt(i);",
193
+ " var module = document.createElement(\"script\");",
194
+ " module.type = \"module\";",
195
+ " module.textContent = new TextDecoder().decode(bytes);",
196
+ " document.body.append(module);",
197
+ "})();"
198
+ ].join("\n");
199
+ /** The two elements that carry and run the page's module (see {@link MODULE_BOOTSTRAP}). */
200
+ function moduleElements(code) {
201
+ return [` <script type="application/octet-stream" id="mostra-module">${Buffer.from(code, "utf8").toString("base64")}<\/script>`, ` <script>${MODULE_BOOTSTRAP}<\/script>`].join("\n");
202
+ }
203
+ /** Reads the build's `index.html` (the builder's own, INTERFACES §11). */
204
+ function readBuiltPage(html) {
205
+ const entry = /<script\b[^>]*\btype="module"[^>]*\bsrc="([^"]+)"/i.exec(html)?.[1];
206
+ if (entry === void 0) throw new Error("the build's index.html names no module script");
207
+ return {
208
+ entry,
209
+ stylesheets: [...html.matchAll(/<link\b[^>]*\brel="stylesheet"[^>]*\bhref="([^"]+)"/gi)].map((match) => match[1]),
210
+ lang: /<html\b[^>]*\blang="([^"]*)"/i.exec(html)?.[1] ?? "en"
211
+ };
212
+ }
213
+ /** The URLs a stylesheet names: `url(x)`, `url("x")`, `url('x')`. */
214
+ const CSS_URL = /url\(\s*(["']?)([^"')]+)\1\s*\)/g;
215
+ /**
216
+ * A stylesheet for the page: each file of the build it names as a `data:` URL, its `@font-face`
217
+ * rules for the build's own faces left out (a chat host's policy loads no font, VERIFIED_FACTS,
218
+ * WP-17; the host's faces take their place, D141 item 4), and the absolute `https:` origins it
219
+ * names.
220
+ */
221
+ async function inlineStylesheet(css, client) {
222
+ let fonts = 0;
223
+ const withoutFaces = css.replace(/@font-face\s*\{[^}]*\}/g, (rule) => {
224
+ const named = [...rule.matchAll(CSS_URL)].map((match) => match[2]);
225
+ if (!(named.length > 0 && named.every((url) => client.paths.has(url.split(/[?#]/)[0] ?? url)))) return rule;
226
+ fonts += 1;
227
+ return "";
228
+ });
229
+ const origins = /* @__PURE__ */ new Set();
230
+ const urls = /* @__PURE__ */ new Map();
231
+ for (const match of withoutFaces.matchAll(CSS_URL)) {
232
+ const url = match[2];
233
+ const path = url.split(/[?#]/)[0] ?? url;
234
+ if (client.paths.has(path) && !FONT_EXTENSIONS.includes(extensionOf(path))) {
235
+ if (!urls.has(path)) urls.set(path, dataUrl(path, await client.read(path)));
236
+ continue;
237
+ }
238
+ const origin = httpsOrigin(url);
239
+ if (origin !== void 0) origins.add(origin);
240
+ }
241
+ return {
242
+ css: withoutFaces.replace(CSS_URL, (whole, _quote, url) => {
243
+ const path = url.split(/[?#]/)[0] ?? url;
244
+ const data = urls.get(path);
245
+ return data === void 0 ? whole : `url("${data}")`;
246
+ }),
247
+ origins: [...origins],
248
+ fonts
249
+ };
250
+ }
251
+ /** The origin of an absolute `https:` URL, or `undefined`. */
252
+ function httpsOrigin(url) {
253
+ if (!/^https:\/\//i.test(url)) return void 0;
254
+ try {
255
+ const parsed = new URL(url);
256
+ return parsed.hostname === "" ? void 0 : parsed.origin;
257
+ } catch {
258
+ return;
259
+ }
260
+ }
261
+ /** Absolute `https:` URLs in code. */
262
+ const HTTPS_URL = /https:\/\/[A-Za-z0-9.-]+(?::\d{1,5})?/g;
263
+ /**
264
+ * The `https:` origins the artifact's own code names, from the build's source maps: only the
265
+ * sources the artifact wrote (under its `source/` directory, never a package's), since packages'
266
+ * documentation links (react.dev, json-schema.org) are never fetched. A build without source maps
267
+ * declares every origin its modules name.
268
+ */
269
+ async function ownOrigins(files, modules) {
270
+ const origins = /* @__PURE__ */ new Set();
271
+ const listed = new Set(await files.list());
272
+ for (const module of modules) {
273
+ const map = `client${module}.map`;
274
+ if (!listed.has(map)) {
275
+ for (const match of (await files.readText(`client${module}`)).matchAll(HTTPS_URL)) {
276
+ const origin = httpsOrigin(match[0]);
277
+ if (origin) origins.add(origin);
278
+ }
279
+ continue;
280
+ }
281
+ const parsed = JSON.parse(await files.readText(map));
282
+ for (const [index, source] of (parsed.sources ?? []).entries()) {
283
+ if (source === null || !isOwnSource(source)) continue;
284
+ const content = parsed.sourcesContent?.[index];
285
+ if (typeof content !== "string") continue;
286
+ for (const match of content.matchAll(HTTPS_URL)) {
287
+ const origin = httpsOrigin(match[0]);
288
+ if (origin) origins.add(origin);
289
+ }
290
+ }
291
+ }
292
+ return [...origins].sort();
293
+ }
294
+ /** Whether a source map's source is the artifact's own file, not a package's or Mostra's. */
295
+ function isOwnSource(source) {
296
+ const path = source.replaceAll("\\", "/");
297
+ return /(^|\/)source\//.test(path) && !path.includes("/node_modules/");
298
+ }
299
+ /**
300
+ * The document. The module runs last, after the stylesheet; a dynamic import's preload of a
301
+ * stylesheet or chunk the page already holds is told not to fail (Vite's `vite:preloadError`).
302
+ */
303
+ function pageHtml(parts) {
304
+ const tokens = JSON.stringify(HOST_TOKENS).replaceAll("<", "\\u003c");
305
+ return [
306
+ "<!doctype html>",
307
+ `<html lang="${escapeHtml(parts.lang)}">`,
308
+ " <head>",
309
+ " <meta charset=\"utf-8\" />",
310
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />",
311
+ ` <meta name="mostra-version" content="${escapeHtml(parts.versionId)}" />`,
312
+ " <meta name=\"mostra-target\" content=\"mcp-app\" />",
313
+ ` <title>${escapeHtml(parts.title)}</title>`,
314
+ ` <script type="application/json" id="mostra-host-tokens">${tokens}<\/script>`,
315
+ " <script>addEventListener(\"vite:preloadError\", function (event) { event.preventDefault(); });<\/script>",
316
+ ` <style>${styleText(parts.css)}</style>`,
317
+ " </head>",
318
+ " <body>",
319
+ " <div id=\"root\"></div>",
320
+ moduleElements(parts.code),
321
+ " </body>",
322
+ "</html>",
323
+ ""
324
+ ].join("\n");
325
+ }
326
+ //#endregion
327
+ //#region src/index.ts
328
+ /**
329
+ * `@mostra/plugin-mcp-app`: Mostra's MCP App exporter (D175 item 2, MC-02), the first first-party
330
+ * plugin, on `@mostra/contract-exporter`. It turns one published version into an MCP App: one
331
+ * self-contained HTML5 page (`index.html`, `text/html;profile=mcp-app`) that a chat host shows
332
+ * inline as `ui://mostra/view/<versionId>`, and `mcp-app.json`, that resource's description with
333
+ * the origins it declares (`_meta.ui.csp`). Every home has it (scope `bundled`, D175 item 3), so
334
+ * `mostra export <artifact> --as mcp-app --out <dir>` and `artifact_open` work with nothing
335
+ * installed.
336
+ *
337
+ * @packageDocumentation
338
+ */
339
+ /** The exporter's ID: what `mostra export --as` names. */
340
+ const EXPORTER_ID = "mcp-app";
341
+ /** The origins an option lists, each an `https:` origin, deduplicated. */
342
+ function originsOption(value, name) {
343
+ if (value === void 0) return [];
344
+ const origins = [];
345
+ for (const entry of value) {
346
+ const origin = httpsOrigin(entry);
347
+ if (origin === void 0 || origin !== entry.replace(/\/$/, "")) throw new Error(`${name} takes https: origins such as https://api.example.com, not ${entry}`);
348
+ if (!origins.includes(origin)) origins.push(origin);
349
+ }
350
+ return origins;
351
+ }
352
+ /** The exporter `mcp-app`: one version as an MCP App (the package's default export). */
353
+ const exporter = defineExporter({
354
+ id: EXPORTER_ID,
355
+ title: "MCP App",
356
+ description: "One self-contained page that chat hosts show inline (MCP Apps), with its ui:// resource's description.",
357
+ output: {
358
+ mediaType: MCP_APP_MIME_TYPE,
359
+ layout: "directory"
360
+ },
361
+ options: {
362
+ type: "object",
363
+ additionalProperties: false,
364
+ properties: {
365
+ connectDomains: {
366
+ type: "array",
367
+ items: { type: "string" },
368
+ description: "More https: origins the page fetches from, beyond those its code names."
369
+ },
370
+ resourceDomains: {
371
+ type: "array",
372
+ items: { type: "string" },
373
+ description: "More https: origins the page loads images, styles or media from."
374
+ },
375
+ prefersBorder: {
376
+ type: "boolean",
377
+ description: "Whether the host draws a border and background around the page; true unless set."
378
+ }
379
+ }
380
+ },
381
+ async export({ version, files, options }, { signal }) {
382
+ const findings = [];
383
+ const client = await clientFiles(files);
384
+ const built = readBuiltPage(await files.readText("client/index.html"));
385
+ const stylesheets = [...built.stylesheets, ...[...client.paths].filter((path) => extensionOf(path) === ".css" && !built.stylesheets.includes(path)).sort()];
386
+ const cssParts = [];
387
+ const cssOrigins = /* @__PURE__ */ new Set();
388
+ let fonts = 0;
389
+ for (const sheet of stylesheets) {
390
+ if (!client.paths.has(sheet)) continue;
391
+ const inlined = await inlineStylesheet(new TextDecoder().decode(await client.read(sheet)), client);
392
+ cssParts.push(inlined.css);
393
+ for (const origin of inlined.origins) cssOrigins.add(origin);
394
+ fonts += inlined.fonts;
395
+ }
396
+ if (signal.aborted) throw new Error("cancelled");
397
+ const bundled = await bundleEntry(built.entry, client, (path) => FONT_EXTENSIONS.includes(extensionOf(path)));
398
+ const codeOrigins = await ownOrigins(files, bundled.modules);
399
+ const connectDomains = [.../* @__PURE__ */ new Set([...codeOrigins, ...originsOption(options["connectDomains"], "connectDomains")])].sort();
400
+ const resourceDomains = [.../* @__PURE__ */ new Set([
401
+ ...codeOrigins,
402
+ ...cssOrigins,
403
+ ...originsOption(options["resourceDomains"], "resourceDomains")
404
+ ])].sort();
405
+ const meta = {
406
+ ...connectDomains.length > 0 || resourceDomains.length > 0 ? { csp: {
407
+ ...connectDomains.length > 0 ? { connectDomains } : {},
408
+ ...resourceDomains.length > 0 ? { resourceDomains } : {}
409
+ } } : {},
410
+ prefersBorder: typeof options["prefersBorder"] === "boolean" ? options["prefersBorder"] : true
411
+ };
412
+ const html = pageHtml({
413
+ title: version.title,
414
+ lang: built.lang,
415
+ versionId: version.versionId,
416
+ css: cssParts.join("\n"),
417
+ code: bundled.code
418
+ });
419
+ if (html.length > APP_PAGE_MAX_CHARS) findings.push({
420
+ code: "PAGE_TOO_LARGE",
421
+ severity: "error",
422
+ message: `The page is ${Math.ceil(html.length / 1024 / 1024)} MiB, past the 16 MiB an MCP App may be.`,
423
+ hint: "Load large media from an https: origin instead of bundling it."
424
+ });
425
+ if (version.server) findings.push({
426
+ code: "SERVER_CODE",
427
+ severity: "hint",
428
+ message: "The page's actions and live data reach Mostra through its MCP server's app tools; a host that serves this page without them shows them as unavailable."
429
+ });
430
+ if (fonts > 0) findings.push({
431
+ code: "FONTS_FROM_HOST",
432
+ severity: "hint",
433
+ message: `The page's own faces (${fonts}) are left out: a chat host loads no font files, and its own faces take their place.`
434
+ });
435
+ if (resourceDomains.length > 0 || connectDomains.length > 0) findings.push({
436
+ code: "ORIGINS_DECLARED",
437
+ severity: "hint",
438
+ message: `The page declares ${[.../* @__PURE__ */ new Set([...connectDomains, ...resourceDomains])].join(", ")} for a host that shows this resource itself; shown inline through artifact_open, whose loader declares no origin, it loads none of them, and says so for each (D175 item 2).`
439
+ });
440
+ const description = {
441
+ uri: mcpAppUri(version.versionId),
442
+ name: `mostra-${version.versionId}`,
443
+ title: version.title,
444
+ ...version.description !== void 0 ? { description: version.description } : {},
445
+ mimeType: MCP_APP_MIME_TYPE,
446
+ _meta: { ui: meta }
447
+ };
448
+ return {
449
+ files: [{
450
+ path: "index.html",
451
+ content: html
452
+ }, {
453
+ path: "mcp-app.json",
454
+ content: `${JSON.stringify(description, null, 2)}\n`
455
+ }],
456
+ entry: "index.html",
457
+ findings
458
+ };
459
+ }
460
+ });
461
+ //#endregion
462
+ export { EXPORTER_ID, exporter as default };
463
+
464
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/bundle.ts","../src/page.ts","../src/index.ts"],"sourcesContent":["/**\n * Re-bundles a version's client build into one module (D175 item 2): the entry the build's\n * `index.html` loads, its static and dynamic imports inlined, every file of the build it names by\n * path (`\"/assets/logo-H.png\"`) as a `data:` URL, so the page needs nothing but itself.\n */\nimport type { FileTree } from \"@mostra/contract-exporter\";\nimport { rolldown } from \"rolldown\";\n\n/** The media types of the files a page may name, by extension; anything else is octet-stream. */\nconst MEDIA_TYPES: Readonly<Record<string, string>> = {\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".avif\": \"image/avif\",\n \".svg\": \"image/svg+xml\",\n \".ico\": \"image/x-icon\",\n \".bmp\": \"image/bmp\",\n \".mp3\": \"audio/mpeg\",\n \".wav\": \"audio/wav\",\n \".ogg\": \"audio/ogg\",\n \".mp4\": \"video/mp4\",\n \".webm\": \"video/webm\",\n \".json\": \"application/json\",\n \".txt\": \"text/plain\",\n \".csv\": \"text/csv\",\n \".css\": \"text/css\",\n \".js\": \"text/javascript\",\n \".wasm\": \"application/wasm\",\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".ttf\": \"font/ttf\",\n \".otf\": \"font/otf\",\n};\n\n/** Font files, which a chat host's default policy never loads (no `font-src`, VERIFIED_FACTS). */\nexport const FONT_EXTENSIONS: readonly string[] = [\".woff\", \".woff2\", \".ttf\", \".otf\", \".eot\"];\n\n/** The extension of a path, lower case, with its dot. */\nexport function extensionOf(path: string): string {\n const name = path.slice(path.lastIndexOf(\"/\") + 1);\n const dot = name.lastIndexOf(\".\");\n return dot <= 0 ? \"\" : name.slice(dot).toLowerCase();\n}\n\n/** A file as a `data:` URL. */\nexport function dataUrl(path: string, bytes: Uint8Array): string {\n const type = MEDIA_TYPES[extensionOf(path)] ?? \"application/octet-stream\";\n return `data:${type};base64,${Buffer.from(bytes).toString(\"base64\")}`;\n}\n\n/** The client build's files the page may name by URL (`/assets/x.png`), by that URL. */\nexport interface ClientFiles {\n /** Every file of `client/`, by its URL path (`/assets/index-H.js`). */\n readonly paths: ReadonlySet<string>;\n /** A file's bytes by its URL path. */\n read(urlPath: string): Promise<Uint8Array>;\n}\n\n/** The client build of a version's file tree, by URL path. */\nexport async function clientFiles(files: FileTree): Promise<ClientFiles> {\n const paths = new Set<string>();\n for (const path of await files.list()) {\n if (path.startsWith(\"client/\")) paths.add(path.slice(\"client\".length));\n }\n return { paths, read: (urlPath) => files.read(`client${urlPath}`) };\n}\n\n/** The characters a quoted URL path may hold, so a replacement never runs into code around it. */\nconst QUOTED_PATH = /([\"'`])(\\/[A-Za-z0-9._~\\-/@%+]+)\\1/g;\n\n/**\n * Replaces each quoted URL path of a build file (`\"/assets/logo-H.png\"`) with its `data:` URL.\n * Only exact quoted paths of files the build holds change, never text that merely contains one.\n */\nexport async function inlineQuotedPaths(\n code: string,\n client: ClientFiles,\n skip: (urlPath: string) => boolean,\n): Promise<{ readonly code: string; readonly inlined: readonly string[] }> {\n const found = new Map<string, string>();\n for (const match of code.matchAll(QUOTED_PATH)) {\n const path = match[2] as string;\n if (!client.paths.has(path) || skip(path) || found.has(path)) continue;\n found.set(path, dataUrl(path, await client.read(path)));\n }\n if (found.size === 0) return { code, inlined: [] };\n const replaced = code.replace(QUOTED_PATH, (whole, quote: string, path: string) => {\n const url = found.get(path);\n return url === undefined ? whole : `${quote}${url}${quote}`;\n });\n return { code: replaced, inlined: [...found.keys()] };\n}\n\n/** Resolves an import of a build module (`./chunk-H.js`, `/assets/x.js`) to its URL path. */\nfunction resolveUrlPath(specifier: string, importer: string | undefined): string | undefined {\n if (specifier.startsWith(\"/\")) return new URL(specifier, \"http://page.invalid\").pathname;\n if (specifier.startsWith(\"./\") || specifier.startsWith(\"../\")) {\n const base = importer ?? \"/\";\n return new URL(specifier, `http://page.invalid${base}`).pathname;\n }\n return undefined;\n}\n\n/** The prefix rolldown sees build modules under, so no path of this machine is ever read. */\nconst MODULE_PREFIX = \"\\0mostra-client:\";\n\n/** What {@link bundleEntry} produced. */\nexport interface Bundled {\n /** The one module's code. */\n readonly code: string;\n /** The build's modules it holds, by URL path. */\n readonly modules: readonly string[];\n /** The files it names by URL that became `data:` URLs. */\n readonly inlined: readonly string[];\n}\n\n/**\n * Bundles the build's module `entry` (a URL path) and everything it imports into one ES module.\n * Every module comes from the version's file tree: an import outside it (a bare specifier, a URL)\n * throws, since a built page imports only its own chunks.\n */\nexport async function bundleEntry(\n entry: string,\n client: ClientFiles,\n skipInline: (urlPath: string) => boolean,\n): Promise<Bundled> {\n const modules: string[] = [];\n const inlined = new Set<string>();\n const build = await rolldown({\n input: `${MODULE_PREFIX}${entry}`,\n // The build is minified already; re-bundling only joins it.\n treeshake: false,\n logLevel: \"silent\",\n plugins: [\n {\n name: \"mostra-client\",\n resolveId(specifier, importer) {\n const from = importer?.startsWith(MODULE_PREFIX)\n ? importer.slice(MODULE_PREFIX.length)\n : undefined;\n const target = specifier.startsWith(MODULE_PREFIX)\n ? specifier.slice(MODULE_PREFIX.length)\n : resolveUrlPath(specifier, from);\n if (target === undefined || !client.paths.has(target)) {\n throw new Error(\n `the build's module ${from ?? entry} imports ${JSON.stringify(specifier)}, which isn't a file of the build`,\n );\n }\n return `${MODULE_PREFIX}${target}`;\n },\n async load(id) {\n if (!id.startsWith(MODULE_PREFIX)) return null;\n const path = id.slice(MODULE_PREFIX.length);\n modules.push(path);\n const text = new TextDecoder().decode(await client.read(path));\n // The build's source map comment names a file the page won't have.\n const code = text.replace(/\\n\\/\\/# sourceMappingURL=[^\\n]*\\s*$/, \"\\n\");\n const done = await inlineQuotedPaths(code, client, (urlPath) => {\n if (skipInline(urlPath)) return true;\n // A module of the build is joined into the bundle, never inlined as a string.\n return extensionOf(urlPath) === \".js\" || extensionOf(urlPath) === \".map\";\n });\n for (const path of done.inlined) inlined.add(path);\n return { code: done.code, moduleType: \"js\" };\n },\n },\n ],\n });\n try {\n const { output } = await build.generate({\n format: \"es\",\n // One module: dynamic imports are inlined, never split into chunks.\n codeSplitting: false,\n sourcemap: false,\n comments: { legal: false },\n });\n const chunk = output.find((item) => item.type === \"chunk\");\n if (chunk?.type !== \"chunk\") throw new Error(\"re-bundling produced no module\");\n return { code: chunk.code, modules, inlined: [...inlined] };\n } finally {\n await build.close();\n }\n}\n","/**\n * The MCP App's document (D175 item 2): one HTML5 page holding the version's whole client build,\n * marked for the `mcp-app` target, with the token table the runtime applies to the host's context\n * and the origins its own code names, declared for the host's policy.\n */\nimport type { FileTree } from \"@mostra/contract-exporter\";\nimport { HOST_TOKENS } from \"@mostra/themes\";\nimport { type ClientFiles, dataUrl, extensionOf, FONT_EXTENSIONS } from \"./bundle.ts\";\n\n/** Escapes text for HTML content and attribute values. */\nexport function escapeHtml(text: string): string {\n return text\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&#39;\");\n}\n\n/**\n * A stylesheet's text inside `<style>`, where `</style` would end it: written `<\\/style`, which\n * CSS reads as the same text (`\\/` is `/`), in a string, a comment or anywhere else.\n */\nexport function styleText(css: string): string {\n return css.replace(/<\\/(style)/gi, \"<\\\\/$1\");\n}\n\n/**\n * The page's own code, run without its text ever going through the HTML parser (review findings\n * Opus 11, Fable 12): rewriting `</script`, `<script` or `<!--` is right in a string and wrong in\n * code (`i<scriptCount`), and only a JavaScript tokenizer could tell them apart. So the module\n * travels as base64, which has no `<`, in an inert element, and {@link MODULE_BOOTSTRAP}, Mostra's\n * own few lines, decodes it and gives it to a module script as its `textContent`: the code runs\n * byte for byte as built. MCP Apps' default policy allows inline scripts (`'unsafe-inline'`).\n */\nexport const MODULE_BOOTSTRAP: string = [\n \"(function () {\",\n // A file the build fetches (`new URL(\"./data.csv\", import.meta.url)`, a wasm module) is a\n // data: URL here, which a host's `connect-src 'none'` would block: it is answered from memory,\n // with its own type (review finding Fable 13). Every other request goes as it would.\n \" var native = window.fetch;\",\n ' if (typeof native === \"function\") {',\n \" window.fetch = function (input, init) {\",\n ' var url = typeof input === \"string\" ? input : input && (input.href || input.url);',\n ' var comma = typeof url === \"string\" && url.slice(0, 5) === \"data:\" ? url.indexOf(\",\") : -1;',\n \" if (comma === -1) return native.apply(this, arguments);\",\n \" var head = url.slice(5, comma);\",\n \" var payload = url.slice(comma + 1);\",\n \" var encoded = /;base64$/i.test(head);\",\n ' var type = head.replace(/;base64$/i, \"\") || \"text/plain;charset=US-ASCII\";',\n \" var data;\",\n \" if (encoded) {\",\n \" var raw = atob(payload);\",\n \" data = new Uint8Array(raw.length);\",\n \" for (var j = 0; j !== raw.length; j++) data[j] = raw.charCodeAt(j);\",\n \" } else data = new TextEncoder().encode(decodeURIComponent(payload));\",\n ' return Promise.resolve(new Response(data, { headers: { \"content-type\": type } }));',\n \" };\",\n \" }\",\n ' var carrier = document.getElementById(\"mostra-module\");',\n \" if (carrier === null) return;\",\n ' var binary = atob((carrier.textContent || \"\").trim());',\n \" var bytes = new Uint8Array(binary.length);\",\n \" for (var i = 0; i !== binary.length; i++) bytes[i] = binary.charCodeAt(i);\",\n ' var module = document.createElement(\"script\");',\n ' module.type = \"module\";',\n \" module.textContent = new TextDecoder().decode(bytes);\",\n \" document.body.append(module);\",\n \"})();\",\n].join(\"\\n\");\n\n/** The two elements that carry and run the page's module (see {@link MODULE_BOOTSTRAP}). */\nexport function moduleElements(code: string): string {\n const encoded = Buffer.from(code, \"utf8\").toString(\"base64\");\n return [\n ` <script type=\"application/octet-stream\" id=\"mostra-module\">${encoded}</script>`,\n ` <script>${MODULE_BOOTSTRAP}</script>`,\n ].join(\"\\n\");\n}\n\n/** What the build's `index.html` names: its module entry and stylesheets, its language. */\nexport interface BuiltPage {\n readonly entry: string;\n readonly stylesheets: readonly string[];\n readonly lang: string;\n}\n\n/** Reads the build's `index.html` (the builder's own, INTERFACES §11). */\nexport function readBuiltPage(html: string): BuiltPage {\n const entry = /<script\\b[^>]*\\btype=\"module\"[^>]*\\bsrc=\"([^\"]+)\"/i.exec(html)?.[1];\n if (entry === undefined) throw new Error(\"the build's index.html names no module script\");\n const stylesheets = [\n ...html.matchAll(/<link\\b[^>]*\\brel=\"stylesheet\"[^>]*\\bhref=\"([^\"]+)\"/gi),\n ].map((match) => match[1] as string);\n const lang = /<html\\b[^>]*\\blang=\"([^\"]*)\"/i.exec(html)?.[1] ?? \"en\";\n return { entry, stylesheets, lang };\n}\n\n/** The URLs a stylesheet names: `url(x)`, `url(\"x\")`, `url('x')`. */\nconst CSS_URL = /url\\(\\s*([\"']?)([^\"')]+)\\1\\s*\\)/g;\n\n/**\n * A stylesheet for the page: each file of the build it names as a `data:` URL, its `@font-face`\n * rules for the build's own faces left out (a chat host's policy loads no font, VERIFIED_FACTS,\n * WP-17; the host's faces take their place, D141 item 4), and the absolute `https:` origins it\n * names.\n */\nexport async function inlineStylesheet(\n css: string,\n client: ClientFiles,\n): Promise<{ readonly css: string; readonly origins: readonly string[]; readonly fonts: number }> {\n let fonts = 0;\n const withoutFaces = css.replace(/@font-face\\s*\\{[^}]*\\}/g, (rule) => {\n const named = [...rule.matchAll(CSS_URL)].map((match) => match[2] as string);\n const ours =\n named.length > 0 && named.every((url) => client.paths.has(url.split(/[?#]/)[0] ?? url));\n if (!ours) return rule;\n fonts += 1;\n return \"\";\n });\n const origins = new Set<string>();\n const urls = new Map<string, string>();\n for (const match of withoutFaces.matchAll(CSS_URL)) {\n const url = match[2] as string;\n const path = url.split(/[?#]/)[0] ?? url;\n if (client.paths.has(path) && !FONT_EXTENSIONS.includes(extensionOf(path))) {\n if (!urls.has(path)) urls.set(path, dataUrl(path, await client.read(path)));\n continue;\n }\n const origin = httpsOrigin(url);\n if (origin !== undefined) origins.add(origin);\n }\n const inlined = withoutFaces.replace(CSS_URL, (whole, _quote: string, url: string) => {\n const path = url.split(/[?#]/)[0] ?? url;\n const data = urls.get(path);\n return data === undefined ? whole : `url(\"${data}\")`;\n });\n return { css: inlined, origins: [...origins], fonts };\n}\n\n/** The origin of an absolute `https:` URL, or `undefined`. */\nexport function httpsOrigin(url: string): string | undefined {\n if (!/^https:\\/\\//i.test(url)) return undefined;\n try {\n const parsed = new URL(url);\n return parsed.hostname === \"\" ? undefined : parsed.origin;\n } catch {\n return undefined;\n }\n}\n\n/** Absolute `https:` URLs in code. */\nconst HTTPS_URL = /https:\\/\\/[A-Za-z0-9.-]+(?::\\d{1,5})?/g;\n\n/**\n * The `https:` origins the artifact's own code names, from the build's source maps: only the\n * sources the artifact wrote (under its `source/` directory, never a package's), since packages'\n * documentation links (react.dev, json-schema.org) are never fetched. A build without source maps\n * declares every origin its modules name.\n */\nexport async function ownOrigins(\n files: FileTree,\n modules: readonly string[],\n): Promise<readonly string[]> {\n const origins = new Set<string>();\n const listed = new Set(await files.list());\n for (const module of modules) {\n const map = `client${module}.map`;\n if (!listed.has(map)) {\n for (const match of (await files.readText(`client${module}`)).matchAll(HTTPS_URL)) {\n const origin = httpsOrigin(match[0]);\n if (origin) origins.add(origin);\n }\n continue;\n }\n const parsed = JSON.parse(await files.readText(map)) as {\n sources?: (string | null)[];\n sourcesContent?: (string | null)[];\n };\n for (const [index, source] of (parsed.sources ?? []).entries()) {\n if (source === null || !isOwnSource(source)) continue;\n const content = parsed.sourcesContent?.[index];\n if (typeof content !== \"string\") continue;\n for (const match of content.matchAll(HTTPS_URL)) {\n const origin = httpsOrigin(match[0]);\n if (origin) origins.add(origin);\n }\n }\n }\n return [...origins].sort();\n}\n\n/** Whether a source map's source is the artifact's own file, not a package's or Mostra's. */\nexport function isOwnSource(source: string): boolean {\n const path = source.replaceAll(\"\\\\\", \"/\");\n return /(^|\\/)source\\//.test(path) && !path.includes(\"/node_modules/\");\n}\n\n/** The page's parts. */\nexport interface PageParts {\n readonly title: string;\n readonly lang: string;\n readonly versionId: string;\n readonly css: string;\n readonly code: string;\n}\n\n/**\n * The document. The module runs last, after the stylesheet; a dynamic import's preload of a\n * stylesheet or chunk the page already holds is told not to fail (Vite's `vite:preloadError`).\n */\nexport function pageHtml(parts: PageParts): string {\n // JSON's own escape for `<`, so no sequence in it can end the script element.\n const tokens = JSON.stringify(HOST_TOKENS).replaceAll(\"<\", \"\\\\u003c\");\n return [\n \"<!doctype html>\",\n `<html lang=\"${escapeHtml(parts.lang)}\">`,\n \" <head>\",\n ' <meta charset=\"utf-8\" />',\n ' <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />',\n ` <meta name=\"mostra-version\" content=\"${escapeHtml(parts.versionId)}\" />`,\n ' <meta name=\"mostra-target\" content=\"mcp-app\" />',\n ` <title>${escapeHtml(parts.title)}</title>`,\n ` <script type=\"application/json\" id=\"mostra-host-tokens\">${tokens}</script>`,\n ' <script>addEventListener(\"vite:preloadError\", function (event) { event.preventDefault(); });</script>',\n ` <style>${styleText(parts.css)}</style>`,\n \" </head>\",\n \" <body>\",\n ' <div id=\"root\"></div>',\n moduleElements(parts.code),\n \" </body>\",\n \"</html>\",\n \"\",\n ].join(\"\\n\");\n}\n","/**\n * `@mostra/plugin-mcp-app`: Mostra's MCP App exporter (D175 item 2, MC-02), the first first-party\n * plugin, on `@mostra/contract-exporter`. It turns one published version into an MCP App: one\n * self-contained HTML5 page (`index.html`, `text/html;profile=mcp-app`) that a chat host shows\n * inline as `ui://mostra/view/<versionId>`, and `mcp-app.json`, that resource's description with\n * the origins it declares (`_meta.ui.csp`). Every home has it (scope `bundled`, D175 item 3), so\n * `mostra export <artifact> --as mcp-app --out <dir>` and `artifact_open` work with nothing\n * installed.\n *\n * @packageDocumentation\n */\nimport {\n defineExporter,\n type Exporter,\n type ExporterDefinition,\n type ExportResult,\n type Finding,\n} from \"@mostra/contract-exporter\";\nimport {\n APP_PAGE_MAX_CHARS,\n MCP_APP_MIME_TYPE,\n type McpAppResourceMeta,\n mcpAppUri,\n} from \"@mostra/protocol\";\nimport { bundleEntry, clientFiles, extensionOf, FONT_EXTENSIONS } from \"./bundle.ts\";\nimport { httpsOrigin, inlineStylesheet, ownOrigins, pageHtml, readBuiltPage } from \"./page.ts\";\n\n/** The exporter's ID: what `mostra export --as` names. */\nexport const EXPORTER_ID = \"mcp-app\";\n\n/** What `mcp-app.json` holds: the page's `ui://` resource as MCP lists it. */\nexport interface McpAppDescription {\n /** The page's resource: `ui://mostra/view/<versionId>`. */\n readonly uri: string;\n /** A stable machine name: `mostra-<versionId>`. */\n readonly name: string;\n /** The artifact's title, for people. */\n readonly title: string;\n /** The artifact's description, when it has one. */\n readonly description?: string;\n /** `text/html;profile=mcp-app`. */\n readonly mimeType: string;\n /** What the page declares to its host: the origins it reaches, its border preference. */\n readonly _meta: { readonly ui: McpAppResourceMeta };\n}\n\n/** The origins an option lists, each an `https:` origin, deduplicated. */\nfunction originsOption(value: unknown, name: string): string[] {\n if (value === undefined) return [];\n const origins: string[] = [];\n for (const entry of value as string[]) {\n const origin = httpsOrigin(entry);\n if (origin === undefined || origin !== entry.replace(/\\/$/, \"\")) {\n throw new Error(`${name} takes https: origins such as https://api.example.com, not ${entry}`);\n }\n if (!origins.includes(origin)) origins.push(origin);\n }\n return origins;\n}\n\n/** The exporter `mcp-app`: one version as an MCP App (the package's default export). */\nconst exporter: Exporter = defineExporter<ExporterDefinition>({\n id: EXPORTER_ID,\n title: \"MCP App\",\n description:\n \"One self-contained page that chat hosts show inline (MCP Apps), with its ui:// resource's description.\",\n output: { mediaType: MCP_APP_MIME_TYPE, layout: \"directory\" },\n options: {\n type: \"object\",\n additionalProperties: false,\n properties: {\n connectDomains: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"More https: origins the page fetches from, beyond those its code names.\",\n },\n resourceDomains: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"More https: origins the page loads images, styles or media from.\",\n },\n prefersBorder: {\n type: \"boolean\",\n description:\n \"Whether the host draws a border and background around the page; true unless set.\",\n },\n },\n },\n async export({ version, files, options }, { signal }): Promise<ExportResult> {\n const findings: Finding[] = [];\n const client = await clientFiles(files);\n const built = readBuiltPage(await files.readText(\"client/index.html\"));\n // Every stylesheet of the build: the page's own first, then those a dynamic import loads.\n const stylesheets = [\n ...built.stylesheets,\n ...[...client.paths]\n .filter((path) => extensionOf(path) === \".css\" && !built.stylesheets.includes(path))\n .sort(),\n ];\n const cssParts: string[] = [];\n const cssOrigins = new Set<string>();\n let fonts = 0;\n for (const sheet of stylesheets) {\n if (!client.paths.has(sheet)) continue;\n const inlined = await inlineStylesheet(\n new TextDecoder().decode(await client.read(sheet)),\n client,\n );\n cssParts.push(inlined.css);\n for (const origin of inlined.origins) cssOrigins.add(origin);\n fonts += inlined.fonts;\n }\n if (signal.aborted) throw new Error(\"cancelled\");\n const bundled = await bundleEntry(built.entry, client, (path) =>\n FONT_EXTENSIONS.includes(extensionOf(path)),\n );\n const codeOrigins = await ownOrigins(files, bundled.modules);\n const connectDomains = [\n ...new Set([...codeOrigins, ...originsOption(options[\"connectDomains\"], \"connectDomains\")]),\n ].sort();\n const resourceDomains = [\n ...new Set([\n ...codeOrigins,\n ...cssOrigins,\n ...originsOption(options[\"resourceDomains\"], \"resourceDomains\"),\n ]),\n ].sort();\n const meta: McpAppResourceMeta = {\n ...(connectDomains.length > 0 || resourceDomains.length > 0\n ? {\n csp: {\n ...(connectDomains.length > 0 ? { connectDomains } : {}),\n ...(resourceDomains.length > 0 ? { resourceDomains } : {}),\n },\n }\n : {}),\n // Said every time, since hosts' own defaults differ (MCP Apps recommends an explicit value):\n // a border and background, so the page and its bar read as one card, unless asked otherwise.\n prefersBorder:\n typeof options[\"prefersBorder\"] === \"boolean\" ? options[\"prefersBorder\"] : true,\n };\n const html = pageHtml({\n title: version.title,\n lang: built.lang,\n versionId: version.versionId,\n css: cssParts.join(\"\\n\"),\n code: bundled.code,\n });\n if (html.length > APP_PAGE_MAX_CHARS) {\n findings.push({\n code: \"PAGE_TOO_LARGE\",\n severity: \"error\",\n message: `The page is ${Math.ceil(html.length / 1024 / 1024)} MiB, past the 16 MiB an MCP App may be.`,\n hint: \"Load large media from an https: origin instead of bundling it.\",\n });\n }\n if (version.server) {\n findings.push({\n code: \"SERVER_CODE\",\n severity: \"hint\",\n message:\n \"The page's actions and live data reach Mostra through its MCP server's app tools; a host that serves this page without them shows them as unavailable.\",\n });\n }\n if (fonts > 0) {\n findings.push({\n code: \"FONTS_FROM_HOST\",\n severity: \"hint\",\n message: `The page's own faces (${fonts}) are left out: a chat host loads no font files, and its own faces take their place.`,\n });\n }\n if (resourceDomains.length > 0 || connectDomains.length > 0) {\n findings.push({\n code: \"ORIGINS_DECLARED\",\n severity: \"hint\",\n message: `The page declares ${[...new Set([...connectDomains, ...resourceDomains])].join(\", \")} for a host that shows this resource itself; shown inline through artifact_open, whose loader declares no origin, it loads none of them, and says so for each (D175 item 2).`,\n });\n }\n const description: McpAppDescription = {\n uri: mcpAppUri(version.versionId),\n name: `mostra-${version.versionId}`,\n title: version.title,\n ...(version.description !== undefined ? { description: version.description } : {}),\n mimeType: MCP_APP_MIME_TYPE,\n _meta: { ui: meta },\n };\n return {\n files: [\n { path: \"index.html\", content: html },\n { path: \"mcp-app.json\", content: `${JSON.stringify(description, null, 2)}\\n` },\n ],\n entry: \"index.html\",\n findings,\n };\n },\n});\n\nexport default exporter;\n"],"mappings":";;;;;;AASA,MAAM,cAAgD;CACpD,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,OAAO;CACP,SAAS;CACT,SAAS;CACT,UAAU;CACV,QAAQ;CACR,QAAQ;AACV;;AAGA,MAAa,kBAAqC;CAAC;CAAS;CAAU;CAAQ;CAAQ;AAAM;;AAG5F,SAAgB,YAAY,MAAsB;CAChD,MAAM,OAAO,KAAK,MAAM,KAAK,YAAY,GAAG,IAAI,CAAC;CACjD,MAAM,MAAM,KAAK,YAAY,GAAG;CAChC,OAAO,OAAO,IAAI,KAAK,KAAK,MAAM,GAAG,CAAC,CAAC,YAAY;AACrD;;AAGA,SAAgB,QAAQ,MAAc,OAA2B;CAE/D,OAAO,QADM,YAAY,YAAY,IAAI,MAAM,2BAC3B,UAAU,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS,QAAQ;AACpE;;AAWA,eAAsB,YAAY,OAAuC;CACvE,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,MAAM,QAAQ,MAAM,MAAM,KAAK,GAClC,IAAI,KAAK,WAAW,SAAS,GAAG,MAAM,I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E;GAC7D,MAAM;EACR,CAAC;EAEH,IAAI,QAAQ,QACV,SAAS,KAAK;GACZ,MAAM;GACN,UAAU;GACV,SACE;EACJ,CAAC;EAEH,IAAI,QAAQ,GACV,SAAS,KAAK;GACZ,MAAM;GACN,UAAU;GACV,SAAS,yBAAyB,MAAM;EAC1C,CAAC;EAEH,IAAI,gBAAgB,SAAS,KAAK,eAAe,SAAS,GACxD,SAAS,KAAK;GACZ,MAAM;GACN,UAAU;GACV,SAAS,qBAAqB,CAAC,mBAAG,IAAI,IAAI,CAAC,GAAG,gBAAgB,GAAG,eAAe,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE;EACjG,CAAC;EAEH,MAAM,cAAiC;GACrC,KAAK,UAAU,QAAQ,SAAS;GAChC,MAAM,UAAU,QAAQ;GACxB,OAAO,QAAQ;GACf,GAAI,QAAQ,gBAAgB,KAAA,IAAY,EAAE,aAAa,QAAQ,YAAY,IAAI,CAAC;GAChF,UAAU;GACV,OAAO,EAAE,IAAI,KAAK;EACpB;EACA,OAAO;GACL,OAAO,CACL;IAAE,MAAM;IAAc,SAAS;GAAK,GACpC;IAAE,MAAM;IAAgB,SAAS,GAAG,KAAK,UAAU,aAAa,MAAM,CAAC,EAAE;GAAI,CAC/E;GACA,OAAO;GACP;EACF;CACF;AACF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,86 @@
1
1
  {
2
2
  "name": "@mostra/plugin-mcp-app",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.17.0",
4
+ "description": "Mostra's MCP App exporter: one published artifact version as a single-file ui:// resource that chat hosts show inline.",
5
+ "license": "Apache-2.0",
6
+ "author": "The Mostra Authors",
7
+ "homepage": "https://github.com/mostra-dev/mostra/tree/main/plugins/mcp-app#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/mostra-dev/mostra.git",
11
+ "directory": "plugins/mcp-app"
12
+ },
13
+ "bugs": "https://github.com/mostra-dev/mostra/issues",
14
+ "keywords": [
15
+ "mostra",
16
+ "mostra-plugin",
17
+ "mcp",
18
+ "mcp-apps",
19
+ "exporter"
20
+ ],
21
+ "type": "module",
22
+ "sideEffects": false,
23
+ "exports": {
24
+ ".": {
25
+ "@mostra/source": "./src/index.ts",
26
+ "types": "./dist/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ },
29
+ "./package.json": "./package.json"
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "src",
34
+ "!src/**/*.test.ts"
35
+ ],
36
+ "engines": {
37
+ "node": ">=22.19"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public",
41
+ "provenance": true
42
+ },
43
+ "mostra": {
44
+ "name": "dev.mostra/mcp-app",
45
+ "title": "MCP App",
46
+ "description": "Exports a version as an MCP App: one self-contained ui:// page that chat hosts show inline.",
47
+ "contracts": {
48
+ "exporter": "^0.1.0"
49
+ },
50
+ "contributes": {
51
+ "exporters": [
52
+ {
53
+ "id": "mcp-app",
54
+ "entry": "./dist/index.js",
55
+ "export": "default"
56
+ }
57
+ ]
58
+ },
59
+ "effects": [],
60
+ "license": "Apache-2.0",
61
+ "platforms": [
62
+ "darwin",
63
+ "linux",
64
+ "win32"
65
+ ]
66
+ },
67
+ "dependencies": {
68
+ "@mostra/contract-exporter": "0.1.0",
69
+ "@mostra/protocol": "0.17.0",
70
+ "@mostra/themes": "0.17.0",
71
+ "rolldown": "1.2.14"
72
+ },
73
+ "devDependencies": {
74
+ "@mostra/tools": "0.0.0",
75
+ "@types/node": "24.19.2",
76
+ "tsdown": "0.23.1",
77
+ "typescript": "7.0.2",
78
+ "vitest": "5.0.5"
79
+ },
80
+ "scripts": {
81
+ "build": "tsdown",
82
+ "typecheck": "tsc -b",
83
+ "test": "vitest run",
84
+ "api": "mostra-tools api"
85
+ }
6
86
  }