mountly-mcp 3.1.0 → 4.0.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.
Files changed (87) hide show
  1. package/README.md +54 -29
  2. package/dist/bridge/iframe-entry.js +24 -16
  3. package/dist/bridge/index.d.ts +5 -5
  4. package/dist/bridge/index.js +2 -2
  5. package/dist/build/index.d.ts +3 -3
  6. package/dist/build/index.js +2 -2
  7. package/dist/{chunk-NLQDVNZP.js → chunk-AEVQKFXX.js} +12 -8
  8. package/dist/chunk-AEVQKFXX.js.map +1 -0
  9. package/dist/{chunk-SNWNF2XI.js → chunk-JVQZGKBL.js} +13 -13
  10. package/dist/chunk-JVQZGKBL.js.map +1 -0
  11. package/dist/chunk-KWVGW5Q7.js +582 -0
  12. package/dist/chunk-KWVGW5Q7.js.map +1 -0
  13. package/dist/{chunk-DQLQOMDM.js → chunk-M4WFJR3C.js} +2 -2
  14. package/dist/{chunk-DQLQOMDM.js.map → chunk-M4WFJR3C.js.map} +1 -1
  15. package/dist/{chunk-4WAKOYMK.js → chunk-MTJDRWGD.js} +2 -2
  16. package/dist/chunk-MTJDRWGD.js.map +1 -0
  17. package/dist/chunk-SADNMGP6.js +16 -0
  18. package/dist/chunk-SADNMGP6.js.map +1 -0
  19. package/dist/cli.js +21 -10
  20. package/dist/cli.js.map +1 -1
  21. package/dist/create.d.ts +10 -0
  22. package/dist/create.js +107 -0
  23. package/dist/create.js.map +1 -0
  24. package/dist/dev/host-entry.js +2 -2
  25. package/dist/dev/index.d.ts +1 -1
  26. package/dist/dev/index.js +1 -1
  27. package/dist/index.d.ts +1 -0
  28. package/dist/index.js +10 -2
  29. package/dist/json-render/{widget.d.ts → generative-view.d.ts} +9 -11
  30. package/dist/json-render/index.d.ts +1 -1
  31. package/dist/json-render/index.js +9 -8
  32. package/dist/json-render/index.js.map +1 -1
  33. package/dist/publish.d.ts +10 -0
  34. package/dist/react/context.d.ts +1 -1
  35. package/dist/react/create-view.d.ts +8 -0
  36. package/dist/react/hooks.d.ts +1 -1
  37. package/dist/react/index.d.ts +1 -1
  38. package/dist/react/index.js +6 -5
  39. package/dist/schema.d.ts +2 -2
  40. package/dist/server/index.d.ts +2 -2
  41. package/dist/server/index.js.map +1 -1
  42. package/dist/svelte/index.d.ts +10 -16
  43. package/dist/svelte/index.js +7 -3
  44. package/dist/svelte/index.js.map +1 -1
  45. package/dist/testing/index.d.ts +1 -1
  46. package/dist/testing/index.js +1 -1
  47. package/dist/testing/index.js.map +1 -1
  48. package/dist/types.d.ts +14 -4
  49. package/dist/vite/index.d.ts +6 -6
  50. package/dist/vite/index.js +7 -7
  51. package/dist/vite/index.js.map +1 -1
  52. package/dist/vue/index.d.ts +12 -17
  53. package/dist/vue/index.js +10 -6
  54. package/dist/vue/index.js.map +1 -1
  55. package/package.json +7 -11
  56. package/templates/react/.gitignore.tmpl +4 -0
  57. package/templates/react/README.md.tmpl +15 -0
  58. package/templates/react/mcp.fixtures.json.tmpl +4 -0
  59. package/templates/react/package.json.tmpl +27 -0
  60. package/templates/react/server.mjs.tmpl +70 -0
  61. package/templates/react/src/view.tsx.tmpl +160 -0
  62. package/templates/react/tsconfig.json.tmpl +15 -0
  63. package/templates/react/vite.config.ts.tmpl +22 -0
  64. package/templates/svelte/.gitignore.tmpl +4 -0
  65. package/templates/svelte/README.md.tmpl +14 -0
  66. package/templates/svelte/mcp.fixtures.json.tmpl +4 -0
  67. package/templates/svelte/package.json.tmpl +26 -0
  68. package/templates/svelte/server.mjs.tmpl +70 -0
  69. package/templates/svelte/src/Dashboard.svelte.tmpl +158 -0
  70. package/templates/svelte/src/view.ts.tmpl +14 -0
  71. package/templates/svelte/tsconfig.json.tmpl +14 -0
  72. package/templates/svelte/vite.config.ts.tmpl +22 -0
  73. package/templates/vue/.gitignore.tmpl +4 -0
  74. package/templates/vue/README.md.tmpl +14 -0
  75. package/templates/vue/mcp.fixtures.json.tmpl +4 -0
  76. package/templates/vue/package.json.tmpl +26 -0
  77. package/templates/vue/server.mjs.tmpl +70 -0
  78. package/templates/vue/src/Dashboard.vue.tmpl +159 -0
  79. package/templates/vue/src/view.ts.tmpl +14 -0
  80. package/templates/vue/tsconfig.json.tmpl +15 -0
  81. package/templates/vue/vite.config.ts.tmpl +22 -0
  82. package/dist/chunk-4WAKOYMK.js.map +0 -1
  83. package/dist/chunk-KRAS266U.js +0 -260
  84. package/dist/chunk-KRAS266U.js.map +0 -1
  85. package/dist/chunk-NLQDVNZP.js.map +0 -1
  86. package/dist/chunk-SNWNF2XI.js.map +0 -1
  87. package/dist/react/create-widget.d.ts +0 -11
@@ -1,260 +0,0 @@
1
- import {
2
- escapeInlineScript,
3
- serializeInlineScriptValue
4
- } from "./chunk-YJA4H6IB.js";
5
-
6
- // src/dev/index.ts
7
- import { existsSync } from "fs";
8
- import { readFile } from "fs/promises";
9
- import { createServer } from "http";
10
- import { fileURLToPath } from "url";
11
- function escapeHtml(value) {
12
- return value.replace(
13
- /[&<>"']/g,
14
- (character) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[character]
15
- );
16
- }
17
- var runtimeCache = /* @__PURE__ */ new Map();
18
- function loadRuntime(name) {
19
- const cached = runtimeCache.get(name);
20
- if (cached) return cached;
21
- const loading = (async () => {
22
- try {
23
- return await readFile(
24
- fileURLToPath(import.meta.resolve(`mountly-mcp/dev/${name}.js`)),
25
- "utf8"
26
- );
27
- } catch {
28
- }
29
- const entry = fileURLToPath(new URL(`./${name}.ts`, import.meta.url));
30
- if (!existsSync(entry)) {
31
- throw new Error(
32
- `mountly-mcp dev: ${name} runtime missing. Expected the packaged 'mountly-mcp/dev/${name}.js' export, or ${entry} when running from source.`
33
- );
34
- }
35
- const { build } = await import("vite");
36
- const result = await build({
37
- configFile: false,
38
- logLevel: "silent",
39
- build: {
40
- write: false,
41
- target: "es2022",
42
- minify: false,
43
- lib: { entry, formats: ["iife"], name: "__mountlyMcpDevRuntime" }
44
- }
45
- });
46
- const outputs = Array.isArray(result) ? result : [result];
47
- const chunk = outputs.flatMap((output) => "output" in output ? output.output : []).find((item) => item.type === "chunk");
48
- if (!chunk || chunk.type !== "chunk")
49
- throw new Error(`mountly-mcp dev: failed to bundle ${name}`);
50
- return chunk.code;
51
- })();
52
- runtimeCache.set(name, loading);
53
- return loading;
54
- }
55
- function listenOnFreePort(server, port) {
56
- return new Promise((resolvePort, reject) => {
57
- const attempt = (candidate) => {
58
- const onError = (error) => {
59
- server.removeListener("listening", onListening);
60
- if (error.code === "EADDRINUSE" && candidate < port + 50) attempt(candidate + 1);
61
- else reject(error);
62
- };
63
- const onListening = () => {
64
- server.removeListener("error", onError);
65
- const address = server.address();
66
- resolvePort(typeof address === "object" && address !== null ? address.port : candidate);
67
- };
68
- server.once("error", onError);
69
- server.once("listening", onListening);
70
- server.listen(candidate);
71
- };
72
- attempt(port);
73
- });
74
- }
75
- async function startDevHost(options) {
76
- const { htmlPath, fixtures = {}, toolInput = {}, callTool } = options;
77
- const metaPath = `${htmlPath}.meta.json`;
78
- const initialMeta = JSON.parse(await readFile(metaPath, "utf8"));
79
- const toolName = options.toolName ?? initialMeta.name;
80
- const [hostRuntime, sandboxRuntime] = await Promise.all([
81
- loadRuntime("host-entry"),
82
- loadRuntime("sandbox-entry")
83
- ]);
84
- let version = 1;
85
- let hostOrigin = "";
86
- const sandboxServer = createServer((_req, res) => {
87
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
88
- res.end(sandboxProxyShell(hostOrigin, sandboxRuntime));
89
- });
90
- const sandboxPort = await listenOnFreePort(
91
- sandboxServer,
92
- options.sandboxPort ?? (options.hostPort ?? 5179) + 1
93
- );
94
- const sandboxOrigin = `http://localhost:${sandboxPort}`;
95
- const hostServer = createServer(async (req, res) => {
96
- const path = new URL(req.url ?? "/", "http://localhost").pathname;
97
- const send = (status, type, body) => {
98
- res.writeHead(status, { "Content-Type": type, "Cache-Control": "no-store" });
99
- res.end(body);
100
- };
101
- try {
102
- if (path === "/call" && req.method === "POST") {
103
- if (!callTool) return send(400, "text/plain", "no server connected");
104
- const body = await new Promise((done, fail) => {
105
- let raw = "";
106
- req.on("data", (chunk) => raw += chunk);
107
- req.on("end", () => done(raw));
108
- req.on("error", fail);
109
- });
110
- const { name, arguments: args } = JSON.parse(body);
111
- const result = await callTool(name, args).catch((error) => ({
112
- isError: true,
113
- content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }]
114
- }));
115
- return send(200, "application/json", JSON.stringify(result));
116
- }
117
- if (path === "/") return send(200, "text/html; charset=utf-8", hostPage());
118
- if (path === "/host.js") return send(200, "text/javascript; charset=utf-8", hostRuntime);
119
- if (path === "/version") return send(200, "application/json", String(version));
120
- if (path === "/widget.html")
121
- return send(200, "text/plain; charset=utf-8", await readFile(htmlPath, "utf8"));
122
- if (path === "/widget.meta.json")
123
- return send(200, "application/json", await readFile(metaPath, "utf8"));
124
- send(404, "text/plain", "not found");
125
- } catch (error) {
126
- send(500, "text/plain", error instanceof Error ? error.message : String(error));
127
- }
128
- });
129
- let hostPort;
130
- try {
131
- hostPort = await listenOnFreePort(hostServer, options.hostPort ?? 5179);
132
- } catch (caught) {
133
- await new Promise((done) => sandboxServer.close(() => done()));
134
- throw caught;
135
- }
136
- hostOrigin = `http://localhost:${hostPort}`;
137
- function hostPage() {
138
- return devHostHtml({
139
- toolName,
140
- sandboxOrigin,
141
- fixtures,
142
- toolInput,
143
- uri: initialMeta.uri,
144
- hasServer: callTool !== void 0
145
- });
146
- }
147
- return {
148
- hostUrl: hostOrigin,
149
- sandboxUrl: sandboxOrigin,
150
- reload() {
151
- version += 1;
152
- },
153
- async close() {
154
- await Promise.all([
155
- new Promise((done) => hostServer.close(() => done())),
156
- new Promise((done) => sandboxServer.close(() => done()))
157
- ]);
158
- }
159
- };
160
- }
161
- function devHostHtml(options) {
162
- const { toolName, sandboxOrigin, fixtures, toolInput, uri, hasServer } = options;
163
- const buttons = Object.keys(fixtures).map(
164
- (name, index) => `<button class="btn" data-fixture="${escapeHtml(name)}"${index === 0 ? ' data-active="true"' : ""}>${escapeHtml(name)}</button>`
165
- ).join("\n");
166
- return `<!doctype html>
167
- <html lang="en">
168
- <head>
169
- <meta charset="utf-8">
170
- <meta name="viewport" content="width=device-width,initial-scale=1">
171
- <title>mountly-mcp dev \xB7 ${escapeHtml(toolName)}</title>
172
- <style>
173
- :root { color-scheme:light; --bg:#f6f7f9; --fg:#0b0c0f; --muted:#5c6675; --accent:#1d4ed8; --border:#dcdfe5; }
174
- :root[data-theme="dark"] { color-scheme:dark; --bg:#0b0c0f; --fg:#e6e9ef; --muted:#9aa3b2; --accent:#7aa2ff; --border:#252a33; }
175
- * { box-sizing:border-box; }
176
- body { margin:0; min-height:100vh; background:var(--bg); color:var(--fg); font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,sans-serif; }
177
- header { padding:18px 24px; border-bottom:1px solid var(--border); display:flex; align-items:center; gap:12px; flex-wrap:wrap; }
178
- header h1 { margin:0; font-size:16px; font-weight:600; }
179
- header code { color:var(--muted); font-size:12px; }
180
- #fixtures { display:flex; gap:8px; flex-wrap:wrap; }
181
- .spacer { flex:1; }
182
- .btn { appearance:none; border:1px solid var(--border); background:transparent; color:var(--fg); padding:6px 12px; border-radius:6px; font:inherit; cursor:pointer; }
183
- .btn:hover { border-color:var(--accent); color:var(--accent); }
184
- .btn[data-active="true"] { background:var(--accent); color:white; border-color:var(--accent); }
185
- main { display:grid; grid-template-columns:minmax(420px,1fr) 360px; gap:20px; padding:24px; align-items:start; }
186
- iframe { width:100%; height:460px; border:1px solid var(--border); border-radius:12px; background:white; }
187
- .panel { border:1px solid var(--border); border-radius:12px; padding:16px; }
188
- .panel + .panel { margin-top:12px; }
189
- .panel h2 { margin:0 0 8px; font-size:13px; text-transform:uppercase; letter-spacing:.08em; color:var(--muted); }
190
- pre { margin:0; padding:10px; border-radius:8px; font:12px/1.45 ui-monospace,Menlo,Consolas,monospace; overflow:auto; max-height:200px; }
191
- .log { font:11px/1.5 ui-monospace,Menlo,Consolas,monospace; color:var(--muted); white-space:pre-wrap; max-height:280px; overflow:auto; }
192
- @media (max-width:880px) { main { grid-template-columns:1fr; padding:16px; } }
193
- </style>
194
- </head>
195
- <body>
196
- <header>
197
- <h1>${escapeHtml(toolName)}</h1>
198
- <code>${escapeHtml(uri)}</code>
199
- <span class="spacer"></span>
200
- <div id="fixtures">${buttons}</div>
201
- <button class="btn" id="theme" type="button">Theme</button>
202
- <button class="btn" id="teardown" type="button">Teardown</button>
203
- </header>
204
- <main>
205
- <iframe id="sandbox" sandbox="allow-scripts allow-same-origin" title="mountly-mcp sandbox proxy"></iframe>
206
- <div>
207
- <section class="panel">
208
- <h2>Last structuredContent</h2>
209
- <pre id="payload">(none yet)</pre>
210
- </section>
211
- <section class="panel">
212
- <h2>Channel log</h2>
213
- <div class="log" id="log"></div>
214
- </section>
215
- </div>
216
- </main>
217
- <script>
218
- globalThis.__mountlyMcpDevHost__ = ${serializeInlineScriptValue({
219
- toolName,
220
- sandboxOrigin,
221
- fixtures,
222
- toolInput,
223
- uri,
224
- hasServer,
225
- sandboxPath: "/sandbox-proxy.html"
226
- })};
227
- const HAS_SERVER = ${hasServer ? "true" : "false"};
228
- </script>
229
- <script src="/host.js"></script>
230
- </body>
231
- </html>
232
- `;
233
- }
234
- function sandboxProxyShell(hostOrigin, runtime) {
235
- return `<!doctype html>
236
- <html lang="en">
237
- <head>
238
- <meta charset="utf-8">
239
- <title>mountly-mcp sandbox proxy</title>
240
- <style>
241
- html, body { margin: 0; padding: 0; width: 100%; height: 100%; background: transparent; }
242
- #inner { width: 100%; height: 100%; border: 0; background: white; }
243
- </style>
244
- </head>
245
- <body>
246
- <script>globalThis.__mountlyMcpSandbox__ = ${serializeInlineScriptValue({ hostOrigin })};</script>
247
- <script>${escapeInlineScript(runtime)}</script>
248
- </body>
249
- </html>
250
- `;
251
- }
252
- async function sandboxProxyHtml(hostOrigin) {
253
- return sandboxProxyShell(hostOrigin, await loadRuntime("sandbox-entry"));
254
- }
255
-
256
- export {
257
- startDevHost,
258
- sandboxProxyHtml
259
- };
260
- //# sourceMappingURL=chunk-KRAS266U.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/dev/index.ts"],"sourcesContent":["/**\n * A local MCP Apps host, so a widget can be developed without installing a\n * real host and restarting it on every change.\n *\n * It is a genuine host, not a preview shim: two origins as the spec requires\n * (§8.4), a sandbox proxy that injects the sidecar's CSP and permissions, the\n * full `ui/initialize` handshake, and tool-input/tool-result delivery. A widget\n * that works here works in Claude, and one that reaches for `eval` fails here\n * for the same reason it would fail there.\n *\n * ```ts\n * const host = await startDevHost({ htmlPath: \"dist/widget.html\", fixtures });\n * console.log(host.hostUrl);\n * ```\n */\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { createServer, type Server } from \"node:http\";\nimport { fileURLToPath } from \"node:url\";\nimport type { McpResourceDeclaration } from \"../types.js\";\nimport { escapeInlineScript, serializeInlineScriptValue } from \"../html.js\";\n\nexport interface DevHostOptions {\n /** Built widget HTML. Its `.meta.json` sidecar is read alongside. */\n htmlPath: string;\n /**\n * Named samples, each becoming a button in the host chrome.\n *\n * Without `callTool` the value is delivered straight through as\n * `structuredContent`. With `callTool` it is the tool's *arguments*, and\n * what the view receives is whatever the real tool returns.\n */\n fixtures?: Record<string, unknown>;\n /**\n * Run a real tool. Supplied when the developer points `dev` at their server,\n * and used both for the fixture buttons and for `tools/call` requests the\n * view makes itself — so app-only tools behave as they will in production.\n */\n callTool?: (name: string, args: unknown) => Promise<unknown>;\n /** Arguments delivered as `ui/notifications/tool-input`. */\n toolInput?: Record<string, unknown>;\n /** Shown in the host chrome. Defaults to the sidecar's resource name. */\n toolName?: string;\n /** Defaults to 5179, incrementing until a free port is found. */\n hostPort?: number;\n /** Defaults to `hostPort + 1`, incrementing until a free port is found. */\n sandboxPort?: number;\n}\n\nexport interface DevHost {\n hostUrl: string;\n sandboxUrl: string;\n /** Tell connected browsers to reload — call after a rebuild. */\n reload(): void;\n close(): Promise<void>;\n}\n\nfunction escapeHtml(value: string): string {\n return value.replace(\n /[&<>\"']/g,\n (character) =>\n ({ \"&\": \"&amp;\", \"<\": \"&lt;\", \">\": \"&gt;\", '\"': \"&quot;\", \"'\": \"&#39;\" })[character]!,\n );\n}\n\nconst runtimeCache = new Map<string, Promise<string>>();\n\n/**\n * Load one of the browser-side runtimes (`host-entry`, `sandbox-entry`) as a\n * string to inline into a page.\n *\n * Installed, the built IIFE is a declared package export, so ask the module\n * resolver for it. Walking from `import.meta.url` breaks the moment a bundler\n * hoists this module into a shared chunk at a different depth — which is what\n * tsup does, leaving it looking in dist/ while the file sits in dist/dev/.\n */\nfunction loadRuntime(name: \"host-entry\" | \"sandbox-entry\"): Promise<string> {\n const cached = runtimeCache.get(name);\n if (cached) return cached;\n const loading = (async () => {\n try {\n return await readFile(\n fileURLToPath(import.meta.resolve(`mountly-mcp/dev/${name}.js`)),\n \"utf8\",\n );\n } catch {\n // Running from source in this repo, where nothing is built yet.\n }\n const entry = fileURLToPath(new URL(`./${name}.ts`, import.meta.url));\n if (!existsSync(entry)) {\n throw new Error(\n `mountly-mcp dev: ${name} runtime missing. Expected the packaged 'mountly-mcp/dev/${name}.js' export, or ${entry} when running from source.`,\n );\n }\n const { build } = await import(\"vite\");\n const result = await build({\n configFile: false,\n logLevel: \"silent\",\n build: {\n write: false,\n target: \"es2022\",\n minify: false,\n lib: { entry, formats: [\"iife\"], name: \"__mountlyMcpDevRuntime\" },\n },\n });\n const outputs = Array.isArray(result) ? result : [result];\n const chunk = outputs\n .flatMap((output) => (\"output\" in output ? output.output : []))\n .find((item) => item.type === \"chunk\");\n if (!chunk || chunk.type !== \"chunk\")\n throw new Error(`mountly-mcp dev: failed to bundle ${name}`);\n return chunk.code;\n })();\n runtimeCache.set(name, loading);\n return loading;\n}\n\nfunction listenOnFreePort(server: Server, port: number): Promise<number> {\n return new Promise((resolvePort, reject) => {\n const attempt = (candidate: number): void => {\n // Listeners are paired and torn down together: `listen()`'s callback form\n // leaves a stale one attached across retries, which then resolves with\n // the port that was already taken.\n const onError = (error: NodeJS.ErrnoException): void => {\n server.removeListener(\"listening\", onListening);\n // ponytail: linear probe, fine for a dev tool on a developer's laptop.\n if (error.code === \"EADDRINUSE\" && candidate < port + 50) attempt(candidate + 1);\n else reject(error);\n };\n const onListening = (): void => {\n server.removeListener(\"error\", onError);\n const address = server.address();\n resolvePort(typeof address === \"object\" && address !== null ? address.port : candidate);\n };\n server.once(\"error\", onError);\n server.once(\"listening\", onListening);\n server.listen(candidate);\n };\n attempt(port);\n });\n}\n\nexport async function startDevHost(options: DevHostOptions): Promise<DevHost> {\n const { htmlPath, fixtures = {}, toolInput = {}, callTool } = options;\n\n const metaPath = `${htmlPath}.meta.json`;\n const initialMeta = JSON.parse(await readFile(metaPath, \"utf8\")) as McpResourceDeclaration;\n const toolName = options.toolName ?? initialMeta.name;\n const [hostRuntime, sandboxRuntime] = await Promise.all([\n loadRuntime(\"host-entry\"),\n loadRuntime(\"sandbox-entry\"),\n ]);\n\n // Bumped on reload(); the browser polls it and reloads when it changes. The\n // widget HTML is read per request rather than baked into the page, so a\n // rebuild is picked up with no server restart.\n let version = 1;\n\n // The two servers reference each other's origin, and each only needs the\n // other's once a request arrives — so the sandbox reads this after the host\n // has bound its port.\n let hostOrigin = \"\";\n\n const sandboxServer = createServer((_req, res) => {\n res.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\", \"Cache-Control\": \"no-store\" });\n res.end(sandboxProxyShell(hostOrigin, sandboxRuntime));\n });\n const sandboxPort = await listenOnFreePort(\n sandboxServer,\n options.sandboxPort ?? (options.hostPort ?? 5179) + 1,\n );\n const sandboxOrigin = `http://localhost:${sandboxPort}`;\n\n const hostServer = createServer(async (req, res) => {\n const path = new URL(req.url ?? \"/\", \"http://localhost\").pathname;\n const send = (status: number, type: string, body: string | Buffer): void => {\n res.writeHead(status, { \"Content-Type\": type, \"Cache-Control\": \"no-store\" });\n res.end(body);\n };\n try {\n if (path === \"/call\" && req.method === \"POST\") {\n if (!callTool) return send(400, \"text/plain\", \"no server connected\");\n const body = await new Promise<string>((done, fail) => {\n let raw = \"\";\n req.on(\"data\", (chunk) => (raw += chunk));\n req.on(\"end\", () => done(raw));\n req.on(\"error\", fail);\n });\n const { name, arguments: args } = JSON.parse(body) as { name: string; arguments?: unknown };\n // Tool failures are the view's problem to render, not the dev server's\n // to crash on, so they come back as a normal result.\n const result = await callTool(name, args).catch((error: unknown) => ({\n isError: true,\n content: [{ type: \"text\", text: error instanceof Error ? error.message : String(error) }],\n }));\n return send(200, \"application/json\", JSON.stringify(result));\n }\n if (path === \"/\") return send(200, \"text/html; charset=utf-8\", hostPage());\n if (path === \"/host.js\") return send(200, \"text/javascript; charset=utf-8\", hostRuntime);\n if (path === \"/version\") return send(200, \"application/json\", String(version));\n if (path === \"/widget.html\")\n return send(200, \"text/plain; charset=utf-8\", await readFile(htmlPath, \"utf8\"));\n if (path === \"/widget.meta.json\")\n return send(200, \"application/json\", await readFile(metaPath, \"utf8\"));\n send(404, \"text/plain\", \"not found\");\n } catch (error) {\n // A rebuild in flight can briefly leave the file missing; say so rather\n // than crashing the dev server.\n send(500, \"text/plain\", error instanceof Error ? error.message : String(error));\n }\n });\n let hostPort: number;\n try {\n hostPort = await listenOnFreePort(hostServer, options.hostPort ?? 5179);\n } catch (caught) {\n await new Promise<void>((done) => sandboxServer.close(() => done()));\n throw caught;\n }\n hostOrigin = `http://localhost:${hostPort}`;\n\n function hostPage(): string {\n return devHostHtml({\n toolName,\n sandboxOrigin,\n fixtures,\n toolInput,\n uri: initialMeta.uri,\n hasServer: callTool !== undefined,\n });\n }\n\n return {\n hostUrl: hostOrigin,\n sandboxUrl: sandboxOrigin,\n reload() {\n version += 1;\n },\n async close() {\n await Promise.all([\n new Promise<void>((done) => hostServer.close(() => done())),\n new Promise<void>((done) => sandboxServer.close(() => done())),\n ]);\n },\n };\n}\n\ninterface HostPageOptions {\n toolName: string;\n sandboxOrigin: string;\n fixtures: Record<string, unknown>;\n toolInput: Record<string, unknown>;\n uri: string;\n hasServer: boolean;\n}\n\nfunction devHostHtml(options: HostPageOptions): string {\n const { toolName, sandboxOrigin, fixtures, toolInput, uri, hasServer } = options;\n const buttons = Object.keys(fixtures)\n .map(\n (name, index) =>\n `<button class=\"btn\" data-fixture=\"${escapeHtml(name)}\"${index === 0 ? ' data-active=\"true\"' : \"\"}>${escapeHtml(name)}</button>`,\n )\n .join(\"\\n\");\n\n return `<!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<title>mountly-mcp dev · ${escapeHtml(toolName)}</title>\n<style>\n :root { color-scheme:light; --bg:#f6f7f9; --fg:#0b0c0f; --muted:#5c6675; --accent:#1d4ed8; --border:#dcdfe5; }\n :root[data-theme=\"dark\"] { color-scheme:dark; --bg:#0b0c0f; --fg:#e6e9ef; --muted:#9aa3b2; --accent:#7aa2ff; --border:#252a33; }\n * { box-sizing:border-box; }\n body { margin:0; min-height:100vh; background:var(--bg); color:var(--fg); font:14px/1.5 -apple-system,BlinkMacSystemFont,\"Segoe UI\",system-ui,sans-serif; }\n header { padding:18px 24px; border-bottom:1px solid var(--border); display:flex; align-items:center; gap:12px; flex-wrap:wrap; }\n header h1 { margin:0; font-size:16px; font-weight:600; }\n header code { color:var(--muted); font-size:12px; }\n #fixtures { display:flex; gap:8px; flex-wrap:wrap; }\n .spacer { flex:1; }\n .btn { appearance:none; border:1px solid var(--border); background:transparent; color:var(--fg); padding:6px 12px; border-radius:6px; font:inherit; cursor:pointer; }\n .btn:hover { border-color:var(--accent); color:var(--accent); }\n .btn[data-active=\"true\"] { background:var(--accent); color:white; border-color:var(--accent); }\n main { display:grid; grid-template-columns:minmax(420px,1fr) 360px; gap:20px; padding:24px; align-items:start; }\n iframe { width:100%; height:460px; border:1px solid var(--border); border-radius:12px; background:white; }\n .panel { border:1px solid var(--border); border-radius:12px; padding:16px; }\n .panel + .panel { margin-top:12px; }\n .panel h2 { margin:0 0 8px; font-size:13px; text-transform:uppercase; letter-spacing:.08em; color:var(--muted); }\n pre { margin:0; padding:10px; border-radius:8px; font:12px/1.45 ui-monospace,Menlo,Consolas,monospace; overflow:auto; max-height:200px; }\n .log { font:11px/1.5 ui-monospace,Menlo,Consolas,monospace; color:var(--muted); white-space:pre-wrap; max-height:280px; overflow:auto; }\n @media (max-width:880px) { main { grid-template-columns:1fr; padding:16px; } }\n</style>\n</head>\n<body>\n<header>\n <h1>${escapeHtml(toolName)}</h1>\n <code>${escapeHtml(uri)}</code>\n <span class=\"spacer\"></span>\n <div id=\"fixtures\">${buttons}</div>\n <button class=\"btn\" id=\"theme\" type=\"button\">Theme</button>\n <button class=\"btn\" id=\"teardown\" type=\"button\">Teardown</button>\n</header>\n<main>\n <iframe id=\"sandbox\" sandbox=\"allow-scripts allow-same-origin\" title=\"mountly-mcp sandbox proxy\"></iframe>\n <div>\n <section class=\"panel\">\n <h2>Last structuredContent</h2>\n <pre id=\"payload\">(none yet)</pre>\n </section>\n <section class=\"panel\">\n <h2>Channel log</h2>\n <div class=\"log\" id=\"log\"></div>\n </section>\n </div>\n</main>\n<script>\nglobalThis.__mountlyMcpDevHost__ = ${serializeInlineScriptValue({\n toolName,\n sandboxOrigin,\n fixtures,\n toolInput,\n uri,\n hasServer,\n sandboxPath: \"/sandbox-proxy.html\",\n })};\nconst HAS_SERVER = ${hasServer ? \"true\" : \"false\"};\n</script>\n<script src=\"/host.js\"></script>\n</body>\n</html>\n`;\n}\n/**\n * The proxy document: a shell around the compiled sandbox runtime.\n *\n * Kept separate from {@link sandboxProxyHtml} so the dev server can load the\n * runtime once at startup and still stamp in the host origin per request,\n * which it only learns after binding a port.\n */\nfunction sandboxProxyShell(hostOrigin: string, runtime: string): string {\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>mountly-mcp sandbox proxy</title>\n<style>\n html, body { margin: 0; padding: 0; width: 100%; height: 100%; background: transparent; }\n #inner { width: 100%; height: 100%; border: 0; background: white; }\n</style>\n</head>\n<body>\n<script>globalThis.__mountlyMcpSandbox__ = ${serializeInlineScriptValue({ hostOrigin })};</script>\n<script>${escapeInlineScript(runtime)}</script>\n</body>\n</html>\n`;\n}\n\n/**\n * The MCP Apps sandbox proxy document (spec §8.4), ready to serve from an\n * origin distinct from the host page.\n *\n * Exported because this is the security boundary — it builds the CSP from the\n * sidecar and decides what the view may execute and reach. Anything standing\n * up a host, including the example harnesses in this repo, should serve this\n * rather than keep a copy that drifts from it.\n */\nexport async function sandboxProxyHtml(hostOrigin: string): Promise<string> {\n return sandboxProxyShell(hostOrigin, await loadRuntime(\"sandbox-entry\"));\n}\n\nexport { connectMcpServer, type ConnectedMcpServer } from \"./connect-server.js\";\n"],"mappings":";;;;;;AAeA,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AACzB,SAAS,oBAAiC;AAC1C,SAAS,qBAAqB;AAuC9B,SAAS,WAAW,OAAuB;AACzC,SAAO,MAAM;AAAA,IACX;AAAA,IACA,CAAC,eACE,EAAE,KAAK,SAAS,KAAK,QAAQ,KAAK,QAAQ,KAAK,UAAU,KAAK,QAAQ,GAAG,SAAS;AAAA,EACvF;AACF;AAEA,IAAM,eAAe,oBAAI,IAA6B;AAWtD,SAAS,YAAY,MAAuD;AAC1E,QAAM,SAAS,aAAa,IAAI,IAAI;AACpC,MAAI,OAAQ,QAAO;AACnB,QAAM,WAAW,YAAY;AAC3B,QAAI;AACF,aAAO,MAAM;AAAA,QACX,cAAc,YAAY,QAAQ,mBAAmB,IAAI,KAAK,CAAC;AAAA,QAC/D;AAAA,MACF;AAAA,IACF,QAAQ;AAAA,IAER;AACA,UAAM,QAAQ,cAAc,IAAI,IAAI,KAAK,IAAI,OAAO,YAAY,GAAG,CAAC;AACpE,QAAI,CAAC,WAAW,KAAK,GAAG;AACtB,YAAM,IAAI;AAAA,QACR,oBAAoB,I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A;AAAA;AAAA;AAAA;AAAA;AAMjD;AAQA,SAAS,kBAAkB,YAAoB,SAAyB;AACtE,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,6CAWoC,2BAA2B,EAAE,WAAW,CAAC,CAAC;AAAA,UAC7E,mBAAmB,OAAO,CAAC;AAAA;AAAA;AAAA;AAIrC;AAWA,eAAsB,iBAAiB,YAAqC;AAC1E,SAAO,kBAAkB,YAAY,MAAM,YAAY,eAAe,CAAC;AACzE;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/react/context.ts","../src/react/hooks.ts","../src/react/create-widget.ts"],"sourcesContent":["import { createContext } from \"react\";\nimport type {\n App,\n McpUiHostContext,\n McpUiToolInputNotification,\n McpUiToolInputPartialNotification,\n McpUiToolResultNotification,\n} from \"@modelcontextprotocol/ext-apps\";\n\n/**\n * Shared per-widget context. The bridge populates this on each mount/update,\n * so consumers can synchronously read the initial values (no event subscription\n * race) and the React tree re-renders when the bridge calls `update()`.\n */\nexport interface McpContextValue {\n app: App;\n toolInput?: McpUiToolInputNotification[\"params\"];\n toolInputPartial?: McpUiToolInputPartialNotification[\"params\"];\n toolResult?: McpUiToolResultNotification[\"params\"];\n hostContext?: McpUiHostContext;\n}\n\nexport const McpContext = createContext<McpContextValue | null>(null);\nMcpContext.displayName = \"McpContext\";\n","import { useContext } from \"react\";\nimport {\n useAutoResize as useAutoResizeBase,\n useDocumentTheme as useDocumentThemeBase,\n useHostFonts as useHostFontsBase,\n useHostStyleVariables as useHostStyleVariablesBase,\n useHostStyles as useHostStylesBase,\n} from \"@modelcontextprotocol/ext-apps/react\";\nimport type {\n App,\n McpUiDisplayMode,\n McpUiHostContext,\n McpUiUpdateModelContextRequest,\n} from \"@modelcontextprotocol/ext-apps\";\nimport { McpContext } from \"./context.js\";\n\nfunction useEnsuredContext() {\n const ctx = useContext(McpContext);\n if (!ctx) {\n throw new Error(\n \"mountly-mcp/react: useMcpHost/useToolInput/etc must be used inside a widget wrapped with createMcpWidget().\",\n );\n }\n return ctx;\n}\n\n/** The view-side ext-apps App. Use this to call server tools, send messages, open links, etc. */\nexport function useMcpHost(): App {\n return useEnsuredContext().app;\n}\n\n/** Complete notification params; read the tool arguments from `.arguments`. */\nexport function useToolInput<T = unknown>(): T | undefined {\n return useEnsuredContext().toolInput as T | undefined;\n}\n\n/**\n * Streaming tool arguments (`ui/notifications/tool-input-partial`), present only\n * when the bridge runs with `streamToolInput`. Best-effort recovered JSON —\n * fields may be missing or change between notifications, so render loading\n * states from it, never critical operations. Undefined once the complete\n * {@link useToolInput} arrives.\n */\nexport function useToolInputPartial<T = unknown>(): Partial<T> | undefined {\n return useEnsuredContext().toolInputPartial as Partial<T> | undefined;\n}\n\n/** Complete MCP tool result; structured data is available at `.structuredContent`. */\nexport function useToolResult<T = unknown>(): T | undefined {\n return useEnsuredContext().toolResult as T | undefined;\n}\n\n/** Latest host context snapshot (theme, styles, displayMode, container dimensions, etc.). */\nexport function useHostContext(): McpUiHostContext | undefined {\n return useEnsuredContext().hostContext;\n}\n\n/** Current display mode reported by the host. */\nexport function useDisplayMode(): McpUiDisplayMode | undefined {\n return useHostContext()?.displayMode;\n}\n\n/**\n * Request a display mode change, resolving to the mode the host actually\n * applied — which the spec allows to differ from the one asked for.\n *\n * Modes the host didn't list in `availableDisplayModes` are never requested\n * (the spec requires views to check first); the current mode comes back\n * unchanged instead.\n */\nexport function useRequestDisplayMode(): (\n mode: McpUiDisplayMode,\n) => Promise<McpUiDisplayMode | undefined> {\n const { app, hostContext } = useEnsuredContext();\n return async (mode) => {\n const available = hostContext?.availableDisplayModes;\n if (available && !available.includes(mode)) return hostContext?.displayMode;\n const result = await app.requestDisplayMode({ mode });\n return result.mode;\n };\n}\n\n/** Apply host CSS variables (and react to host-context changes). */\nexport function useHostStyleVariables(): void {\n const { app, hostContext } = useEnsuredContext();\n useHostStyleVariablesBase(app, hostContext ?? null);\n}\n\n/** Apply host-provided `@font-face`/`@import` rules. */\nexport function useHostFonts(): void {\n const { app, hostContext } = useEnsuredContext();\n useHostFontsBase(app, hostContext ?? null);\n}\n\n/** One-shot helper: apply both host style variables and host fonts. */\nexport function useHostStyles(): void {\n const { app, hostContext } = useEnsuredContext();\n useHostStylesBase(app, hostContext ?? null);\n}\n\n/** Track the document theme reactively. */\nexport function useDocumentTheme() {\n return useDocumentThemeBase();\n}\n\n/**\n * Return a function that calls `app.updateModelContext(params)`.\n *\n * Context updates are available to the model in future turns without\n * triggering an immediate response. Only the last update is kept.\n */\nexport function useUpdateModelContext(): (\n params: McpUiUpdateModelContextRequest[\"params\"],\n) => Promise<void> {\n const { app } = useEnsuredContext();\n return async (params) => {\n await app.updateModelContext(params);\n };\n}\n\n/** Manually control auto-resize (rarely needed — the bridge calls setupSizeChangedNotifications by default). */\nexport function useAutoResize(...args: Parameters<typeof useAutoResizeBase>) {\n return useAutoResizeBase(...args);\n}\n","import { createElement, type ComponentType } from \"react\";\nimport { createWidget } from \"mountly-react\";\nimport type { AdapterOptions, WidgetModule } from \"mountly/adapter\";\nimport type { McpWidgetProps } from \"../index.js\";\nimport { McpContext, type McpContextValue } from \"./context.js\";\n\n/**\n * Wraps a React component as a mountly `WidgetModule` driven by the\n * mountly-mcp bridge. The bridge passes spec-defined props\n * (`mcp` / `toolInput` / `toolResult` / `hostContext`) on each `mount` /\n * `update`. The wrapper consumes those bridge props and exposes them through\n * `useMcpHost()` and the other hooks from `mountly-mcp/react`; the wrapped\n * component's own props remain unchanged.\n */\nexport function createMcpWidget<P extends object>(\n Component: ComponentType<P>,\n options?: AdapterOptions,\n): WidgetModule {\n const Wrapped = (props: P & McpWidgetProps) => {\n const { mcp, toolInput, toolInputPartial, toolResult, hostContext, ...rest } =\n props as McpWidgetProps & P;\n const value: McpContextValue = {\n app: mcp,\n toolInput,\n toolInputPartial,\n toolResult,\n hostContext,\n };\n return createElement(\n McpContext.Provider,\n { value },\n createElement(Component as ComponentType, rest as P),\n );\n };\n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AACpC,QAAM,EAAE,KAAK,YAAY,IAAI,kBAAkB;AAC/C,oBAAkB,KAAK,eAAe,IAAI;AAC5C;AAGO,SAAS,mBAAmB;AACjC,SAAO,qBAAqB;AAC9B;AAQO,SAAS,wBAEG;AACjB,QAAM,EAAE,IAAI,IAAI,kBAAkB;AAClC,SAAO,OAAO,WAAW;AACvB,UAAM,IAAI,mBAAmB,MAAM;AAAA,EACrC;AACF;AAGO,SAAS,iBAAiB,MAA4C;AAC3E,SAAO,kBAAkB,GAAG,IAAI;AAClC;;;AC3HA,SAAS,qBAAyC;AAClD,SAAS,oBAAoB;AAatB,SAAS,gBACd,WACA,SACc;AACd,QAAM,UAAU,CAAC,UAA8B;AAC7C,UAAM,EAAE,KAAK,WAAW,kBAAkB,YAAY,aAAa,GAAG,KAAK,IACzE;AACF,UAAM,QAAyB;AAAA,MAC7B,KAAK;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACA,WAAO;AAAA,MACL,WAAW;AAAA,MACX,EAAE,MAAM;AAAA,MACR,cAAc,WAA4B,IAAS;AAAA,IACrD;AAAA,EACF;AACA,SAAO,aAAa,SAA8C,OAAO;AAC3E;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/bridge/index.ts"],"sourcesContent":["/**\n * View-side bridge that turns an MCP Apps `App` into a mountly `WidgetModule`\n * lifecycle. The full spec handshake — `ui/initialize`,\n * `ui/notifications/initialized`, `ui/notifications/tool-input(-partial)`,\n * `ui/notifications/tool-result`, `ui/notifications/tool-cancelled`,\n * `ui/notifications/host-context-changed`, `ui/resource-teardown`,\n * `ui/notifications/size-changed` — is delegated to ext-apps's `App`.\n */\nimport {\n App,\n PostMessageTransport,\n type McpUiAppCapabilities,\n type McpUiDisplayMode,\n type McpUiToolInputNotification,\n type McpUiToolInputPartialNotification,\n type McpUiToolResultNotification,\n} from \"@modelcontextprotocol/ext-apps\";\nimport type { WidgetModule } from \"mountly/adapter\";\nimport { MCP_ERROR_CODES } from \"../schema.js\";\nimport type { McpWidgetProps } from \"../types.js\";\n\nexport interface RunBridgeOptions {\n /** Pre-constructed App (used by jsdom tests); otherwise one is created here. */\n app?: App;\n widget: WidgetModule;\n container: Element;\n /**\n * If true (default), mount is deferred until the first tool-result arrives;\n * the widget renders against `{ toolInput, toolResult, hostContext, mcp }`\n * props on each notification.\n *\n * If false, mount fires immediately after `ui/initialize` with `{ mcp }`\n * only — for \"stateless\" views that drive themselves via `mcp.callServerTool`.\n */\n awaitToolResult?: boolean;\n /**\n * Render progressive states from `ui/notifications/tool-input-partial`.\n *\n * Off by default — the spec lets views ignore partials, and they carry\n * best-effort recovered JSON that MUST NOT drive critical operations. When\n * on, partials arrive as `toolInputPartial` (mounting the widget early if\n * needed) and are cleared once the complete `tool-input` lands.\n */\n streamToolInput?: boolean;\n /** Display modes this view supports. Declared to the host during `ui/initialize`. */\n availableDisplayModes?: ReadonlyArray<McpUiDisplayMode>;\n /** App identity sent during `ui/initialize`. */\n appInfo?: { name: string; version: string };\n /** Override for tests; defaults to `window.addEventListener('beforeunload', ...)`. */\n onTeardown?: (handler: () => void) => () => void;\n}\n\nexport interface RunningBridge {\n /** Resolves once `ui/initialize` handshake completes and the first mount (or deferred mount) is wired. */\n ready: Promise<void>;\n /** The underlying App; exposed for hosts that want to drive the view directly. */\n app: App;\n /** Synchronously triggers teardown. */\n stop(): void;\n}\n\n/**\n * `data-mountly-mcp-state` is the View's machine-readable outcome, read by\n * `verify --render`. It only ever moves forward — `mounted` once the widget\n * has mounted, `error` if the boundary replaced it — so a state written here\n * can never be clobbered by a later lifecycle step.\n */\nfunction renderErrorBoundary(container: Element, code: string, message?: string): void {\n container.setAttribute(\"data-mountly-mcp-state\", \"error\");\n const doc = container.ownerDocument;\n if (!doc) return;\n const errorDiv = doc.createElement(\"div\");\n errorDiv.setAttribute(\"data-mountly-mcp-error\", code);\n if (message !== undefined) errorDiv.textContent = message;\n container.innerHTML = \"\";\n container.appendChild(errorDiv);\n}\n\nexport function runBridge(options: RunBridgeOptions): RunningBridge {\n const {\n widget,\n container,\n awaitToolResult = true,\n streamToolInput = false,\n availableDisplayModes = [\"inline\"],\n appInfo = { name: \"mountly-mcp\", version: \"0.0.0\" },\n } = options;\n\n const appCapabilities: McpUiAppCapabilities = {\n availableDisplayModes: [...availableDisplayModes],\n };\n\n const app = options.app ?? new App(appInfo, appCapabilities);\n\n let toolInput: McpUiToolInputNotification[\"params\"] | undefined;\n let toolInputPartial: McpUiToolInputPartialNotification[\"params\"] | undefined;\n let toolResult: McpUiToolResultNotification[\"params\"] | undefined;\n let mounted = false;\n let stopped = false;\n let pending: Promise<void> = Promise.resolve();\n\n function currentProps(): McpWidgetProps {\n return {\n mcp: app,\n toolInput,\n toolInputPartial,\n toolResult,\n hostContext: app.getHostContext(),\n };\n }\n\n function notifyError(code: string, error: unknown): void {\n const message = error instanceof Error ? error.message : String(error);\n try {\n void app.sendLog({ level: \"error\", data: { code, message } }).catch(() => undefined);\n } catch {\n // ignore — log channel may not be ready\n }\n renderErrorBoundary(container, code, message);\n }\n\n function renderWith(props: McpWidgetProps): Promise<void> {\n pending = pending.then(async () => {\n if (stopped) return;\n try {\n if (!mounted) {\n const r = widget.mount(container, props);\n if (r instanceof Promise) await r;\n mounted = true;\n container.setAttribute(\"data-mountly-mcp-state\", \"mounted\");\n } else if (widget.update) {\n const r = widget.update(container, props);\n if (r instanceof Promise) await r;\n } else {\n await widget.unmount(container);\n mounted = false;\n const r = widget.mount(container, props);\n if (r instanceof Promise) await r;\n mounted = true;\n }\n } catch (error) {\n notifyError(MCP_ERROR_CODES.WIDGET_MOUNT_THREW, error);\n }\n });\n return pending;\n }\n\n async function unmountWidget(): Promise<void> {\n await pending;\n if (!mounted) return;\n mounted = false;\n await widget.unmount(container);\n }\n\n // Event handlers MUST be registered before connect() — ext-apps will refuse\n // to attach handlers retroactively after the initialize handshake completes.\n const handleToolInput = (params: McpUiToolInputNotification[\"params\"]) => {\n toolInput = params;\n toolInputPartial = undefined;\n if (!awaitToolResult) return;\n if (mounted || toolResult !== undefined) void renderWith(currentProps());\n };\n\n const handleToolInputPartial = (params: McpUiToolInputPartialNotification[\"params\"]) => {\n // Views MAY ignore partial input per spec; opt in with `streamToolInput`.\n // Consumers wanting finer control can subscribe via app.addEventListener.\n if (!streamToolInput) return;\n toolInputPartial = params;\n void renderWith(currentProps());\n };\n\n const handleToolResult = (params: McpUiToolResultNotification[\"params\"]) => {\n toolResult = params;\n void renderWith(currentProps());\n };\n\n const handleToolCancelled = () => {\n void renderWith(currentProps());\n };\n\n const handleHostContextChanged = () => {\n if (mounted) void renderWith(currentProps());\n };\n\n app.addEventListener(\"toolinput\", handleToolInput);\n app.addEventListener(\"toolinputpartial\", handleToolInputPartial);\n app.addEventListener(\"toolresult\", handleToolResult);\n app.addEventListener(\"toolcancelled\", handleToolCancelled);\n app.addEventListener(\"hostcontextchanged\", handleHostContextChanged);\n\n const previousTeardown = app.onteardown;\n const bridgeTeardown: NonNullable<typeof app.onteardown> = async (params, extra) => {\n stopped = true;\n detachTeardown();\n detachAppHandlers();\n await unmountWidget();\n return (await previousTeardown?.(params, extra)) ?? {};\n };\n app.onteardown = bridgeTeardown;\n\n function detachAppHandlers(): void {\n app.removeEventListener(\"toolinput\", handleToolInput);\n app.removeEventListener(\"toolinputpartial\", handleToolInputPartial);\n app.removeEventListener(\"toolresult\", handleToolResult);\n app.removeEventListener(\"toolcancelled\", handleToolCancelled);\n app.removeEventListener(\"hostcontextchanged\", handleHostContextChanged);\n if (app.onteardown === bridgeTeardown) app.onteardown = previousTeardown;\n }\n\n const ready = (async () => {\n try {\n if (!options.app) {\n // App.connect() defaults to PostMessageTransport(window.parent, window.parent)\n // and owns automatic resize setup.\n await app.connect();\n }\n\n if (!awaitToolResult) {\n await renderWith(currentProps());\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const code = /timeout/i.test(message)\n ? MCP_ERROR_CODES.INITIALIZE_TIMEOUT\n : MCP_ERROR_CODES.INITIALIZE_FAILED;\n notifyError(code, error);\n throw error;\n }\n })();\n\n let detachTeardown: () => void = () => undefined;\n\n function stopBridge(): void {\n if (stopped) return;\n stopped = true;\n detachTeardown();\n detachAppHandlers();\n void unmountWidget();\n if (!options.app) void app.close().catch(() => undefined);\n }\n\n detachTeardown =\n options.onTeardown?.(stopBridge) ??\n (typeof window !== \"undefined\"\n ? (() => {\n const h = () => stopBridge();\n window.addEventListener(\"beforeunload\", h);\n return () => window.removeEventListener(\"beforeunload\", h);\n })()\n : () => undefined);\n\n return {\n ready,\n app,\n stop: stopBridge,\n };\n}\n\nexport { App, PostMessageTransport };\nexport type {\n McpUiAppCapabilities,\n McpUiHostCapabilities,\n McpUiHostContext,\n McpUiToolInputNotification,\n McpUiToolInputPartialNotification,\n McpUiToolResultNotification,\n McpUiToolCancelledNotification,\n McpUiHostContextChangedNotification,\n} from \"@modelcontextprotocol/ext-apps\";\n"],"mappings":";;;;;AAQA;AAAA,EACE;AAAA,EACA;AAAA,OAMK;AAmDP,SAAS,oBAAoB,WAAoB,MAAc,SAAwB;AACrF,YAAU,aAAa,0BAA0B,OAAO;AACxD,QAAM,MAAM,UAAU;AACtB,MAAI,CAAC,IAAK;AACV,QAAM,WAAW,IAAI,cAAc,KAAK;AACxC,WAAS,aAAa,0BAA0B,IAAI;AACpD,MAAI,YAAY,OAAW,UAAS,cAAc;AAClD,YAAU,YAAY;AACtB,YAAU,YAAY,QAAQ;AAChC;AAEO,SAAS,UAAU,SAA0C;AAClE,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA,kBAAkB;AAAA,IAClB,kBAAkB;AAAA,IAClB,wBAAwB,CAAC,QAAQ;AAAA,IACjC,UAAU,EAAE,MAAM,eAAe,SAAS,QAAQ;AAAA,EACpD,IAAI;AAEJ,QAAM,kBAAwC;AAAA,IAC5C,uBAAuB,CAAC,GAAG,qBAAqB;AAAA,EAClD;AAEA,QAAM,MAAM,QAAQ,OAAO,IAAI,IAAI,SAAS,eAAe;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M,IAAI,QAAQ;AAAA,MACpB;AAEA,UAAI,CAAC,iBAAiB;AACpB,cAAM,WAAW,aAAa,CAAC;AAAA,MACjC;AAAA,IACF,SAAS,OAAO;AACd,YAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,YAAM,OAAO,WAAW,KAAK,OAAO,IAChC,gBAAgB,qBAChB,gBAAgB;AACpB,kBAAY,MAAM,KAAK;AACvB,YAAM;AAAA,IACR;AAAA,EACF,GAAG;AAEH,MAAI,iBAA6B,MAAM;AAEvC,WAAS,aAAmB;AAC1B,QAAI,QAAS;AACb,cAAU;AACV,mBAAe;AACf,sBAAkB;AAClB,SAAK,cAAc;AACnB,QAAI,CAAC,QAAQ,IAAK,MAAK,IAAI,MAAM,EAAE,MAAM,MAAM,MAAS;AAAA,EAC1D;AAEA,mBACE,QAAQ,aAAa,UAAU,MAC9B,OAAO,WAAW,eACd,MAAM;AACL,UAAM,IAAI,MAAM,WAAW;AAC3B,WAAO,iBAAiB,gBAAgB,CAAC;AACzC,WAAO,MAAM,OAAO,oBAAoB,gBAAgB,CAAC;AAAA,EAC3D,GAAG,IACH,MAAM;AAEZ,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,MAAM;AAAA,EACR;AACF;","names":[]}
@@ -1,11 +0,0 @@
1
- import { type ComponentType } from "react";
2
- import type { AdapterOptions, WidgetModule } from "mountly/adapter";
3
- /**
4
- * Wraps a React component as a mountly `WidgetModule` driven by the
5
- * mountly-mcp bridge. The bridge passes spec-defined props
6
- * (`mcp` / `toolInput` / `toolResult` / `hostContext`) on each `mount` /
7
- * `update`. The wrapper consumes those bridge props and exposes them through
8
- * `useMcpHost()` and the other hooks from `mountly-mcp/react`; the wrapped
9
- * component's own props remain unchanged.
10
- */
11
- export declare function createMcpWidget<P extends object>(Component: ComponentType<P>, options?: AdapterOptions): WidgetModule;