@dudko.dev/agent-web-ui 0.0.1 → 0.0.3

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 (265) hide show
  1. package/README.md +94 -3
  2. package/dist/canvas.cjs +0 -1
  3. package/dist/canvas.js +1 -2
  4. package/dist/{chunk-EL2YCROY.js → chunk-D64VLIRY.js} +0 -1
  5. package/dist/chunk-G7LQTOA2.js +1439 -0
  6. package/dist/{chunk-4EHUITGU.js → chunk-S5AHUAFG.js} +6 -1
  7. package/dist/{chunk-7O64ZI6Z.js → chunk-TJBGZM6D.js} +0 -1
  8. package/dist/{chunk-P2F2P3JC.js → chunk-UNIXGP4N.js} +6 -1
  9. package/dist/{chunk-A55Q377T.js → chunk-V33T6VX3.js} +6 -1
  10. package/dist/{chunk-TPK25QGK.js → chunk-VZCQXE3P.js} +6 -1
  11. package/dist/{chunk-GB7RZJMG.js → chunk-WEYQMUKY.js} +0 -1
  12. package/dist/{chunk-KZQB35LS.js → chunk-Y6QYUFSC.js} +0 -1
  13. package/dist/controller.cjs +1890 -0
  14. package/dist/controller.d.cts +253 -0
  15. package/dist/controller.d.ts +253 -0
  16. package/dist/controller.js +481 -0
  17. package/dist/{en-CcNUz2tN.d.ts → en-Dg2MtzcJ.d.cts} +6 -0
  18. package/dist/{en-CcNUz2tN.d.cts → en-Dg2MtzcJ.d.ts} +6 -0
  19. package/dist/index.cjs +133 -1
  20. package/dist/index.d.cts +82 -4
  21. package/dist/index.d.ts +82 -4
  22. package/dist/index.js +144 -1422
  23. package/dist/{labels-UuWI7wPo.d.ts → labels-CmiTBLWD.d.cts} +68 -100
  24. package/dist/{labels-D5BrHct4.d.cts → labels-DH1ESUtm.d.ts} +68 -100
  25. package/dist/locales/be.cjs +12 -1
  26. package/dist/locales/be.d.cts +4 -2
  27. package/dist/locales/be.d.ts +4 -2
  28. package/dist/locales/be.js +7 -2
  29. package/dist/locales/bg.cjs +12 -1
  30. package/dist/locales/bg.d.cts +4 -2
  31. package/dist/locales/bg.d.ts +4 -2
  32. package/dist/locales/bg.js +7 -2
  33. package/dist/locales/ca.cjs +12 -1
  34. package/dist/locales/ca.d.cts +4 -2
  35. package/dist/locales/ca.d.ts +4 -2
  36. package/dist/locales/ca.js +7 -2
  37. package/dist/locales/cs.cjs +12 -1
  38. package/dist/locales/cs.d.cts +4 -2
  39. package/dist/locales/cs.d.ts +4 -2
  40. package/dist/locales/cs.js +7 -2
  41. package/dist/locales/da.cjs +12 -1
  42. package/dist/locales/da.d.cts +4 -2
  43. package/dist/locales/da.d.ts +4 -2
  44. package/dist/locales/da.js +7 -2
  45. package/dist/locales/de.cjs +12 -1
  46. package/dist/locales/de.d.cts +4 -2
  47. package/dist/locales/de.d.ts +4 -2
  48. package/dist/locales/de.js +7 -2
  49. package/dist/locales/el.cjs +12 -1
  50. package/dist/locales/el.d.cts +4 -2
  51. package/dist/locales/el.d.ts +4 -2
  52. package/dist/locales/el.js +7 -2
  53. package/dist/locales/en.cjs +12 -1
  54. package/dist/locales/en.d.cts +4 -2
  55. package/dist/locales/en.d.ts +4 -2
  56. package/dist/locales/en.js +7 -2
  57. package/dist/locales/es-419.cjs +16 -2
  58. package/dist/locales/es-419.d.cts +4 -2
  59. package/dist/locales/es-419.d.ts +4 -2
  60. package/dist/locales/es-419.js +6 -4
  61. package/dist/locales/es.cjs +12 -1
  62. package/dist/locales/es.d.cts +4 -2
  63. package/dist/locales/es.d.ts +4 -2
  64. package/dist/locales/es.js +2 -3
  65. package/dist/locales/fi.cjs +12 -1
  66. package/dist/locales/fi.d.cts +4 -2
  67. package/dist/locales/fi.d.ts +4 -2
  68. package/dist/locales/fi.js +7 -2
  69. package/dist/locales/fr-CA.cjs +12 -1
  70. package/dist/locales/fr-CA.d.cts +4 -2
  71. package/dist/locales/fr-CA.d.ts +4 -2
  72. package/dist/locales/fr-CA.js +2 -3
  73. package/dist/locales/fr.cjs +12 -1
  74. package/dist/locales/fr.d.cts +4 -2
  75. package/dist/locales/fr.d.ts +4 -2
  76. package/dist/locales/fr.js +2 -3
  77. package/dist/locales/gn.cjs +12 -1
  78. package/dist/locales/gn.d.cts +4 -2
  79. package/dist/locales/gn.d.ts +4 -2
  80. package/dist/locales/gn.js +7 -2
  81. package/dist/locales/hr.cjs +12 -1
  82. package/dist/locales/hr.d.cts +4 -2
  83. package/dist/locales/hr.d.ts +4 -2
  84. package/dist/locales/hr.js +7 -2
  85. package/dist/locales/ht.cjs +12 -1
  86. package/dist/locales/ht.d.cts +4 -2
  87. package/dist/locales/ht.d.ts +4 -2
  88. package/dist/locales/ht.js +7 -2
  89. package/dist/locales/hu.cjs +12 -1
  90. package/dist/locales/hu.d.cts +4 -2
  91. package/dist/locales/hu.d.ts +4 -2
  92. package/dist/locales/hu.js +7 -2
  93. package/dist/locales/index.cjs +6 -1
  94. package/dist/locales/index.d.cts +6 -4
  95. package/dist/locales/index.d.ts +6 -4
  96. package/dist/locales/index.js +1 -2
  97. package/dist/locales/it.cjs +12 -1
  98. package/dist/locales/it.d.cts +4 -2
  99. package/dist/locales/it.d.ts +4 -2
  100. package/dist/locales/it.js +7 -2
  101. package/dist/locales/nb.cjs +12 -1
  102. package/dist/locales/nb.d.cts +4 -2
  103. package/dist/locales/nb.d.ts +4 -2
  104. package/dist/locales/nb.js +7 -2
  105. package/dist/locales/nl.cjs +12 -1
  106. package/dist/locales/nl.d.cts +4 -2
  107. package/dist/locales/nl.d.ts +4 -2
  108. package/dist/locales/nl.js +7 -2
  109. package/dist/locales/pl.cjs +12 -1
  110. package/dist/locales/pl.d.cts +4 -2
  111. package/dist/locales/pl.d.ts +4 -2
  112. package/dist/locales/pl.js +7 -2
  113. package/dist/locales/pt-BR.cjs +12 -1
  114. package/dist/locales/pt-BR.d.cts +4 -2
  115. package/dist/locales/pt-BR.d.ts +4 -2
  116. package/dist/locales/pt-BR.js +7 -2
  117. package/dist/locales/pt.cjs +12 -1
  118. package/dist/locales/pt.d.cts +4 -2
  119. package/dist/locales/pt.d.ts +4 -2
  120. package/dist/locales/pt.js +7 -2
  121. package/dist/locales/qu.cjs +12 -1
  122. package/dist/locales/qu.d.cts +4 -2
  123. package/dist/locales/qu.d.ts +4 -2
  124. package/dist/locales/qu.js +7 -2
  125. package/dist/locales/ro.cjs +12 -1
  126. package/dist/locales/ro.d.cts +4 -2
  127. package/dist/locales/ro.d.ts +4 -2
  128. package/dist/locales/ro.js +7 -2
  129. package/dist/locales/ru.cjs +12 -1
  130. package/dist/locales/ru.d.cts +4 -2
  131. package/dist/locales/ru.d.ts +4 -2
  132. package/dist/locales/ru.js +7 -2
  133. package/dist/locales/sk.cjs +12 -1
  134. package/dist/locales/sk.d.cts +4 -2
  135. package/dist/locales/sk.d.ts +4 -2
  136. package/dist/locales/sk.js +7 -2
  137. package/dist/locales/sq.cjs +12 -1
  138. package/dist/locales/sq.d.cts +4 -2
  139. package/dist/locales/sq.d.ts +4 -2
  140. package/dist/locales/sq.js +7 -2
  141. package/dist/locales/sr-Latn.cjs +12 -1
  142. package/dist/locales/sr-Latn.d.cts +4 -2
  143. package/dist/locales/sr-Latn.d.ts +4 -2
  144. package/dist/locales/sr-Latn.js +2 -3
  145. package/dist/locales/sr.cjs +12 -1
  146. package/dist/locales/sr.d.cts +4 -2
  147. package/dist/locales/sr.d.ts +4 -2
  148. package/dist/locales/sr.js +2 -3
  149. package/dist/locales/sv.cjs +12 -1
  150. package/dist/locales/sv.d.cts +4 -2
  151. package/dist/locales/sv.d.ts +4 -2
  152. package/dist/locales/sv.js +7 -2
  153. package/dist/locales/tr.cjs +12 -1
  154. package/dist/locales/tr.d.cts +4 -2
  155. package/dist/locales/tr.d.ts +4 -2
  156. package/dist/locales/tr.js +7 -2
  157. package/dist/locales/uk.cjs +12 -1
  158. package/dist/locales/uk.d.cts +4 -2
  159. package/dist/locales/uk.d.ts +4 -2
  160. package/dist/locales/uk.js +7 -2
  161. package/dist/markdown.cjs +0 -1
  162. package/dist/markdown.js +1 -2
  163. package/dist/mcp-app-sandbox.cjs +0 -1
  164. package/dist/mcp-app-sandbox.js +1 -2
  165. package/dist/mcp-app.cjs +0 -1
  166. package/dist/mcp-app.d.cts +491 -3
  167. package/dist/mcp-app.d.ts +491 -3
  168. package/dist/mcp-app.js +2 -3
  169. package/dist/pipeline.cjs +0 -1
  170. package/dist/pipeline.js +1 -2
  171. package/dist/questions-Dw--IEjT.d.cts +100 -0
  172. package/dist/questions-Dw--IEjT.d.ts +100 -0
  173. package/dist/{types-BmvgYUzF.d.cts → types-CQquuZpl.d.cts} +1 -1
  174. package/dist/{types-Cr5gmUts.d.ts → types-CXZfZVP5.d.ts} +1 -1
  175. package/dist/{mcp-app-entry-BA-Ca39z.d.ts → types-DnBCok3z.d.cts} +2 -488
  176. package/dist/{mcp-app-entry-tybABaHg.d.cts → types-DnBCok3z.d.ts} +2 -488
  177. package/package.json +13 -3
  178. package/dist/canvas.cjs.map +0 -1
  179. package/dist/canvas.js.map +0 -1
  180. package/dist/chunk-4EHUITGU.js.map +0 -1
  181. package/dist/chunk-7O64ZI6Z.js.map +0 -1
  182. package/dist/chunk-A55Q377T.js.map +0 -1
  183. package/dist/chunk-EL2YCROY.js.map +0 -1
  184. package/dist/chunk-GB7RZJMG.js.map +0 -1
  185. package/dist/chunk-KZQB35LS.js.map +0 -1
  186. package/dist/chunk-P2F2P3JC.js.map +0 -1
  187. package/dist/chunk-TPK25QGK.js.map +0 -1
  188. package/dist/index.cjs.map +0 -1
  189. package/dist/index.js.map +0 -1
  190. package/dist/locales/be.cjs.map +0 -1
  191. package/dist/locales/be.js.map +0 -1
  192. package/dist/locales/bg.cjs.map +0 -1
  193. package/dist/locales/bg.js.map +0 -1
  194. package/dist/locales/ca.cjs.map +0 -1
  195. package/dist/locales/ca.js.map +0 -1
  196. package/dist/locales/cs.cjs.map +0 -1
  197. package/dist/locales/cs.js.map +0 -1
  198. package/dist/locales/da.cjs.map +0 -1
  199. package/dist/locales/da.js.map +0 -1
  200. package/dist/locales/de.cjs.map +0 -1
  201. package/dist/locales/de.js.map +0 -1
  202. package/dist/locales/el.cjs.map +0 -1
  203. package/dist/locales/el.js.map +0 -1
  204. package/dist/locales/en.cjs.map +0 -1
  205. package/dist/locales/en.js.map +0 -1
  206. package/dist/locales/es-419.cjs.map +0 -1
  207. package/dist/locales/es-419.js.map +0 -1
  208. package/dist/locales/es.cjs.map +0 -1
  209. package/dist/locales/es.js.map +0 -1
  210. package/dist/locales/fi.cjs.map +0 -1
  211. package/dist/locales/fi.js.map +0 -1
  212. package/dist/locales/fr-CA.cjs.map +0 -1
  213. package/dist/locales/fr-CA.js.map +0 -1
  214. package/dist/locales/fr.cjs.map +0 -1
  215. package/dist/locales/fr.js.map +0 -1
  216. package/dist/locales/gn.cjs.map +0 -1
  217. package/dist/locales/gn.js.map +0 -1
  218. package/dist/locales/hr.cjs.map +0 -1
  219. package/dist/locales/hr.js.map +0 -1
  220. package/dist/locales/ht.cjs.map +0 -1
  221. package/dist/locales/ht.js.map +0 -1
  222. package/dist/locales/hu.cjs.map +0 -1
  223. package/dist/locales/hu.js.map +0 -1
  224. package/dist/locales/index.cjs.map +0 -1
  225. package/dist/locales/index.js.map +0 -1
  226. package/dist/locales/it.cjs.map +0 -1
  227. package/dist/locales/it.js.map +0 -1
  228. package/dist/locales/nb.cjs.map +0 -1
  229. package/dist/locales/nb.js.map +0 -1
  230. package/dist/locales/nl.cjs.map +0 -1
  231. package/dist/locales/nl.js.map +0 -1
  232. package/dist/locales/pl.cjs.map +0 -1
  233. package/dist/locales/pl.js.map +0 -1
  234. package/dist/locales/pt-BR.cjs.map +0 -1
  235. package/dist/locales/pt-BR.js.map +0 -1
  236. package/dist/locales/pt.cjs.map +0 -1
  237. package/dist/locales/pt.js.map +0 -1
  238. package/dist/locales/qu.cjs.map +0 -1
  239. package/dist/locales/qu.js.map +0 -1
  240. package/dist/locales/ro.cjs.map +0 -1
  241. package/dist/locales/ro.js.map +0 -1
  242. package/dist/locales/ru.cjs.map +0 -1
  243. package/dist/locales/ru.js.map +0 -1
  244. package/dist/locales/sk.cjs.map +0 -1
  245. package/dist/locales/sk.js.map +0 -1
  246. package/dist/locales/sq.cjs.map +0 -1
  247. package/dist/locales/sq.js.map +0 -1
  248. package/dist/locales/sr-Latn.cjs.map +0 -1
  249. package/dist/locales/sr-Latn.js.map +0 -1
  250. package/dist/locales/sr.cjs.map +0 -1
  251. package/dist/locales/sr.js.map +0 -1
  252. package/dist/locales/sv.cjs.map +0 -1
  253. package/dist/locales/sv.js.map +0 -1
  254. package/dist/locales/tr.cjs.map +0 -1
  255. package/dist/locales/tr.js.map +0 -1
  256. package/dist/locales/uk.cjs.map +0 -1
  257. package/dist/locales/uk.js.map +0 -1
  258. package/dist/markdown.cjs.map +0 -1
  259. package/dist/markdown.js.map +0 -1
  260. package/dist/mcp-app-sandbox.cjs.map +0 -1
  261. package/dist/mcp-app-sandbox.js.map +0 -1
  262. package/dist/mcp-app.cjs.map +0 -1
  263. package/dist/mcp-app.js.map +0 -1
  264. package/dist/pipeline.cjs.map +0 -1
  265. package/dist/pipeline.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/mcp-app-sandbox.ts","../src/mcp-app-policy.ts"],"sourcesContent":["import {\n isMcpAppSandboxMessage,\n MCP_APP_POLICY_MAX_ORIGINS,\n MCP_APP_POLICY_TOKEN_MAX_CHARS,\n MCP_APP_SANDBOX_PROXY_READY,\n MCP_APP_SANDBOX_RESOURCE_READY,\n MCP_APP_SCHEME_PARAM,\n mcpAppColorScheme,\n mcpAppPolicy,\n mcpAppPolicyOfToken,\n mcpAppPolicyOrigin,\n mcpAppPolicyToken,\n type McpAppColorScheme,\n type McpAppPolicyOrigins,\n} from './mcp-app-policy.js'\n\n/**\n * The `./mcp-app-sandbox` entry: the MCP Apps sandbox proxy - the page a host serves on ANOTHER\n * origin, so that an app runs on an origin of its own (storage, cookies, a real `Origin`) and not\n * in an opaque one. Framework-free, no imports but `mcp-app-policy.ts`: a Cloudflare Worker, Deno,\n * Bun or Node (18+) serves it with `mcpAppSandboxResponse` (Request in, Response out).\n *\n * The page, `<base>/<policy>` (`<policy>` = `mcpAppPolicyToken`):\n *\n * 1. Its response carries the app's policy as a HEADER, built from the path (`mcpAppPolicy`), plus\n * `frame-ancestors` = the allowed host origins. The app's document is written into a frame\n * the page creates (`about:blank`, `document.write`), which INHERITS that policy - nothing the\n * app's markup says comes before it, and every document the app can reach on this origin\n * (this page, a reload of it, a frame of it) has a policy some host chose for that frame.\n * 2. Its script binds to the first ANCESTOR window on an allowed host origin that sends it\n * `ui/notifications/sandbox-resource-ready`, once; after that it relays the extension's\n * messages between that window (to its exact origin) and the app's window (to this origin),\n * never the `ui/notifications/sandbox-*` ones, and creates nothing else. It asks for\n * `ui/notifications/sandbox-proxy-ready` with a content-free message to every ancestor.\n * 3. The app's frame: `sandbox=\"allow-scripts allow-same-origin\"`, no `allow` attribute. The app\n * is same-origin with this page and can reach it - which is why the boundary is not here but\n * in what the HOST draws around it (the frame's sandbox, the shell's `frame-src` pinned to\n * this URL) and in the policy header above. A `sandbox`, `csp` or `permissions` the host sends\n * is ignored: the header is the policy, and no permission is ever granted.\n */\n\nexport {\n isMcpAppSandboxMessage,\n MCP_APP_POLICY_MAX_ORIGINS,\n MCP_APP_POLICY_TOKEN_MAX_CHARS,\n MCP_APP_SANDBOX_PROXY_READY,\n MCP_APP_SANDBOX_RESOURCE_READY,\n MCP_APP_SCHEME_PARAM,\n mcpAppColorScheme,\n mcpAppPolicy,\n mcpAppPolicyOfToken,\n mcpAppPolicyOrigin,\n mcpAppPolicyToken,\n}\nexport type { McpAppColorScheme, McpAppPolicyOrigins }\n\n/** A host origin pattern: `https://<prefix>*<suffix>.<rest>`, `*` one run of `[a-z0-9-]`. */\nexport interface McpAppSandboxHostPattern {\n prefix: string\n suffix: string\n /** The rest of the host name after the first label: two labels at least. */\n rest: string\n}\n\n/** The host origins a sandbox page answers, as `parseMcpAppSandboxHosts` reads them. */\nexport interface McpAppSandboxHosts {\n /** Exact origins (`https://agent.example.com`, `http://127.0.0.1:4173`). */\n origins: string[]\n /** One-label patterns (`https://*-agents.example.workers.dev`). */\n patterns: McpAppSandboxHostPattern[]\n /** The same as `frame-ancestors` sources (a pattern widened to `https://*.<rest>`). */\n frameAncestors: string[]\n /** Entries that are neither: a sandbox with any of these refuses to serve (503). */\n invalid: string[]\n}\n\nconst LABEL = '[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?'\nconst NAME = `${LABEL}(?:\\\\.${LABEL})+`\nconst EXACT_HTTPS = new RegExp(`^https://${LABEL}(?:\\\\.${LABEL})*(?::\\\\d{1,5})?$`)\nconst EXACT_LOOPBACK = /^http:\\/\\/(?:localhost|127\\.0\\.0\\.1)(?::\\d{1,5})?$/\nconst PATTERN = new RegExp(`^https://([a-z0-9-]{0,40})\\\\*([a-z0-9-]{0,40})\\\\.(${NAME})$`)\n\n/**\n * The allowed host origins, from a list or a space / comma separated string (a deploy-time\n * setting, e.g. `ALLOWED_HOST_ORIGINS=\"https://agent.example.com https://*-agents.example.workers.dev\"`).\n * An entry is an exact origin - `https://`, or `http://` on `localhost` / `127.0.0.1` - or a\n * pattern with ONE `*` inside the first label of an `https://` host. The page's script holds the\n * pattern to one label (`[a-z0-9-]+`, no dot); `frame-ancestors` cannot say that, so there the\n * pattern is widened to `https://*.<rest>` (every subdomain of `<rest>`). Anything else is\n * `invalid`.\n */\nexport const parseMcpAppSandboxHosts = (\n value: string | readonly string[] | undefined,\n): McpAppSandboxHosts => {\n const entries = (typeof value === 'string' ? value.split(/[\\s,]+/) : [...(value ?? [])])\n .map((e) => (typeof e === 'string' ? e.trim() : ''))\n .filter(Boolean)\n const hosts: McpAppSandboxHosts = { origins: [], patterns: [], frameAncestors: [], invalid: [] }\n const ancestor = (source: string) => {\n if (!hosts.frameAncestors.includes(source)) hosts.frameAncestors.push(source)\n }\n for (const raw of entries) {\n const entry = raw.toLowerCase().replace(/\\/$/, '')\n const pattern = PATTERN.exec(entry)\n if (pattern) {\n const [, prefix, suffix, rest] = pattern\n if (\n !hosts.patterns.some((p) => p.prefix === prefix && p.suffix === suffix && p.rest === rest)\n ) {\n hosts.patterns.push({ prefix, suffix, rest })\n }\n ancestor(`https://*.${rest}`)\n } else if (EXACT_HTTPS.test(entry) || EXACT_LOOPBACK.test(entry)) {\n if (!hosts.origins.includes(entry)) hosts.origins.push(entry)\n ancestor(entry)\n } else {\n hosts.invalid.push(raw.slice(0, 120))\n }\n }\n return hosts\n}\n\n/** Whether an origin is one of the hosts (the same rule the page's script applies). */\nexport const isMcpAppSandboxHost = (hosts: McpAppSandboxHosts, origin: string): boolean => {\n if (hosts.origins.includes(origin)) return true\n const head = 'https://'\n for (const p of hosts.patterns) {\n const tail = `.${p.rest}`\n if (!origin.startsWith(head) || !origin.endsWith(tail)) continue\n const label = origin.slice(head.length, origin.length - tail.length)\n if (label.length > 63 || !label.startsWith(p.prefix) || !label.endsWith(p.suffix)) continue\n const middle = label.slice(p.prefix.length, label.length - p.suffix.length)\n if (/^[a-z0-9-]+$/.test(middle)) return true\n }\n return false\n}\n\n/**\n * The page's script (inline; it runs under the app's own policy, which allows inline scripts).\n * It reads the hosts from `#mcp-app-sandbox-hosts`, binds to the first allowed ancestor that sends\n * the resource, writes the app into its frame, and relays - see the entry's comment.\n */\nexport const MCP_APP_SANDBOX_SCRIPT = `(function () {\n 'use strict'\n var READY = ${JSON.stringify(MCP_APP_SANDBOX_PROXY_READY)}\n var RESOURCE = ${JSON.stringify(MCP_APP_SANDBOX_RESOURCE_READY)}\n var RESERVED = 'ui/notifications/sandbox-'\n var me = window\n if (me.parent === me) return\n var cfg\n try {\n cfg = JSON.parse(document.getElementById('mcp-app-sandbox-hosts').textContent)\n } catch (e) {\n return\n }\n var origins = cfg && Array.isArray(cfg.origins) ? cfg.origins : []\n var patterns = cfg && Array.isArray(cfg.patterns) ? cfg.patterns : []\n function allowed(origin) {\n if (typeof origin !== 'string') return false\n if (origins.indexOf(origin) >= 0) return true\n for (var i = 0; i < patterns.length; i++) {\n var p = patterns[i]\n var head = 'https://'\n var tail = '.' + p.rest\n if (origin.indexOf(head) !== 0 || origin.length <= head.length + tail.length) continue\n if (origin.slice(origin.length - tail.length) !== tail) continue\n var label = origin.slice(head.length, origin.length - tail.length)\n if (label.length > 63 || label.indexOf(p.prefix) !== 0) continue\n if (label.slice(label.length - p.suffix.length) !== p.suffix) continue\n if (/^[a-z0-9-]+$/.test(label.slice(p.prefix.length, label.length - p.suffix.length))) return true\n }\n return false\n }\n var ancestors = []\n for (var w = me.parent; ancestors.length < 32; w = w.parent) {\n ancestors.push(w)\n if (w === w.parent) break\n }\n function ancestor(source) {\n for (var i = 0; i < ancestors.length; i++) if (ancestors[i] === source) return true\n return false\n }\n function reserved(d) {\n return !!d && typeof d === 'object' && typeof d.method === 'string' && d.method.indexOf(RESERVED) === 0\n }\n var OWN = me.origin\n var host = null\n var hostOrigin = ''\n var app = null\n me.addEventListener('message', function (e) {\n var d = e.data\n if (app && e.source === app) {\n if (e.origin !== OWN || reserved(d)) return\n host.postMessage(d, hostOrigin)\n return\n }\n if (host) {\n if (e.source !== host || e.origin !== hostOrigin || reserved(d) || !app) return\n app.postMessage(d, OWN)\n return\n }\n if (!d || typeof d !== 'object' || d.jsonrpc !== '2.0' || d.method !== RESOURCE) return\n if (!ancestor(e.source) || !allowed(e.origin)) return\n var p = d.params\n if (!p || typeof p !== 'object' || typeof p.html !== 'string') return\n host = e.source\n hostOrigin = e.origin\n var frame = document.createElement('iframe')\n frame.id = 'app'\n frame.setAttribute('sandbox', 'allow-scripts allow-same-origin')\n frame.setAttribute('referrerpolicy', 'no-referrer')\n frame.setAttribute('title', 'MCP App')\n document.body.appendChild(frame)\n app = frame.contentWindow\n var doc = frame.contentDocument\n doc.open()\n doc.write(p.html)\n doc.close()\n })\n var ready = { jsonrpc: '2.0', method: READY, params: {} }\n for (var i = 0; i < ancestors.length; i++) ancestors[i].postMessage(ready, '*')\n})()`\n\nconst json = (value: unknown): string =>\n JSON.stringify(value).replace(/</g, '\\\\u003c').replace(/>/g, '\\\\u003e').replace(/&/g, '\\\\u0026')\n\n/**\n * The page: the hosts as data, the script. Serve it with `mcpAppSandboxHeaders`. `scheme` (the\n * frame's colour scheme, `?scheme=` of the page's URL) is declared by the page and on the app's\n * frame - only `light` / `dark`; without one the page declares nothing.\n */\nexport const mcpAppSandboxPage = (\n hosts: McpAppSandboxHosts,\n scheme?: McpAppColorScheme,\n): string => {\n const s = mcpAppColorScheme(scheme)\n return (\n '<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"robots\" content=\"noindex\">' +\n (s ? `<meta name=\"color-scheme\" content=\"${s}\">` : '') +\n '<title>MCP App sandbox</title>' +\n `<style>${s ? `:root{color-scheme:${s}}` : ''}` +\n 'html,body{margin:0;height:100%;overflow:hidden;background:transparent}' +\n `iframe{display:block;border:0;width:100%;height:100%${s ? `;color-scheme:${s}` : ''}}` +\n '</style></head><body>' +\n `<script type=\"application/json\" id=\"mcp-app-sandbox-hosts\">${json({\n origins: hosts.origins,\n patterns: hosts.patterns,\n })}</script>` +\n `<script>${MCP_APP_SANDBOX_SCRIPT}</script></body></html>`\n )\n}\n\n/** Browser features the page and the app may never use, whatever an app asks for. */\nexport const MCP_APP_SANDBOX_PERMISSIONS_POLICY =\n 'camera=(), microphone=(), geolocation=(), display-capture=(), payment=(), usb=(), serial=(), midi=()'\n\nconst COMMON = {\n 'X-Content-Type-Options': 'nosniff',\n 'X-Robots-Tag': 'noindex, nofollow',\n 'Referrer-Policy': 'no-referrer',\n 'Cache-Control': 'no-store',\n}\n\n/**\n * The page's response headers: the app's policy AND `frame-ancestors` (the hosts; `'none'` when\n * there are none), `nosniff`, `no-store` (a policy is never served from a stale copy), no referrer,\n * `noindex`, and a Permissions-Policy that grants nothing.\n */\nexport const mcpAppSandboxHeaders = (\n policy: McpAppPolicyOrigins,\n hosts: McpAppSandboxHosts,\n): Record<string, string> => ({\n 'Content-Type': 'text/html; charset=utf-8',\n 'Content-Security-Policy': `${mcpAppPolicy(policy)}; frame-ancestors ${\n hosts.frameAncestors.length > 0 ? hosts.frameAncestors.join(' ') : \"'none'\"\n }`,\n 'Permissions-Policy': MCP_APP_SANDBOX_PERMISSIONS_POLICY,\n ...COMMON,\n})\n\nexport interface McpAppSandboxServeOptions {\n /** Where the pages are: `'/sandbox/v1'` serves `/sandbox/v1/<policy>`. */\n path: string\n /** The host origins that may frame the page and send it an app (see `parseMcpAppSandboxHosts`). */\n hosts: string | readonly string[] | undefined\n}\n\nconst plain = (status: number, text: string, extra: Record<string, string> = {}): Response =>\n new Response(text, {\n status,\n headers: {\n 'Content-Type': 'text/plain; charset=utf-8',\n 'Content-Security-Policy': \"default-src 'none'; frame-ancestors 'none'\",\n ...COMMON,\n ...extra,\n },\n })\n\n/**\n * A fetch handler for the sandbox page: `GET` / `HEAD` of `<path>/<policy>` is the page, with its\n * headers (and `?scheme=light|dark`, the frame's colour scheme - anything else is none); a token\n * that is not exactly what `mcpAppPolicyToken` writes is 400; another method 405;\n * any other path 404; no valid host origin (or an invalid entry in the setting) 503 - a sandbox\n * nobody may frame is a configuration error, not a page.\n */\nexport const mcpAppSandboxResponse = (\n request: Request,\n options: McpAppSandboxServeOptions,\n): Response => {\n const { pathname, searchParams } = new URL(request.url)\n const base = options.path.replace(/\\/+$/, '')\n if (!pathname.startsWith(`${base}/`)) return plain(404, 'Not found')\n const token = pathname.slice(base.length + 1)\n if (token.length === 0 || token.includes('/')) return plain(404, 'Not found')\n if (request.method !== 'GET' && request.method !== 'HEAD') {\n return plain(405, 'Method not allowed', { Allow: 'GET, HEAD' })\n }\n const policy = mcpAppPolicyOfToken(token)\n if (!policy) return plain(400, 'Not a policy this sandbox serves')\n const hosts = parseMcpAppSandboxHosts(options.hosts)\n if (hosts.invalid.length > 0 || hosts.frameAncestors.length === 0) {\n return plain(503, 'This sandbox has no valid allowed host origins')\n }\n const scheme = mcpAppColorScheme(searchParams.get(MCP_APP_SCHEME_PARAM))\n return new Response(request.method === 'HEAD' ? null : mcpAppSandboxPage(hosts, scheme), {\n status: 200,\n headers: mcpAppSandboxHeaders(policy, hosts),\n })\n}\n","/**\n * MCP Apps: what the host (the page, `mcp-app.ts`) and the sandbox proxy (a page on ANOTHER\n * origin, `mcp-app-sandbox.ts`) must agree on - the app's Content-Security-Policy, the policy as a\n * path segment of the proxy's URL, and the names of the sandbox messages. Pure code with NO\n * imports at all: the proxy's server bundles it without React or the core (a Worker), so the\n * origin rule below is a copy of the core's `mcpAppOrigin`, and `tests/apps-sandbox.test.ts`\n * holds the two to the same answers.\n */\n\n/** The proxy tells the host it can take the app (Sandbox → Host; content-free). */\nexport const MCP_APP_SANDBOX_PROXY_READY = 'ui/notifications/sandbox-proxy-ready'\n/** The host hands the proxy the app's HTML (Host → Sandbox), once. */\nexport const MCP_APP_SANDBOX_RESOURCE_READY = 'ui/notifications/sandbox-resource-ready'\n\n/** The specification reserves these between a host and its proxy: never relayed to or from an app. */\nexport const isMcpAppSandboxMessage = (data: unknown): boolean =>\n typeof data === 'object' &&\n data !== null &&\n typeof (data as { method?: unknown }).method === 'string' &&\n (data as { method: string }).method.startsWith('ui/notifications/sandbox-')\n\n/**\n * The colour scheme of an app's frame: the theme the app is told when its frame is drawn. Every\n * document between the page and the app declares it (the frame element, the shell, the sandbox\n * page and its frame), because a browser paints an OPAQUE canvas - the canvas colour of the\n * embedded document's own scheme - behind a document whose scheme differs from its frame\n * element's: an app that is dark with a transparent body was drawn on white.\n */\nexport type McpAppColorScheme = 'light' | 'dark'\n\n/** The query parameter of the sandbox page that carries the scheme (`?scheme=dark`). */\nexport const MCP_APP_SCHEME_PARAM = 'scheme'\n\n/** `light` or `dark` exactly; anything else is no scheme (nothing is declared). */\nexport const mcpAppColorScheme = (value: unknown): McpAppColorScheme | undefined =>\n value === 'light' || value === 'dark' ? value : undefined\n\n/** The origins an app's policy grants, each already an origin (`mcpAppPolicyOrigin`). */\nexport interface McpAppPolicyOrigins {\n /** `fetch` / XHR / WebSocket (`connect-src`). */\n connect: string[]\n /** Scripts, styles, images, fonts, media. */\n resources: string[]\n}\n\n/**\n * The policy of an app's document: scripts and styles inline, `data:` / `blob:` media, and the\n * network ONLY where the resource declared it. Nested frames, workers, plugins, forms and `<base>`\n * are refused whatever was declared (a frame the app may embed would also be a place it may\n * navigate itself to). The lists must already be checked origins: nothing here re-checks them.\n *\n * `'wasm-unsafe-eval'` lets the app compile WebAssembly (a tracer, a codec, a parser), which the\n * specification's default policy leaves out and a server cannot ask for (it declares origins, not\n * keywords). It adds no reach: a module only calls what the app's own script hands it, and the\n * network stays `connect-src`. `eval`, `new Function` and string timers stay refused - that is\n * `'unsafe-eval'`, which is never granted.\n */\nexport const mcpAppPolicy = ({ connect, resources }: McpAppPolicyOrigins): string => {\n const from = resources.length > 0 ? ` ${resources.join(' ')}` : ''\n return [\n \"default-src 'none'\",\n `script-src 'unsafe-inline' 'wasm-unsafe-eval'${from}`,\n `style-src 'unsafe-inline'${from}`,\n `img-src data: blob:${from}`,\n `font-src data:${from}`,\n `media-src data: blob:${from}`,\n connect.length > 0 ? `connect-src ${connect.join(' ')}` : \"connect-src 'none'\",\n \"frame-src 'none'\",\n \"child-src 'none'\",\n \"worker-src 'none'\",\n \"object-src 'none'\",\n \"form-action 'none'\",\n \"base-uri 'none'\",\n \"webrtc 'block'\",\n ].join('; ')\n}\n\n// ── The origin rule: a COPY of the core's `mcpAppOrigin` (src/mcp/apps.ts) ──────────────────\n\nconst LABEL = '[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?'\nconst HOST = `(?:\\\\*\\\\.)?${LABEL}(?:\\\\.${LABEL})*`\nconst PORT = '(?::\\\\d{1,5})?'\nconst SECURE_ORIGIN = new RegExp(`^(?:https|wss)://${HOST}${PORT}$`)\nconst LOOPBACK_ORIGIN = new RegExp(`^(?:http|ws)://(?:localhost|127\\\\.0\\\\.0\\\\.1|\\\\[::1\\\\])${PORT}$`)\n\n/**\n * One declared CSP entry as a source expression a policy may carry, or `undefined`: only an\n * origin (`https://` / `wss://`, a `*.` wildcard over at least two labels, or `http://` /\n * `ws://` on loopback). The same answers as the core's `mcpAppOrigin`, for the proxy's server.\n */\nexport const mcpAppPolicyOrigin = (entry: unknown): string | undefined => {\n if (typeof entry !== 'string' || entry.length > 300) return undefined\n const value = entry.trim().toLowerCase().replace(/\\/$/, '')\n if (SECURE_ORIGIN.test(value)) {\n const host = value.replace(/^[a-z]+:\\/\\//, '').replace(/:\\d+$/, '')\n if (host.startsWith('*.') && !host.slice(2).includes('.')) return undefined\n return value\n }\n return LOOPBACK_ORIGIN.test(value) ? value : undefined\n}\n\n// ── The policy in the proxy's URL ────────────────────────────────────────────────────────────\n\n/** At most this many origins per list (the core's `MCP_APP_MAX_DOMAINS`). */\nexport const MCP_APP_POLICY_MAX_ORIGINS = 32\n/** A policy token longer than this is not put in a URL: the app runs without its own origin. */\nexport const MCP_APP_POLICY_TOKEN_MAX_CHARS = 4096\n\nconst B64URL = /^[A-Za-z0-9_-]+$/\n\n/**\n * The policy as one path segment (base64url of `{\"c\":[…],\"r\":[…]}`), or `undefined` when it does\n * not fit. It is in the PATH, not the query, because a `frame-src` source expression matches a\n * path exactly and ignores the query: the host pins the proxy's frame to this one URL, so nothing\n * inside the frame can load the proxy page with a policy of its choosing.\n */\nexport const mcpAppPolicyToken = ({\n connect,\n resources,\n}: McpAppPolicyOrigins): string | undefined => {\n const json = JSON.stringify({ c: connect, r: resources })\n // Origins are ASCII; anything else is not a list of checked origins.\n if (/[^\\x20-\\x7e]/.test(json)) return undefined\n const token = btoa(json).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n return token.length <= MCP_APP_POLICY_TOKEN_MAX_CHARS ? token : undefined\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst originList = (value: unknown): string[] | undefined => {\n if (!Array.isArray(value) || value.length > MCP_APP_POLICY_MAX_ORIGINS) return undefined\n const out: string[] = []\n for (const entry of value) {\n // Exactly an origin as the host writes it: checked, canonical, once.\n if (typeof entry !== 'string' || mcpAppPolicyOrigin(entry) !== entry || out.includes(entry)) {\n return undefined\n }\n out.push(entry)\n }\n return out\n}\n\n/**\n * The policy a token stands for, or `undefined` for anything that is not exactly what\n * `mcpAppPolicyToken` writes: base64url of an object with the two lists and nothing else, every\n * entry an origin by the rule above, no more than `MCP_APP_POLICY_MAX_ORIGINS` each, the\n * canonical encoding (one URL per policy).\n */\nexport const mcpAppPolicyOfToken = (token: unknown): McpAppPolicyOrigins | undefined => {\n if (\n typeof token !== 'string' ||\n token.length === 0 ||\n token.length > MCP_APP_POLICY_TOKEN_MAX_CHARS ||\n !B64URL.test(token)\n ) {\n return undefined\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(atob(token.replace(/-/g, '+').replace(/_/g, '/')))\n } catch {\n return undefined\n }\n if (!isObject(parsed)) return undefined\n const keys = Object.keys(parsed)\n if (keys.length !== 2 || !keys.includes('c') || !keys.includes('r')) return undefined\n const connect = originList(parsed.c)\n const resources = originList(parsed.r)\n if (!connect || !resources) return undefined\n const policy = { connect, resources }\n return mcpAppPolicyToken(policy) === token ? policy : undefined\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACUO,IAAM,8BAA8B;AAEpC,IAAM,iCAAiC;AAGvC,IAAM,yBAAyB,CAAC,SACrC,OAAO,SAAS,YAChB,SAAS,QACT,OAAQ,KAA8B,WAAW,YAChD,KAA4B,OAAO,WAAW,2BAA2B;AAYrE,IAAM,uBAAuB;AAG7B,IAAM,oBAAoB,CAAC,UAChC,UAAU,WAAW,UAAU,SAAS,QAAQ;AAsB3C,IAAM,eAAe,CAAC,EAAE,SAAS,UAAU,MAAmC;AACnF,QAAM,OAAO,UAAU,SAAS,IAAI,IAAI,UAAU,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AAM,SAAS,GAAG,EAAG,QAAO,MAAM,KAAK,WAAW;AAC5E,MAAI,QAAQ,WAAW,SAAS,QAAQ,WAAW,QAAQ;AACzD,WAAO,MAAM,KAAK,sBAAsB,EAAE,OAAO,YAAY,CAAC;AAAA,EAChE;AACA,QAAM,SAAS,oBAAoB,KAAK;AACxC,MAAI,CAAC,OAAQ,QAAO,MAAM,KAAK,kCAAkC;AACjE,QAAM,QAAQ,wBAAwB,QAAQ,KAAK;AACnD,MAAI,MAAM,QAAQ,SAAS,KAAK,MAAM,eAAe,WAAW,GAAG;AACjE,WAAO,MAAM,KAAK,gDAAgD;AAAA,EACpE;AACA,QAAM,SAAS,kBAAkB,aAAa,IAAI,oBAAoB,CAAC;AACvE,SAAO,IAAI,SAAS,QAAQ,WAAW,SAAS,OAAO,kBAAkB,OAAO,MAAM,GAAG;AAAA,IACvF,QAAQ;AAAA,IACR,SAAS,qBAAqB,QAAQ,KAAK;AAAA,EAC7C,CAAC;AACH;","names":["json","LABEL"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/mcp-app-sandbox.ts"],"sourcesContent":["import {\n isMcpAppSandboxMessage,\n MCP_APP_POLICY_MAX_ORIGINS,\n MCP_APP_POLICY_TOKEN_MAX_CHARS,\n MCP_APP_SANDBOX_PROXY_READY,\n MCP_APP_SANDBOX_RESOURCE_READY,\n MCP_APP_SCHEME_PARAM,\n mcpAppColorScheme,\n mcpAppPolicy,\n mcpAppPolicyOfToken,\n mcpAppPolicyOrigin,\n mcpAppPolicyToken,\n type McpAppColorScheme,\n type McpAppPolicyOrigins,\n} from './mcp-app-policy.js'\n\n/**\n * The `./mcp-app-sandbox` entry: the MCP Apps sandbox proxy - the page a host serves on ANOTHER\n * origin, so that an app runs on an origin of its own (storage, cookies, a real `Origin`) and not\n * in an opaque one. Framework-free, no imports but `mcp-app-policy.ts`: a Cloudflare Worker, Deno,\n * Bun or Node (18+) serves it with `mcpAppSandboxResponse` (Request in, Response out).\n *\n * The page, `<base>/<policy>` (`<policy>` = `mcpAppPolicyToken`):\n *\n * 1. Its response carries the app's policy as a HEADER, built from the path (`mcpAppPolicy`), plus\n * `frame-ancestors` = the allowed host origins. The app's document is written into a frame\n * the page creates (`about:blank`, `document.write`), which INHERITS that policy - nothing the\n * app's markup says comes before it, and every document the app can reach on this origin\n * (this page, a reload of it, a frame of it) has a policy some host chose for that frame.\n * 2. Its script binds to the first ANCESTOR window on an allowed host origin that sends it\n * `ui/notifications/sandbox-resource-ready`, once; after that it relays the extension's\n * messages between that window (to its exact origin) and the app's window (to this origin),\n * never the `ui/notifications/sandbox-*` ones, and creates nothing else. It asks for\n * `ui/notifications/sandbox-proxy-ready` with a content-free message to every ancestor.\n * 3. The app's frame: `sandbox=\"allow-scripts allow-same-origin\"`, no `allow` attribute. The app\n * is same-origin with this page and can reach it - which is why the boundary is not here but\n * in what the HOST draws around it (the frame's sandbox, the shell's `frame-src` pinned to\n * this URL) and in the policy header above. A `sandbox`, `csp` or `permissions` the host sends\n * is ignored: the header is the policy, and no permission is ever granted.\n */\n\nexport {\n isMcpAppSandboxMessage,\n MCP_APP_POLICY_MAX_ORIGINS,\n MCP_APP_POLICY_TOKEN_MAX_CHARS,\n MCP_APP_SANDBOX_PROXY_READY,\n MCP_APP_SANDBOX_RESOURCE_READY,\n MCP_APP_SCHEME_PARAM,\n mcpAppColorScheme,\n mcpAppPolicy,\n mcpAppPolicyOfToken,\n mcpAppPolicyOrigin,\n mcpAppPolicyToken,\n}\nexport type { McpAppColorScheme, McpAppPolicyOrigins }\n\n/** A host origin pattern: `https://<prefix>*<suffix>.<rest>`, `*` one run of `[a-z0-9-]`. */\nexport interface McpAppSandboxHostPattern {\n prefix: string\n suffix: string\n /** The rest of the host name after the first label: two labels at least. */\n rest: string\n}\n\n/** The host origins a sandbox page answers, as `parseMcpAppSandboxHosts` reads them. */\nexport interface McpAppSandboxHosts {\n /** Exact origins (`https://agent.example.com`, `http://127.0.0.1:4173`). */\n origins: string[]\n /** One-label patterns (`https://*-agents.example.workers.dev`). */\n patterns: McpAppSandboxHostPattern[]\n /** The same as `frame-ancestors` sources (a pattern widened to `https://*.<rest>`). */\n frameAncestors: string[]\n /** Entries that are neither: a sandbox with any of these refuses to serve (503). */\n invalid: string[]\n}\n\nconst LABEL = '[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?'\nconst NAME = `${LABEL}(?:\\\\.${LABEL})+`\nconst EXACT_HTTPS = new RegExp(`^https://${LABEL}(?:\\\\.${LABEL})*(?::\\\\d{1,5})?$`)\nconst EXACT_LOOPBACK = /^http:\\/\\/(?:localhost|127\\.0\\.0\\.1)(?::\\d{1,5})?$/\nconst PATTERN = new RegExp(`^https://([a-z0-9-]{0,40})\\\\*([a-z0-9-]{0,40})\\\\.(${NAME})$`)\n\n/**\n * The allowed host origins, from a list or a space / comma separated string (a deploy-time\n * setting, e.g. `ALLOWED_HOST_ORIGINS=\"https://agent.example.com https://*-agents.example.workers.dev\"`).\n * An entry is an exact origin - `https://`, or `http://` on `localhost` / `127.0.0.1` - or a\n * pattern with ONE `*` inside the first label of an `https://` host. The page's script holds the\n * pattern to one label (`[a-z0-9-]+`, no dot); `frame-ancestors` cannot say that, so there the\n * pattern is widened to `https://*.<rest>` (every subdomain of `<rest>`). Anything else is\n * `invalid`.\n */\nexport const parseMcpAppSandboxHosts = (\n value: string | readonly string[] | undefined,\n): McpAppSandboxHosts => {\n const entries = (typeof value === 'string' ? value.split(/[\\s,]+/) : [...(value ?? [])])\n .map((e) => (typeof e === 'string' ? e.trim() : ''))\n .filter(Boolean)\n const hosts: McpAppSandboxHosts = { origins: [], patterns: [], frameAncestors: [], invalid: [] }\n const ancestor = (source: string) => {\n if (!hosts.frameAncestors.includes(source)) hosts.frameAncestors.push(source)\n }\n for (const raw of entries) {\n const entry = raw.toLowerCase().replace(/\\/$/, '')\n const pattern = PATTERN.exec(entry)\n if (pattern) {\n const [, prefix, suffix, rest] = pattern\n if (\n !hosts.patterns.some((p) => p.prefix === prefix && p.suffix === suffix && p.rest === rest)\n ) {\n hosts.patterns.push({ prefix, suffix, rest })\n }\n ancestor(`https://*.${rest}`)\n } else if (EXACT_HTTPS.test(entry) || EXACT_LOOPBACK.test(entry)) {\n if (!hosts.origins.includes(entry)) hosts.origins.push(entry)\n ancestor(entry)\n } else {\n hosts.invalid.push(raw.slice(0, 120))\n }\n }\n return hosts\n}\n\n/** Whether an origin is one of the hosts (the same rule the page's script applies). */\nexport const isMcpAppSandboxHost = (hosts: McpAppSandboxHosts, origin: string): boolean => {\n if (hosts.origins.includes(origin)) return true\n const head = 'https://'\n for (const p of hosts.patterns) {\n const tail = `.${p.rest}`\n if (!origin.startsWith(head) || !origin.endsWith(tail)) continue\n const label = origin.slice(head.length, origin.length - tail.length)\n if (label.length > 63 || !label.startsWith(p.prefix) || !label.endsWith(p.suffix)) continue\n const middle = label.slice(p.prefix.length, label.length - p.suffix.length)\n if (/^[a-z0-9-]+$/.test(middle)) return true\n }\n return false\n}\n\n/**\n * The page's script (inline; it runs under the app's own policy, which allows inline scripts).\n * It reads the hosts from `#mcp-app-sandbox-hosts`, binds to the first allowed ancestor that sends\n * the resource, writes the app into its frame, and relays - see the entry's comment.\n */\nexport const MCP_APP_SANDBOX_SCRIPT = `(function () {\n 'use strict'\n var READY = ${JSON.stringify(MCP_APP_SANDBOX_PROXY_READY)}\n var RESOURCE = ${JSON.stringify(MCP_APP_SANDBOX_RESOURCE_READY)}\n var RESERVED = 'ui/notifications/sandbox-'\n var me = window\n if (me.parent === me) return\n var cfg\n try {\n cfg = JSON.parse(document.getElementById('mcp-app-sandbox-hosts').textContent)\n } catch (e) {\n return\n }\n var origins = cfg && Array.isArray(cfg.origins) ? cfg.origins : []\n var patterns = cfg && Array.isArray(cfg.patterns) ? cfg.patterns : []\n function allowed(origin) {\n if (typeof origin !== 'string') return false\n if (origins.indexOf(origin) >= 0) return true\n for (var i = 0; i < patterns.length; i++) {\n var p = patterns[i]\n var head = 'https://'\n var tail = '.' + p.rest\n if (origin.indexOf(head) !== 0 || origin.length <= head.length + tail.length) continue\n if (origin.slice(origin.length - tail.length) !== tail) continue\n var label = origin.slice(head.length, origin.length - tail.length)\n if (label.length > 63 || label.indexOf(p.prefix) !== 0) continue\n if (label.slice(label.length - p.suffix.length) !== p.suffix) continue\n if (/^[a-z0-9-]+$/.test(label.slice(p.prefix.length, label.length - p.suffix.length))) return true\n }\n return false\n }\n var ancestors = []\n for (var w = me.parent; ancestors.length < 32; w = w.parent) {\n ancestors.push(w)\n if (w === w.parent) break\n }\n function ancestor(source) {\n for (var i = 0; i < ancestors.length; i++) if (ancestors[i] === source) return true\n return false\n }\n function reserved(d) {\n return !!d && typeof d === 'object' && typeof d.method === 'string' && d.method.indexOf(RESERVED) === 0\n }\n var OWN = me.origin\n var host = null\n var hostOrigin = ''\n var app = null\n me.addEventListener('message', function (e) {\n var d = e.data\n if (app && e.source === app) {\n if (e.origin !== OWN || reserved(d)) return\n host.postMessage(d, hostOrigin)\n return\n }\n if (host) {\n if (e.source !== host || e.origin !== hostOrigin || reserved(d) || !app) return\n app.postMessage(d, OWN)\n return\n }\n if (!d || typeof d !== 'object' || d.jsonrpc !== '2.0' || d.method !== RESOURCE) return\n if (!ancestor(e.source) || !allowed(e.origin)) return\n var p = d.params\n if (!p || typeof p !== 'object' || typeof p.html !== 'string') return\n host = e.source\n hostOrigin = e.origin\n var frame = document.createElement('iframe')\n frame.id = 'app'\n frame.setAttribute('sandbox', 'allow-scripts allow-same-origin')\n frame.setAttribute('referrerpolicy', 'no-referrer')\n frame.setAttribute('title', 'MCP App')\n document.body.appendChild(frame)\n app = frame.contentWindow\n var doc = frame.contentDocument\n doc.open()\n doc.write(p.html)\n doc.close()\n })\n var ready = { jsonrpc: '2.0', method: READY, params: {} }\n for (var i = 0; i < ancestors.length; i++) ancestors[i].postMessage(ready, '*')\n})()`\n\nconst json = (value: unknown): string =>\n JSON.stringify(value).replace(/</g, '\\\\u003c').replace(/>/g, '\\\\u003e').replace(/&/g, '\\\\u0026')\n\n/**\n * The page: the hosts as data, the script. Serve it with `mcpAppSandboxHeaders`. `scheme` (the\n * frame's colour scheme, `?scheme=` of the page's URL) is declared by the page and on the app's\n * frame - only `light` / `dark`; without one the page declares nothing.\n */\nexport const mcpAppSandboxPage = (\n hosts: McpAppSandboxHosts,\n scheme?: McpAppColorScheme,\n): string => {\n const s = mcpAppColorScheme(scheme)\n return (\n '<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"robots\" content=\"noindex\">' +\n (s ? `<meta name=\"color-scheme\" content=\"${s}\">` : '') +\n '<title>MCP App sandbox</title>' +\n `<style>${s ? `:root{color-scheme:${s}}` : ''}` +\n 'html,body{margin:0;height:100%;overflow:hidden;background:transparent}' +\n `iframe{display:block;border:0;width:100%;height:100%${s ? `;color-scheme:${s}` : ''}}` +\n '</style></head><body>' +\n `<script type=\"application/json\" id=\"mcp-app-sandbox-hosts\">${json({\n origins: hosts.origins,\n patterns: hosts.patterns,\n })}</script>` +\n `<script>${MCP_APP_SANDBOX_SCRIPT}</script></body></html>`\n )\n}\n\n/** Browser features the page and the app may never use, whatever an app asks for. */\nexport const MCP_APP_SANDBOX_PERMISSIONS_POLICY =\n 'camera=(), microphone=(), geolocation=(), display-capture=(), payment=(), usb=(), serial=(), midi=()'\n\nconst COMMON = {\n 'X-Content-Type-Options': 'nosniff',\n 'X-Robots-Tag': 'noindex, nofollow',\n 'Referrer-Policy': 'no-referrer',\n 'Cache-Control': 'no-store',\n}\n\n/**\n * The page's response headers: the app's policy AND `frame-ancestors` (the hosts; `'none'` when\n * there are none), `nosniff`, `no-store` (a policy is never served from a stale copy), no referrer,\n * `noindex`, and a Permissions-Policy that grants nothing.\n */\nexport const mcpAppSandboxHeaders = (\n policy: McpAppPolicyOrigins,\n hosts: McpAppSandboxHosts,\n): Record<string, string> => ({\n 'Content-Type': 'text/html; charset=utf-8',\n 'Content-Security-Policy': `${mcpAppPolicy(policy)}; frame-ancestors ${\n hosts.frameAncestors.length > 0 ? hosts.frameAncestors.join(' ') : \"'none'\"\n }`,\n 'Permissions-Policy': MCP_APP_SANDBOX_PERMISSIONS_POLICY,\n ...COMMON,\n})\n\nexport interface McpAppSandboxServeOptions {\n /** Where the pages are: `'/sandbox/v1'` serves `/sandbox/v1/<policy>`. */\n path: string\n /** The host origins that may frame the page and send it an app (see `parseMcpAppSandboxHosts`). */\n hosts: string | readonly string[] | undefined\n}\n\nconst plain = (status: number, text: string, extra: Record<string, string> = {}): Response =>\n new Response(text, {\n status,\n headers: {\n 'Content-Type': 'text/plain; charset=utf-8',\n 'Content-Security-Policy': \"default-src 'none'; frame-ancestors 'none'\",\n ...COMMON,\n ...extra,\n },\n })\n\n/**\n * A fetch handler for the sandbox page: `GET` / `HEAD` of `<path>/<policy>` is the page, with its\n * headers (and `?scheme=light|dark`, the frame's colour scheme - anything else is none); a token\n * that is not exactly what `mcpAppPolicyToken` writes is 400; another method 405;\n * any other path 404; no valid host origin (or an invalid entry in the setting) 503 - a sandbox\n * nobody may frame is a configuration error, not a page.\n */\nexport const mcpAppSandboxResponse = (\n request: Request,\n options: McpAppSandboxServeOptions,\n): Response => {\n const { pathname, searchParams } = new URL(request.url)\n const base = options.path.replace(/\\/+$/, '')\n if (!pathname.startsWith(`${base}/`)) return plain(404, 'Not found')\n const token = pathname.slice(base.length + 1)\n if (token.length === 0 || token.includes('/')) return plain(404, 'Not found')\n if (request.method !== 'GET' && request.method !== 'HEAD') {\n return plain(405, 'Method not allowed', { Allow: 'GET, HEAD' })\n }\n const policy = mcpAppPolicyOfToken(token)\n if (!policy) return plain(400, 'Not a policy this sandbox serves')\n const hosts = parseMcpAppSandboxHosts(options.hosts)\n if (hosts.invalid.length > 0 || hosts.frameAncestors.length === 0) {\n return plain(503, 'This sandbox has no valid allowed host origins')\n }\n const scheme = mcpAppColorScheme(searchParams.get(MCP_APP_SCHEME_PARAM))\n return new Response(request.method === 'HEAD' ? null : mcpAppSandboxPage(hosts, scheme), {\n status: 200,\n headers: mcpAppSandboxHe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K,SAAS,CAAC;AAC5C,MAAI,MAAM,WAAW,KAAK,MAAM,SAAS,GAAG,EAAG,QAAO,MAAM,KAAK,WAAW;AAC5E,MAAI,QAAQ,WAAW,SAAS,QAAQ,WAAW,QAAQ;AACzD,WAAO,MAAM,KAAK,sBAAsB,EAAE,OAAO,YAAY,CAAC;AAAA,EAChE;AACA,QAAM,SAAS,oBAAoB,KAAK;AACxC,MAAI,CAAC,OAAQ,QAAO,MAAM,KAAK,kCAAkC;AACjE,QAAM,QAAQ,wBAAwB,QAAQ,KAAK;AACnD,MAAI,MAAM,QAAQ,SAAS,KAAK,MAAM,eAAe,WAAW,GAAG;AACjE,WAAO,MAAM,KAAK,gDAAgD;AAAA,EACpE;AACA,QAAM,SAAS,kBAAkB,aAAa,IAAI,oBAAoB,CAAC;AACvE,SAAO,IAAI,SAAS,QAAQ,WAAW,SAAS,OAAO,kBAAkB,OAAO,MAAM,GAAG;AAAA,IACvF,QAAQ;AAAA,IACR,SAAS,qBAAqB,QAAQ,KAAK;AAAA,EAC7C,CAAC;AACH;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/mcp-app-entry.ts","../src/mcp-app.ts","../src/html-preview.ts","../src/mcp-app-policy.ts"],"sourcesContent":["// The `./mcp-app` entry: MCP Apps on the PAGE's side - the frame's policy and shell, the\n// extension's JSON-RPC bridge, the link to a sandbox page on an origin of its own, the app's\n// requests (links, messages, downloads, sampling). Pure code: no framework, no DOM node created.\n// A security boundary: every guard has a `guard …` test in tests/apps*.test.ts.\nexport * from './mcp-app.js'\nexport * from './mcp-app-policy.js'\n","import { mcpAppOrigin, type McpAppCsp } from '@dudko.dev/agent-web'\nimport { cspMetaTag, escapeAttribute, withPolicyFirst } from './html-preview.js'\nimport {\n isMcpAppSandboxMessage,\n MCP_APP_SANDBOX_PROXY_READY,\n MCP_APP_SANDBOX_RESOURCE_READY,\n MCP_APP_SCHEME_PARAM,\n mcpAppColorScheme,\n mcpAppPolicy,\n mcpAppPolicyToken,\n type McpAppColorScheme,\n} from './mcp-app-policy.js'\nimport type { AppView, ApprovalView } from './types.js'\n\n/**\n * MCP Apps, the host's side: the security core of `<McpAppFrame>`, as pure code - no React, no\n * DOM - so every guard is unit-tested (`tests/apps.test.ts`) and proved in a real browser\n * (`e2e/apps.spec.ts`).\n *\n * The frame: an app is third-party HTML WITH scripts that must talk to the page, so it gets the\n * HTML preview's boundary (`html-preview.ts`) and one addition, a relay:\n *\n * 1. The outer `<iframe sandbox=\"allow-scripts\">` (never `allow-same-origin`): an opaque origin,\n * no access to the page's DOM, storage, IndexedDB (the key vault) or cookies; no top\n * navigation, popups, forms, modals, downloads. No `allow` attribute: no camera, microphone,\n * geolocation or clipboard, whatever the app asked for.\n * 2. It holds a SHELL of ours (`buildMcpAppDocument`): the policy built from the resource's\n * declared origins and nothing else (`mcpAppCsp`), one inner frame - the app, also\n * `sandbox=\"allow-scripts\"`, with the same policy first in its own document - and a relay\n * script. The shell's `frame-src 'none'` is what stops the app navigating itself (a frame\n * may always navigate itself; only the EMBEDDING document's policy decides where to).\n * 3. The relay forwards messages between the page and the app, and nothing else: from the\n * app's window to the page, from the page to the app's window, never the\n * `ui/notifications/sandbox-*` messages the specification reserves. The app talks to\n * `window.parent` as the extension's SDK does; the page accepts messages only from the outer\n * frame (`event.source`), so the app writing to `window.top` directly is ignored.\n * 4. The bridge (`McpAppBridge`) answers the app: a method allow-list, checked parameters, a\n * cap on requests in flight, and every request that DOES something (a tool call, a link, a\n * message) handed to the host, which asks the user.\n *\n * That is the default. Opt-in, the app runs on an origin of its own instead, behind a sandbox\n * page the host serves on another origin (the specification's \"sandbox proxy\"): 1 - 3 change\n * (see \"An app on an origin of its own\" below and `mcp-app-policy.ts`), 4 does not.\n */\n\n/** The revision of the extension this host speaks. */\nexport const MCP_APP_PROTOCOL_VERSION = '2026-01-26'\n\n/** An app's frame height, before it says how tall it is. */\nexport const APP_DEFAULT_HEIGHT = 360\n/**\n * The frame's height is the host's: the app's wish, clamped to `APP_MIN_HEIGHT` .. the cap. The\n * cap is `appHeightCap` of the chat's visible height - a few screens, never less than\n * `APP_MAX_HEIGHT` - so an app as tall as its content has no scroller of its own inside the\n * transcript (one scroller: the chat's), and an app that grows forever stops there.\n */\nexport const APP_MIN_HEIGHT = 120\n/** The least the cap is (and the cap where nothing says how tall the chat is). */\nexport const APP_MAX_HEIGHT = 800\n/** The cap is this many of the chat's visible heights. */\nexport const APP_HEIGHT_SCREENS = 3\n/** ... and never more than this, whatever the screen. */\nexport const APP_HEIGHT_CEILING = 6000\n\n/**\n * The tallest an inline app's frame is drawn, for a chat body (or viewport) `viewHeight` px tall:\n * `APP_HEIGHT_SCREENS` of it, rounded down to 100 px (the app is told it in\n * `containerDimensions.maxHeight`, and a resize of a few pixels must not tell it again), at least\n * `APP_MAX_HEIGHT`, at most `APP_HEIGHT_CEILING`.\n */\nexport const appHeightCap = (viewHeight: number | undefined): number => {\n if (typeof viewHeight !== 'number' || !Number.isFinite(viewHeight) || viewHeight <= 0) {\n return APP_MAX_HEIGHT\n }\n const screens = Math.floor((viewHeight * APP_HEIGHT_SCREENS) / 100) * 100\n return Math.min(APP_HEIGHT_CEILING, Math.max(APP_MAX_HEIGHT, screens))\n}\n\n/**\n * The cap of a frame that is already drawn, when the chat's height changes: `appHeightCap` of the\n * new height, but never less than the cap the frame had (`current`) - a rotation, a keyboard\n * resizing the page or a relayout for a touch screen must not give an app that was drawn whole a\n * scroller of its own. The cap only grows while the frame is shown (at most\n * `APP_HEIGHT_CEILING`); a new frame starts from the cap of its moment.\n */\nexport const nextAppHeightCap = (current: number, viewHeight: number | undefined): number => {\n const now = appHeightCap(viewHeight)\n return Number.isFinite(current) && current > now ? Math.min(APP_HEIGHT_CEILING, current) : now\n}\n\n/** At most this many requests of one app wait at once (tool calls, links, messages). */\nexport const MCP_APP_MAX_IN_FLIGHT = 3\n/** A message an app puts in the chat: at most this many characters. */\nexport const MCP_APP_MAX_MESSAGE_CHARS = 4000\n/** A link an app asks to open: at most this many characters. */\nexport const MCP_APP_MAX_URL_CHARS = 2048\n/** The arguments of a tool call an app makes: at most this many characters as JSON. */\nexport const MCP_APP_MAX_ARGS_CHARS = 64_000\n\n/** An app's wish for a height, as the frame draws it: within `APP_MIN_HEIGHT` .. `max` (the cap). */\nexport const clampAppHeight = (height: number, max: number = APP_MAX_HEIGHT): number =>\n Math.min(\n Math.max(\n APP_MIN_HEIGHT,\n Math.min(APP_HEIGHT_CEILING, Number.isFinite(max) ? max : APP_MAX_HEIGHT),\n ),\n Math.max(APP_MIN_HEIGHT, Math.round(Number.isFinite(height) ? height : APP_DEFAULT_HEIGHT)),\n )\n\n/** The declared origins of a list that are origins (re-checked here: whoever built the object). */\nconst origins = (list: readonly string[] | undefined): string[] => {\n const out: string[] = []\n for (const entry of list ?? []) {\n const origin = mcpAppOrigin(entry)\n if (origin && !out.includes(origin)) out.push(origin)\n }\n return out\n}\n\n/**\n * The policy of an app's document: scripts and styles inline, `data:` / `blob:` media, and the\n * network ONLY where the resource declared it - `connectDomains` for `fetch` / XHR / WebSocket,\n * `resourceDomains` for scripts, styles, images, fonts and media. Nothing declared, nothing\n * reached. Nested frames, workers, plugins, forms and `<base>` are refused whatever was declared\n * (`frameDomains` / `baseUriDomains` are not granted: a frame the app may embed would also be a\n * place it may navigate itself to). Each entry is checked again with the core's `mcpAppOrigin`.\n */\nexport const mcpAppCsp = (csp?: Partial<McpAppCsp>): string =>\n mcpAppPolicy({ connect: origins(csp?.connectDomains), resources: origins(csp?.resourceDomains) })\n\n/** The origins the policy actually grants: what the app is told in `hostCapabilities.sandbox`. */\nexport const grantedAppCsp = (\n csp?: Partial<McpAppCsp>,\n): { connectDomains: string[]; resourceDomains: string[] } => ({\n connectDomains: origins(csp?.connectDomains),\n resourceDomains: origins(csp?.resourceDomains),\n})\n\n/**\n * The relay of the shell: the app's messages to the page, the page's to the app - matched by\n * `event.source`, never by anything the message says - and not the reserved\n * `ui/notifications/sandbox-*` ones. It reads nothing else and runs nothing it is sent.\n */\nexport const MCP_APP_RELAY =\n \"(function(){var f=document.getElementById('app');\" +\n \"function reserved(d){return !!d&&typeof d.method==='string'&&d.method.indexOf('ui/notifications/sandbox-')===0}\" +\n \"addEventListener('message',function(e){var w=f&&f.contentWindow;if(!w||reserved(e.data))return;\" +\n \"if(e.source===w){parent.postMessage(e.data,'*')}else if(e.source===parent){w.postMessage(e.data,'*')}})})()\"\n\n/**\n * What a document of ours between the page and the app says about its colour scheme: the\n * `color-scheme` meta and the same on `:root` and on its frame element, so the document, its\n * frame and (for an app that declares the same) the app agree and no canvas is painted opaque\n * between them. Nothing for anything but `light` / `dark`.\n */\nconst schemeMeta = (scheme: McpAppColorScheme | undefined): string =>\n scheme ? `<meta name=\"color-scheme\" content=\"${scheme}\">` : ''\nconst schemeCss = (scheme: McpAppColorScheme | undefined): string =>\n scheme ? `:root{color-scheme:${scheme}}` : ''\nconst schemeOfFrame = (scheme: McpAppColorScheme | undefined): string =>\n scheme ? `;color-scheme:${scheme}` : ''\n\n/**\n * What goes into the OUTER frame's `srcdoc`: the shell (the app's policy first, one inner frame\n * that fills it, the relay) carrying the app, escaped, as the inner frame's `srcdoc` - with the\n * same policy first in it. Give the outer `<iframe>` `sandbox=\"allow-scripts\"` and nothing else.\n * `scheme` (the theme the app is told) is declared by the shell and its inner frame; give the\n * outer `<iframe>` the same `color-scheme`. Only `light` / `dark` are declared.\n */\nexport const buildMcpAppDocument = (\n html: string,\n csp?: Partial<McpAppCsp>,\n scheme?: McpAppColorScheme,\n): string => {\n const policy = mcpAppCsp(csp)\n const s = mcpAppColorScheme(scheme)\n return (\n '<!doctype html><html><head>' +\n `<meta http-equiv=\"Content-Security-Policy\" content=\"${escapeAttribute(policy)}\">` +\n schemeMeta(s) +\n `<style>${schemeCss(s)}html,body{margin:0;height:100%;overflow:hidden;background:transparent}` +\n `iframe{display:block;border:0;width:100%;height:100%${schemeOfFrame(s)}}</style></head><body>` +\n `<iframe id=\"app\" sandbox=\"allow-scripts\" referrerpolicy=\"no-referrer\" ` +\n `srcdoc=\"${escapeAttribute(withPolicyFirst(html, policy))}\"></iframe>` +\n `<script>${MCP_APP_RELAY}</script></body></html>`\n )\n}\n\n/** A link an app asks to open, taken apart for the prompt: the host is what the user checks. */\nexport interface AppLink {\n /** The normalised URL (what is opened). */\n href: string\n /** `https://` */\n scheme: string\n /** The host (and port), as the browser will go there - an internationalised name in punycode. */\n host: string\n /** Everything after the host. */\n rest: string\n}\n\n/** An `http(s)` URL with a host and no credentials, at most `MCP_APP_MAX_URL_CHARS`; else none. */\nexport const appLinkOf = (value: unknown): AppLink | undefined => {\n if (typeof value !== 'string' || value.length > MCP_APP_MAX_URL_CHARS) return undefined\n let url: URL\n try {\n url = new URL(value)\n } catch {\n return undefined\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') return undefined\n if (url.username || url.password || !url.hostname) return undefined\n const scheme = `${url.protocol}//`\n return {\n href: url.href,\n scheme,\n host: url.host,\n rest: url.href.slice(scheme.length + url.host.length),\n }\n}\n\n// Characters that change how text reads without being seen (bidirectional overrides,\n// zero-width) and control characters other than line breaks and tabs.\n// eslint-disable-next-line no-control-regex\nconst HIDDEN = /[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f​-‏‪-‮⁦-⁩]/g\n\n/**\n * The text of a `ui/message` an app sends: text blocks only (one, or a list of at most 20),\n * joined, without invisible characters, at most `MCP_APP_MAX_MESSAGE_CHARS`. Anything else -\n * an image, a resource, an empty or a longer text - is refused (`undefined`).\n */\nexport const appMessageTextOf = (content: unknown): string | undefined => {\n const blocks = Array.isArray(content) ? content : content === undefined ? [] : [content]\n if (blocks.length === 0 || blocks.length > 20) return undefined\n const texts: string[] = []\n for (const block of blocks) {\n if (!isObject(block) || block.type !== 'text' || typeof block.text !== 'string') {\n return undefined\n }\n texts.push(block.text)\n }\n const text = texts.join('\\n\\n').replace(HIDDEN, '').trim()\n return text && text.length <= MCP_APP_MAX_MESSAGE_CHARS ? text : undefined\n}\n\ntype Obj = Record<string, unknown>\nconst isObject = (value: unknown): value is Obj =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** A JSON-RPC message as the bridge sends it. */\nexport type McpAppRpcMessage =\n | { jsonrpc: '2.0'; id: string | number; method: string; params?: unknown }\n | { jsonrpc: '2.0'; method: string; params?: unknown }\n | { jsonrpc: '2.0'; id: string | number; result: unknown }\n | { jsonrpc: '2.0'; id: string | number; error: { code: number; message: string } }\n\n/** The requests an app may make of this host. Any other is answered \"method not found\". */\nexport const MCP_APP_REQUESTS = [\n 'ui/initialize',\n 'ping',\n 'tools/call',\n 'ui/open-link',\n 'ui/message',\n 'ui/request-display-mode',\n] as const\n/**\n * Requests answered only when the host turned the feature on (`downloadFile` / `sampling` in\n * `hostCapabilities`, a handler given to the bridge); otherwise \"method not found\", as before.\n */\nexport const MCP_APP_OPTIONAL_REQUESTS = ['ui/download-file', 'sampling/createMessage'] as const\n/** The notifications this host reads. Any other is dropped. */\nexport const MCP_APP_NOTIFICATIONS = [\n 'ui/notifications/initialized',\n 'ui/notifications/size-changed',\n] as const\n\n/** An error the bridge answers with: a JSON-RPC code and a message for the app. */\nexport class McpAppRpcError extends Error {\n constructor(\n readonly code: number,\n message: string,\n ) {\n super(message)\n this.name = 'McpAppRpcError'\n }\n}\n\nconst METHOD_NOT_FOUND = -32601\nconst INVALID_PARAMS = -32602\nconst INVALID_REQUEST = -32600\n/** The host refused: the user said no, too many requests, not initialized. */\nexport const MCP_APP_REFUSED = -32000\n\n/** How an app is shown (`hostContext.displayMode`). This host offers `inline` and `fullscreen`. */\nexport type McpAppDisplayMode = 'inline' | 'fullscreen' | 'pip'\n/** The modes the extension names (a request for any other is invalid). */\nexport const MCP_APP_DISPLAY_MODES: readonly McpAppDisplayMode[] = ['inline', 'fullscreen', 'pip']\n\n/** A file an app asks the host to save (`ui/download-file`), as checked by `appDownloadOf`. */\nexport type AppDownload =\n | {\n kind: 'embedded'\n /** The file name, sanitized (`appFileNameOf`): what it is saved as. */\n name: string\n /** The type the app declared, if it is a MIME type at all. */\n mimeType?: string\n bytes: Uint8Array\n }\n | {\n /** A `resource_link`: read with `resources/read` on the app's own server, never fetched. */\n kind: 'link'\n uri: string\n name: string\n mimeType?: string\n }\n\n/** What the host does for an app (the user is asked inside these, never by the bridge). */\nexport interface McpAppBridgeHandlers {\n /** A `tools/call`: resolves with the result the app is given; throws when refused. */\n callTool: (name: string, args: Record<string, unknown>) => Promise<unknown>\n /** A link (already checked): resolves true when it was opened, false when the user said no. */\n openLink: (link: AppLink) => Promise<boolean>\n /** A message (already cleaned): resolves true when it was accepted, false when not. */\n message: (text: string) => Promise<boolean>\n /** The app's wish for a height (the caller clamps it). */\n resize: (height: number) => void\n /**\n * `ui/request-display-mode` for a mode the host offers and the app declared (or `inline`):\n * the mode the app is in afterwards - the host may say no and answer the current one.\n * Without it, an app stays where it is.\n */\n displayMode?: (mode: McpAppDisplayMode) => McpAppDisplayMode | Promise<McpAppDisplayMode>\n /**\n * `ui/download-file` (already checked): true once the file was saved, false when the user said\n * no. Without it the method is not offered (`hostCapabilities.downloadFile` absent).\n */\n downloadFile?: (file: AppDownload) => Promise<boolean>\n /**\n * `sampling/createMessage`: the result for the app; throws (an `McpAppRpcError`) when refused.\n * Without it the method is not offered (`hostCapabilities.sampling` absent).\n */\n sample?: (params: Record<string, unknown>) => Promise<unknown>\n}\n\nexport interface McpAppBridgeOptions {\n /** Send a message to the app (the page posts it to the outer frame). */\n post: (message: McpAppRpcMessage) => void\n handlers: McpAppBridgeHandlers\n hostInfo: { name: string; version: string }\n hostCapabilities: Record<string, unknown>\n hostContext: Record<string, unknown>\n /** The tool call's arguments: sent once the app says it is initialized. */\n toolInput: Record<string, unknown>\n /** Its result; `undefined` = the app is told the call was cancelled (`reason`). */\n toolResult?: unknown\n cancelledReason?: string\n maxInFlight?: number\n}\n\nconst validId = (id: unknown): id is string | number =>\n (typeof id === 'string' && id.length > 0 && id.length <= 100) ||\n (typeof id === 'number' && Number.isFinite(id))\n\n/**\n * One app's conversation with the host (the extension's JSON-RPC over `postMessage`). It never\n * touches the DOM: `receive` is given what arrived - from the right frame, the caller checked\n * `event.source` - and `post` sends. Requests outside the allow-list get \"method not found\";\n * before `ui/initialize`, only `ping` is answered; parameters are checked before a handler sees\n * them; at most `maxInFlight` requests run at once. The tool's input and result are sent once,\n * after the app's `ui/notifications/initialized`, as the specification requires.\n */\nexport class McpAppBridge {\n private readonly o: McpAppBridgeOptions\n private initializeSeen = false\n private delivered = false\n private inFlight = 0\n private closed = false\n private seq = 0\n // The display modes the app declared at `ui/initialize` (undefined: none declared).\n private appModes: McpAppDisplayMode[] | undefined\n\n constructor(options: McpAppBridgeOptions) {\n this.o = options\n }\n\n /** The app said it is ready, and was given the tool's input and result. */\n get initialized(): boolean {\n return this.delivered\n }\n\n /** Stop answering: the frame is gone or was reloaded. */\n close(): void {\n this.closed = true\n }\n\n /** Tell the app it is being torn down (not waited for: the frame goes anyway). */\n teardown(reason: string): void {\n if (!this.delivered || this.closed) return\n this.seq += 1\n this.send({\n jsonrpc: '2.0',\n id: `host-teardown-${this.seq}`,\n method: 'ui/resource-teardown',\n params: { reason },\n })\n }\n\n /** The display modes the app declared at `ui/initialize` (undefined: none, or not yet). */\n get appDisplayModes(): readonly McpAppDisplayMode[] | undefined {\n return this.appModes ? [...this.appModes] : undefined\n }\n\n /** How the app is shown now (`hostContext.displayMode`). */\n get displayMode(): McpAppDisplayMode {\n const mode = this.o.hostContext.displayMode\n return MCP_APP_DISPLAY_MODES.includes(mode as McpAppDisplayMode)\n ? (mode as McpAppDisplayMode)\n : 'inline'\n }\n\n /** Tell an initialized app that part of the host context changed (the theme). */\n updateContext(patch: Record<string, unknown>): void {\n Object.assign(this.o.hostContext, patch)\n if (this.delivered && !this.closed) {\n this.send({ jsonrpc: '2.0', method: 'ui/notifications/host-context-changed', params: patch })\n }\n }\n\n /** One message from the app's frame. */\n receive(data: unknown): void {\n if (this.closed || !isObject(data) || data.jsonrpc !== '2.0') return\n const method = data.method\n const id = data.id\n if (method === undefined) return // a response to a request of ours: nothing waits for it\n if (typeof method !== 'string' || method.length === 0 || method.length > 100) {\n if (validId(id)) this.error(id, INVALID_REQUEST, 'Invalid request')\n return\n }\n if (id === undefined) {\n this.notification(method, data.params)\n return\n }\n if (!validId(id)) return\n if (data.params !== undefined && !isObject(data.params)) {\n this.error(id, INVALID_PARAMS, 'params must be an object')\n return\n }\n void this.request(id, method, (data.params ?? {}) as Obj)\n }\n\n private send(message: McpAppRpcMessage): void {\n if (!this.closed) this.o.post(message)\n }\n\n private error(id: string | number, code: number, message: string): void {\n this.send({ jsonrpc: '2.0', id, error: { code, message } })\n }\n\n private notification(method: string, params: unknown): void {\n const p = isObject(params) ? params : {}\n if (method === 'ui/notifications/initialized') {\n if (!this.initializeSeen || this.delivered) return\n this.delivered = true\n this.send({\n jsonrpc: '2.0',\n method: 'ui/notifications/tool-input',\n params: { arguments: this.o.toolInput },\n })\n this.send(\n this.o.toolResult === undefined\n ? {\n jsonrpc: '2.0',\n method: 'ui/notifications/tool-cancelled',\n params: { reason: this.o.cancelledReason ?? 'no result' },\n }\n : { jsonrpc: '2.0', method: 'ui/notifications/tool-result', params: this.o.toolResult },\n )\n return\n }\n if (method === 'ui/notifications/size-changed') {\n if (typeof p.height === 'number' && Number.isFinite(p.height) && p.height > 0) {\n this.o.handlers.resize(p.height)\n }\n }\n // Anything else (a log line, a teardown wish, an unknown one) is dropped.\n }\n\n private async request(id: string | number, method: string, params: Obj): Promise<void> {\n const h = this.o.handlers\n const offered =\n (MCP_APP_REQUESTS as readonly string[]).includes(method) ||\n (method === 'ui/download-file' && typeof h.downloadFile === 'function') ||\n (method === 'sampling/createMessage' && typeof h.sample === 'function')\n if (!offered) {\n this.error(id, METHOD_NOT_FOUND, `Method not found: ${method.slice(0, 60)}`)\n return\n }\n if (method === 'ping') {\n this.send({ jsonrpc: '2.0', id, result: {} })\n return\n }\n if (method === 'ui/initialize') {\n this.initializeSeen = true\n const caps = isObject(params.appCapabilities) ? params.appCapabilities : {}\n this.appModes = Array.isArray(caps.availableDisplayModes)\n ? caps.availableDisplayModes.filter((m): m is McpAppDisplayMode =>\n MCP_APP_DISPLAY_MODES.includes(m as McpAppDisplayMode),\n )\n : undefined\n this.send({\n jsonrpc: '2.0',\n id,\n result: {\n protocolVersion: MCP_APP_PROTOCOL_VERSION,\n hostInfo: this.o.hostInfo,\n hostCapabilities: this.o.hostCapabilities,\n hostContext: this.o.hostContext,\n },\n })\n return\n }\n if (!this.initializeSeen) {\n this.error(id, MCP_APP_REFUSED, 'The app is not initialized (send ui/initialize first)')\n return\n }\n if (method === 'ui/request-display-mode') {\n const requested = params.mode\n if (!MCP_APP_DISPLAY_MODES.includes(requested as McpAppDisplayMode)) {\n this.error(id, INVALID_PARAMS, 'mode must be \"inline\", \"fullscreen\" or \"pip\"')\n return\n }\n // The host decides where an app is shown, and answers the mode it is in afterwards.\n const current = this.displayMode\n const host = Array.isArray(this.o.hostContext.availableDisplayModes)\n ? (this.o.hostContext.availableDisplayModes as McpAppDisplayMode[])\n : ['inline' as const]\n let mode: McpAppDisplayMode = current\n if (\n h.displayMode &&\n appDisplayModeAllowed({\n requested: requested as McpAppDisplayMode,\n current,\n host,\n app: this.appModes,\n })\n ) {\n try {\n const next = await h.displayMode(requested as McpAppDisplayMode)\n mode = MCP_APP_DISPLAY_MODES.includes(next) ? next : current\n } catch {\n mode = this.displayMode\n }\n }\n this.send({ jsonrpc: '2.0', id, result: { mode } })\n return\n }\n // What remains does something the user is asked about: capped, then handed over.\n let run: (() => Promise<unknown>) | undefined\n if (method === 'tools/call') {\n const name = params.name\n const args = params.arguments === undefined ? {} : params.arguments\n if (typeof name !== 'string' || name.length === 0 || name.length > 128) {\n this.error(id, INVALID_PARAMS, 'tools/call needs the name of a tool')\n return\n }\n if (!isObject(args)) {\n this.error(id, INVALID_PARAMS, 'tools/call arguments must be an object')\n return\n }\n let size = Infinity\n try {\n size = JSON.stringify(args).length\n } catch {\n // not serialisable: refused below\n }\n if (size > MCP_APP_MAX_ARGS_CHARS) {\n this.error(id, INVALID_PARAMS, 'tools/call arguments are too large')\n return\n }\n run = () => this.o.handlers.callTool(name, args)\n } else if (method === 'ui/download-file') {\n const file = appDownloadOf(params)\n if (typeof file === 'string') {\n this.error(id, INVALID_PARAMS, file)\n return\n }\n const save = h.downloadFile!\n // Denied (or not saved): a result with `isError`, as the extension's SDK expects.\n run = async () => ((await save(file)) ? {} : { isError: true })\n } else if (method === 'sampling/createMessage') {\n const sample = h.sample!\n run = () => sample(params)\n } else if (method === 'ui/open-link') {\n const link = appLinkOf(params.url)\n if (!link) {\n this.error(id, INVALID_PARAMS, 'Invalid URL: only http(s) links without credentials')\n return\n }\n run = async () => {\n if (!(await this.o.handlers.openLink(link))) {\n throw new McpAppRpcError(MCP_APP_REFUSED, 'Link opening denied by user')\n }\n return {}\n }\n } else {\n const text = params.role === 'user' ? appMessageTextOf(params.content) : undefined\n if (text === undefined) {\n this.error(\n id,\n INVALID_PARAMS,\n 'Invalid message format: one user text, not empty, not too long',\n )\n return\n }\n run = async () => {\n if (!(await this.o.handlers.message(text))) {\n throw new McpAppRpcError(MCP_APP_REFUSED, 'Message sending denied')\n }\n return {}\n }\n }\n const cap = this.o.maxInFlight ?? MCP_APP_MAX_IN_FLIGHT\n if (this.inFlight >= cap) {\n this.error(id, MCP_APP_REFUSED, 'Too many requests of this app are waiting')\n return\n }\n this.inFlight += 1\n try {\n const result = await run()\n this.send({ jsonrpc: '2.0', id, result })\n } catch (err) {\n const code = err instanceof McpAppRpcError ? err.code : MCP_APP_REFUSED\n const message = (err instanceof Error ? err.message : String(err)).slice(0, 300)\n this.error(id, code, message)\n } finally {\n this.inFlight -= 1\n }\n }\n}\n\n/**\n * What this host tells an app it can do (`hostCapabilities` of `ui/initialize`): only what it\n * does. `downloadFile` and `sampling` (never `sampling.tools`) only when the host turned them on.\n */\nexport const mcpAppHostCapabilities = (\n csp?: Partial<McpAppCsp>,\n features: { downloadFile?: boolean; sampling?: boolean } = {},\n): Record<string, unknown> => ({\n openLinks: {},\n serverTools: {},\n message: { text: {} },\n ...(features.downloadFile ? { downloadFile: {} } : {}),\n ...(features.sampling ? { sampling: {} } : {}),\n // What the frame grants: the declared origins it kept; no permission at all.\n sandbox: { permissions: {}, csp: grantedAppCsp(csp) },\n})\n\n// ── Display modes ───────────────────────────────────────────────────────────────────────────\n\n/**\n * Whether a display mode an app asks for may be given: `inline` always (the way back needs no\n * permission); any other only when the host offers it AND the app declared it in\n * `appCapabilities.availableDisplayModes` - an app that declared nothing stays inline (the\n * specification lets a host decline it).\n */\nexport const appDisplayModeAllowed = (o: {\n requested: McpAppDisplayMode\n current: McpAppDisplayMode\n host: readonly McpAppDisplayMode[]\n app: readonly McpAppDisplayMode[] | undefined\n}): boolean =>\n o.requested === o.current ||\n o.requested === 'inline' ||\n (o.host.includes(o.requested) && (o.app?.includes(o.requested) ?? false))\n\n/**\n * Whether the user just acted INSIDE the app's frame: the page's frame element has the focus\n * (a click or a key in a frame focuses it) and the page has transient user activation (an\n * activation in a frame reaches every page above it, for a few seconds). Where the browser has\n * no `navigator.userActivation`, the focus alone.\n */\nexport const appGestureOf = (o: { focused: boolean; activation: boolean | undefined }): boolean =>\n o.focused && o.activation !== false\n\n// ── Downloads: a file the app hands the host to save ────────────────────────────────────────\n\n/** A file an app asks to save: at most this many bytes. */\nexport const MCP_APP_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024\n/** A saved file's name: at most this many characters (the extension kept). */\nexport const MCP_APP_MAX_FILE_NAME_CHARS = 100\n\n/**\n * Extensions this host never saves: programs, scripts, installers, shortcuts, disk images - and\n * documents a browser runs scripts in when they are opened (HTML, SVG, XML).\n */\nexport const MCP_APP_REFUSED_DOWNLOAD_EXTENSIONS: readonly string[] = [\n 'exe',\n 'com',\n 'bat',\n 'cmd',\n 'scr',\n 'pif',\n 'msi',\n 'msp',\n 'mst',\n 'msc',\n 'cpl',\n 'dll',\n 'sys',\n 'ps1',\n 'psm1',\n 'psd1',\n 'vbs',\n 'vbe',\n 'js',\n 'jse',\n 'mjs',\n 'cjs',\n 'wsf',\n 'wsh',\n 'ws',\n 'hta',\n 'jar',\n 'jnlp',\n 'lnk',\n 'reg',\n 'inf',\n 'scf',\n 'url',\n 'website',\n 'application',\n 'gadget',\n 'sh',\n 'bash',\n 'zsh',\n 'csh',\n 'ksh',\n 'command',\n 'tool',\n 'app',\n 'pkg',\n 'mpkg',\n 'dmg',\n 'deb',\n 'rpm',\n 'apk',\n 'xapk',\n 'appimage',\n 'run',\n 'bin',\n 'elf',\n 'out',\n 'py',\n 'pyw',\n 'pyz',\n 'pl',\n 'rb',\n 'php',\n 'html',\n 'htm',\n 'xhtml',\n 'xht',\n 'shtml',\n 'mht',\n 'mhtml',\n 'svg',\n 'svgz',\n 'xml',\n 'xsl',\n 'xslt',\n 'webloc',\n 'desktop',\n 'iso',\n 'img',\n 'vhd',\n 'vhdx',\n 'library-ms',\n 'settingcontent-ms',\n]\n\n/** Types this host never saves (the same kinds), and any `…+xml`. */\nexport const MCP_APP_REFUSED_DOWNLOAD_TYPES: readonly string[] = [\n 'text/html',\n 'application/xhtml+xml',\n 'image/svg+xml',\n 'application/xml',\n 'text/xml',\n 'text/javascript',\n 'application/javascript',\n 'application/ecmascript',\n 'application/x-javascript',\n 'application/x-msdownload',\n 'application/x-msdos-program',\n 'application/x-msi',\n 'application/x-ms-installer',\n 'application/vnd.microsoft.portable-executable',\n 'application/x-executable',\n 'application/x-elf',\n 'application/x-sh',\n 'application/x-shellscript',\n 'application/x-csh',\n 'application/java-archive',\n 'application/x-java-jnlp-file',\n 'application/hta',\n 'application/x-apple-diskimage',\n 'application/vnd.android.package-archive',\n 'application/x-python-code',\n 'text/x-python',\n 'application/x-httpd-php',\n]\n\nconst MIME = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/\n\n/** A declared type as a bare MIME type (`text/plain`), or undefined when it is not one. */\nexport const appMimeTypeOf = (value: unknown): string | undefined => {\n if (typeof value !== 'string') return undefined\n const type = value.split(';')[0]!.trim().toLowerCase()\n return MIME.test(type) ? type : undefined\n}\n\n// Device names Windows will not let a file be called (with any extension).\nconst RESERVED_NAME = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\\..*)?$/i\n\n/**\n * The name a file is saved under: the last segment of a path or URI (`file:///x/report.json` →\n * `report.json`; percent-encoding decoded, and split again), without what cannot be seen or\n * reserved characters (`<>:\"/\\|?*`, controls), no leading dots (a hidden file) or trailing dots\n * and spaces, not a Windows device name, at most `MCP_APP_MAX_FILE_NAME_CHARS` with the extension\n * kept; `download` when nothing is left.\n */\nexport const appFileNameOf = (value: unknown): string => {\n let name = typeof value === 'string' ? value.slice(0, 2048) : ''\n name = name.replace(/[?#].*$/s, '')\n name = name.split(/[\\\\/]/).pop() ?? ''\n try {\n name = decodeURIComponent(name)\n } catch {\n // not percent-encoded: as it is\n }\n name = (name.split(/[\\\\/]/).pop() ?? '')\n .replace(HIDDEN, '')\n // eslint-disable-next-line no-control-regex\n .replace(/[<>:\"|?*\\u0000-\\u001f\\u007f]/g, '_')\n .replace(/\\s+/g, ' ')\n .replace(/^[.\\s]+/, '')\n .replace(/[.\\s]+$/, '')\n if (RESERVED_NAME.test(name)) name = `_${name}`\n if (name.length > MCP_APP_MAX_FILE_NAME_CHARS) {\n const dot = name.lastIndexOf('.')\n const ext = dot > 0 && name.length - dot <= 16 ? name.slice(dot) : ''\n name = name.slice(0, MCP_APP_MAX_FILE_NAME_CHARS - ext.length).replace(/[.\\s]+$/, '') + ext\n }\n return name || 'download'\n}\n\n/** The extension of a (sanitized) file name, lowercased, without the dot; '' when none. */\nexport const appFileExtensionOf = (name: string): string => {\n const dot = name.lastIndexOf('.')\n return dot > 0 ? name.slice(dot + 1).toLowerCase() : ''\n}\n\n/**\n * Why a file may not be saved, or undefined when it may: an extension or a type of the refused\n * lists (a program, a script, a page a browser would run), checked on the sanitized name and\n * the declared type both.\n */\nexport const appDownloadRefusal = (name: string, mimeType?: string): string | undefined => {\n const ext = appFileExtensionOf(name)\n if (MCP_APP_REFUSED_DOWNLOAD_EXTENSIONS.includes(ext)) return `“.${ext}” files are not saved`\n const type = appMimeTypeOf(mimeType)\n if (type && (MCP_APP_REFUSED_DOWNLOAD_TYPES.includes(type) || type.endsWith('+xml'))) {\n return `${type} files are not saved`\n }\n return undefined\n}\n\nconst URI_LINE = /^[^\\u0000-\\u001f\\u007f\\s]{1,2048}$/\n\nconst bytesOfBase64 = (blob: string, maxBytes: number): Uint8Array | string => {\n if (blob.length > Math.ceil((maxBytes * 4) / 3) + 4)\n return `the file is larger than ${maxBytes} bytes`\n if (!/^[A-Za-z0-9+/\\s]*={0,2}\\s*$/.test(blob)) return 'blob must be base64'\n try {\n const binary = atob(blob.replace(/\\s+/g, ''))\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)\n return bytes\n } catch {\n return 'blob must be base64'\n }\n}\n\n/**\n * What `ui/download-file` asks for, checked - or why not (a message for the app): ONE item of\n * `contents` (one file per request, one prompt); an `EmbeddedResource` (`resource.uri` names\n * it, `text` as UTF-8 or base64 `blob`, at most `maxBytes`) or a `ResourceLink` (a one-line URI,\n * read later from the app's own server: the name is its last segment, else its `name`); the\n * name sanitized and the name and type not refused (`appDownloadRefusal`).\n */\nexport const appDownloadOf = (\n params: unknown,\n maxBytes: number = MCP_APP_MAX_DOWNLOAD_BYTES,\n): AppDownload | string => {\n const contents = isObject(params) ? params.contents : undefined\n if (!Array.isArray(contents) || contents.length === 0) return 'contents must list the file'\n if (contents.length > 1) return 'One file per request'\n const item = contents[0]\n if (!isObject(item)) return 'Invalid content'\n if (item.type === 'resource') {\n const r = item.resource\n if (!isObject(r) || typeof r.uri !== 'string' || !URI_LINE.test(r.uri)) {\n return 'Invalid content: resource.uri names the file'\n }\n const name = appFileNameOf(r.uri)\n const mimeType = appMimeTypeOf(r.mimeType)\n const refused = appDownloadRefusal(name, mimeType)\n if (refused) return `Policy violation: ${refused}`\n let bytes: Uint8Array | string\n if (typeof r.text === 'string') {\n bytes =\n r.text.length > maxBytes\n ? `the file is larger than ${maxBytes} bytes`\n : new TextEncoder().encode(r.text)\n } else if (typeof r.blob === 'string') {\n bytes = bytesOfBase64(r.blob, maxBytes)\n } else {\n return 'Invalid content: text or blob'\n }\n if (typeof bytes === 'string') return `Invalid content: ${bytes}`\n if (bytes.length > maxBytes) return `Invalid content: the file is larger than ${maxBytes} bytes`\n return { kind: 'embedded', name, ...(mimeType ? { mimeType } : {}), bytes }\n }\n if (item.type === 'resource_link') {\n if (typeof item.uri !== 'string' || !URI_LINE.test(item.uri)) {\n return 'Invalid content: a resource_link needs a URI'\n }\n const fromUri = appFileNameOf(item.uri)\n const name =\n fromUri !== 'download' || typeof item.name !== 'string' ? fromUri : appFileNameOf(item.name)\n const mimeType = appMimeTypeOf(item.mimeType)\n const refused = appDownloadRefusal(name, mimeType)\n if (refused) return `Policy violation: ${refused}`\n return { kind: 'link', uri: item.uri, name, ...(mimeType ? { mimeType } : {}) }\n }\n return 'Invalid content: a resource or a resource_link'\n}\n\n/** A file ready to be put to the user: its name, type, bytes, and where the bytes came from. */\nexport interface AppReadyDownload {\n name: string\n mimeType?: string\n bytes: Uint8Array\n source: 'embedded' | 'link'\n}\n\n/** How a linked file is read: `resources/read` on the app's OWN server (the connection's). */\nexport type AppResourceReader = (\n server: string,\n uri: string,\n options: { signal?: AbortSignal; maxBytes: number },\n) => Promise<{ mimeType?: string; bytes: Uint8Array }>\n\n/**\n * The bytes of a checked file: an embedded one as it came; a linked one read from `server` -\n * the app's own - through `read` (never a fetch of its URI), at most `maxBytes`, and the type the\n * SERVER gives it judged again (an app cannot pass a page off as a text file through a link).\n * Throws an `McpAppRpcError` for the app: no reader, a failed read, a refused type, too large.\n */\nexport const resolveAppDownload = async (\n file: AppDownload,\n server: string,\n read: AppResourceReader | undefined,\n signal?: AbortSignal,\n maxBytes: number = MCP_APP_MAX_DOWNLOAD_BYTES,\n): Promise<AppReadyDownload> => {\n if (file.kind === 'embedded') {\n return {\n name: file.name,\n ...(file.mimeType ? { mimeType: file.mimeType } : {}),\n bytes: file.bytes,\n source: 'embedded',\n }\n }\n if (!read) throw new McpAppRpcError(MCP_APP_REFUSED, 'This host cannot read a linked file')\n let got: { mimeType?: string; bytes: Uint8Array }\n try {\n got = await read(server, file.uri, { ...(signal ? { signal } : {}), maxBytes })\n } catch (err) {\n const why = err instanceof Error ? err.message : String(err)\n throw new McpAppRpcError(MCP_APP_REFUSED, `Invalid content: ${why.slice(0, 200)}`)\n }\n if (!(got?.bytes instanceof Uint8Array)) {\n throw new McpAppRpcError(MCP_APP_REFUSED, 'Invalid content: no bytes')\n }\n if (got.bytes.length > maxBytes) {\n throw new McpAppRpcError(INVALID_PARAMS, `Invalid content: larger than ${maxBytes} bytes`)\n }\n const mimeType = appMimeTypeOf(got.mimeType) ?? file.mimeType\n const refused = appDownloadRefusal(file.name, mimeType)\n if (refused) throw new McpAppRpcError(INVALID_PARAMS, `Policy violation: ${refused}`)\n return { name: file.name, ...(mimeType ? { mimeType } : {}), bytes: got.bytes, source: 'link' }\n}\n\n/**\n * The error an app is told when the agent did not answer its sampling request: the core's\n * `AppSamplingError` carries its JSON-RPC code (`-1`: the user said no, `-32602`: not a request\n * this host takes, `-32000`: too many); anything else is a refusal.\n */\nexport const appSamplingErrorOf = (err: unknown): McpAppRpcError => {\n if (err instanceof McpAppRpcError) return err\n const rpc = (err as { rpcCode?: unknown } | null)?.rpcCode\n const message = (err instanceof Error ? err.message : String(err)).slice(0, 300)\n return err instanceof Error && err.name === 'AppSamplingError' && typeof rpc === 'number'\n ? new McpAppRpcError(rpc, message)\n : new McpAppRpcError(MCP_APP_REFUSED, message)\n}\n\n/** What `saveAppFile` uses of the page (passed in: this module touches no DOM by itself). */\nexport interface AppFileSaverEnv {\n document: { createElement: (tag: 'a') => HTMLAnchorElement; body: { append: (n: Node) => void } }\n URL: { createObjectURL: (blob: Blob) => string; revokeObjectURL: (url: string) => void }\n setTimeout: (fn: () => void, ms: number) => unknown\n}\n\n/**\n * Save a checked file the user agreed to: a `Blob` of type `application/octet-stream` (the\n * browser never renders or sniffs it as a page), a `blob:` URL of THIS page, an `<a download>`\n * made here and clicked once. No navigation, no `data:` or `javascript:` URL, nothing of the app\n * in the page; the URL is revoked a minute later.\n */\nexport const saveAppFile = (\n file: { name: string; bytes: Uint8Array },\n env: AppFileSaverEnv,\n): void => {\n const blob = new Blob([file.bytes as BlobPart], { type: 'application/octet-stream' })\n const url = env.URL.createObjectURL(blob)\n const a = env.document.createElement('a')\n a.href = url\n a.download = appFileNameOf(file.name)\n a.rel = 'noopener'\n a.style.display = 'none'\n env.document.body.append(a)\n a.click()\n a.remove()\n env.setTimeout(() => env.URL.revokeObjectURL(url), 60_000)\n}\n\n// ── An app on an origin of its own: the sandbox proxy (opt-in) ──────────────────────────────\n//\n// The specification's web-host model: the app is not framed by a `srcdoc` of ours but by a page\n// the host serves on ANOTHER origin (`./mcp-app-sandbox`), so the app gets that origin - storage,\n// cookies, a real `Origin` on its requests - and never the page's. From the page down:\n//\n// your page ── <iframe sandbox=\"allow-scripts allow-same-origin\" srcdoc=SHELL> (your origin)\n// SHELL: no script (`script-src 'none'`); `frame-src` = the proxy's exact URL\n// └─ <iframe sandbox=\"allow-scripts allow-same-origin\" src=PROXY> (the sandbox origin)\n// PROXY: the app's policy as a header; relays messages\n// └─ the app, written into a frame of the proxy (the sandbox origin)\n//\n// The app is same-origin with the proxy and can reach into it - make it navigate, run code in it.\n// So the guards are what the app cannot reach: the frames' sandbox flags (drawn on YOUR side,\n// cross-origin to the app), the shell's `frame-src`, which pins the proxy's frame to its one URL\n// (any other navigation of it is refused, so nothing leaves for an origin the app did not\n// declare), the policy in that URL's PATH (which the pin covers; a query would not be), and the\n// page's checks below: messages only from the proxy's window AND the sandbox origin, posted to\n// that origin only, one handshake. A second `sandbox-proxy-ready` means the proxy was loaded again\n// - by the app - and the app is stopped. Without a sandbox URL, or when its page does not answer,\n// the app runs in the opaque frame above: the stricter of the two.\n\n/** `<AgentChat appSandbox>` / `useMcpAppHost({ sandbox })`. */\nexport interface McpAppSandboxOptions {\n /**\n * The sandbox page's base URL on another origin you serve (`mcpAppSandboxResponse` of the\n * `./mcp-app-sandbox` entry), e.g. `https://apps.example.com/sandbox/v1`; an app's frame loads\n * `<url>/<policy>`. `{server}` in the host name gives each server an origin of its own\n * (`https://{server}.apps.example.com/sandbox/v1`; the server's name must be a DNS label - it\n * needs a wildcard certificate). `https://` only; `http://` on `localhost` / `127.0.0.1`.\n */\n url: string\n /** How long a frame waits for the page's handshake before it falls back (default 5000 ms). */\n timeoutMs?: number\n}\n\n/** Why an app runs in the opaque frame although a sandbox URL is set. */\nexport type McpAppSandboxReason =\n | 'invalid'\n | 'insecure'\n | 'same-origin'\n | 'no-page-origin'\n | 'server-name'\n | 'too-many-origins'\n | 'no-answer'\n\nexport type McpAppSandboxTarget =\n { ok: true; origin: string; base: string } | { ok: false; reason: McpAppSandboxReason }\n\n/** The placeholder for the server's name in `McpAppSandboxOptions.url`. */\nexport const MCP_APP_SANDBOX_SERVER = '{server}'\nexport const MCP_APP_SANDBOX_TIMEOUT_MS = 5000\n/** After the shell has loaded (the proxy loaded or failed), the handshake gets this much longer. */\nexport const MCP_APP_SANDBOX_GRACE_MS = 1000\n/**\n * The sandbox flags of the shell's frame and of the proxy's: scripts and an origin - the shell\n * must keep YOUR origin (else the proxy below it would get an opaque one) and runs no script; the\n * proxy is on the sandbox origin. Nothing else: no navigation, popup, form, modal, download.\n */\nexport const MCP_APP_SANDBOX_FRAME_TOKENS = 'allow-scripts allow-same-origin'\n\nconst DNS_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/\n// CSP cannot name an IPv6 literal (`[::1]`): the proxy's frame could not be pinned.\nconst LOOPBACK_HOSTS = ['localhost', '127.0.0.1']\n// What a `frame-src` source expression's path may hold, and a URL keeps as it is.\nconst SAFE_PATH = /^\\/[A-Za-z0-9\\-._~/%]*$/\n\nconst no = (reason: McpAppSandboxReason): McpAppSandboxTarget => ({ ok: false, reason })\n\n/**\n * Where an app of `server` runs, for a page on `pageOrigin`: the sandbox's origin and base URL,\n * or why not. Refused: not a URL; credentials, a query or a fragment; not `https://` (`http://`\n * only on `localhost` / `127.0.0.1`); a path a policy cannot name; `{server}` anywhere but the\n * host name, more than once, or a server name that is not a lowercase DNS label; a page without\n * an origin; and the sandbox on the PAGE'S OWN origin - `allow-same-origin` there would hand the\n * app your storage and the key vault.\n */\nexport const mcpAppSandboxTarget = (\n options: McpAppSandboxOptions | undefined,\n server: string,\n pageOrigin: string | undefined,\n): McpAppSandboxTarget => {\n const template = options?.url\n if (typeof template !== 'string' || template.length === 0 || template.length > 2048) {\n return no('invalid')\n }\n const parts = template.split(MCP_APP_SANDBOX_SERVER)\n if (parts.length > 2) return no('invalid')\n let raw = template\n if (parts.length === 2) {\n const authority = /^[a-z][a-z0-9+.-]*:\\/\\/([^/?#]*)/i.exec(template)?.[1] ?? ''\n if (!authority.replace(/:\\d*$/, '').includes(MCP_APP_SANDBOX_SERVER)) return no('invalid')\n if (typeof server !== 'string' || !DNS_LABEL.test(server)) return no('server-name')\n raw = template.replace(MCP_APP_SANDBOX_SERVER, server)\n }\n if (/[?#\\s]/.test(raw)) return no('invalid')\n let url: URL\n try {\n url = new URL(raw)\n } catch {\n return no('invalid')\n }\n const loopback = LOOPBACK_HOSTS.includes(url.hostname)\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) return no('insecure')\n if (url.username || url.password || !url.hostname) return no('invalid')\n if (!url.hostname.split('.').every((label) => DNS_LABEL.test(label))) {\n return no(parts.length === 2 ? 'server-name' : 'invalid')\n }\n if (!SAFE_PATH.test(url.pathname)) return no('invalid')\n if (!pageOrigin || pageOrigin === 'null') return no('no-page-origin')\n if (url.origin === pageOrigin) return no('same-origin')\n return { ok: true, origin: url.origin, base: `${url.origin}${url.pathname.replace(/\\/+$/, '')}` }\n}\n\n/** The proxy page's URL for an app's declared origins (`<base>/<policy>`), or none if too long. */\nexport const mcpAppSandboxProxyUrl = (\n base: string,\n csp?: Partial<McpAppCsp>,\n): string | undefined => {\n const granted = grantedAppCsp(csp)\n const token = mcpAppPolicyToken({\n connect: granted.connectDomains,\n resources: granted.resourceDomains,\n })\n return token ? `${base}/${token}` : undefined\n}\n\nconst PROXY_URL = /^https?:\\/\\/[A-Za-z0-9.-]+(?::\\d{1,5})?\\/[A-Za-z0-9\\-._~/%]*$/\n\n/**\n * The policy of the shell: no script at all, and frames from the proxy's exact URL only - a\n * `frame-src` with a path matches that path and nothing else (the query is not part of the\n * match), so the proxy's frame can never be navigated anywhere else.\n */\nexport const mcpAppSandboxShellCsp = (proxyUrl: string): string =>\n [\n \"default-src 'none'\",\n \"script-src 'none'\",\n \"style-src 'unsafe-inline'\",\n `frame-src ${proxyUrl}`,\n \"child-src 'none'\",\n \"worker-src 'none'\",\n \"object-src 'none'\",\n \"form-action 'none'\",\n \"base-uri 'none'\",\n ].join('; ')\n\n/**\n * What goes into the OUTER frame's `srcdoc` in sandbox mode: the shell - its policy first, one\n * frame of the proxy page, no script, nothing of the app. Give the outer `<iframe>`\n * `sandbox={MCP_APP_SANDBOX_FRAME_TOKENS}` and nothing else. Throws on a URL that is not a proxy\n * URL this package builds (`mcpAppSandboxProxyUrl`). `scheme` is declared by the shell and its\n * frame, and handed to the proxy page as `?scheme=` on its frame's `src` ONLY: the shell's\n * `frame-src` stays the path (a source expression carries no query, and a path source ignores\n * one), so the pin is the same with or without it.\n */\nexport const buildMcpAppSandboxShell = (proxyUrl: string, scheme?: McpAppColorScheme): string => {\n if (!PROXY_URL.test(proxyUrl)) throw new Error('not a sandbox proxy URL')\n const s = mcpAppColorScheme(scheme)\n const src = s ? `${proxyUrl}?${MCP_APP_SCHEME_PARAM}=${s}` : proxyUrl\n return (\n '<!doctype html><html><head>' +\n cspMetaTag(mcpAppSandboxShellCsp(proxyUrl)) +\n schemeMeta(s) +\n `<style>${schemeCss(s)}html,body{margin:0;height:100%;overflow:hidden;background:transparent}` +\n `iframe{display:block;border:0;width:100%;height:100%${schemeOfFrame(s)}}</style></head><body>` +\n `<iframe id=\"proxy\" sandbox=\"${MCP_APP_SANDBOX_FRAME_TOKENS}\" referrerpolicy=\"no-referrer\" ` +\n `src=\"${escapeAttribute(src)}\"></iframe></body></html>`\n )\n}\n\n/** What one message from the proxy's frame is, for the page (`McpAppSandboxLink.receive`). */\nexport type McpAppSandboxInput = 'drop' | 'ready' | 'broken' | 'app'\n\nexport interface McpAppSandboxLinkOptions {\n /** The sandbox origin (`mcpAppSandboxTarget(…).origin`). */\n origin: string\n /** The app, as read from its server: sent once, on the proxy's first ready. */\n html: string\n csp?: Partial<McpAppCsp>\n /** Post to the proxy's window. Always called with the sandbox origin as the target - never `*`. */\n post: (message: unknown, targetOrigin: string) => void\n}\n\n/**\n * The page's side of the sandbox proxy, without the DOM: which messages are the proxy's, the\n * handshake, and every post to the sandbox origin. A message is the proxy's only when it comes\n * from the proxy's window (`event.source`) AND from the sandbox origin (`event.origin`). The\n * first `sandbox-proxy-ready` is answered with the app (`sandbox-resource-ready`); another one\n * means the proxy page was loaded again - by the app - and the link breaks (`'broken'`: stop the\n * app). Every other `ui/notifications/sandbox-*` message is dropped; nothing reaches the bridge\n * (`'app'`) before the app was handed over.\n */\nexport class McpAppSandboxLink {\n private readonly o: McpAppSandboxLinkOptions\n private state: 'waiting' | 'loaded' | 'broken' | 'closed' = 'waiting'\n\n constructor(options: McpAppSandboxLinkOptions) {\n this.o = options\n }\n\n /** The proxy answered and was given the app. */\n get ready(): boolean {\n return this.state === 'loaded'\n }\n\n /** The proxy page was loaded a second time: the app must be stopped. */\n get broken(): boolean {\n return this.state === 'broken'\n }\n\n /** Whether a message event is the proxy's: its window, and the sandbox origin. */\n accepts(event: { source: unknown; origin: string }, proxy: unknown): boolean {\n return (\n proxy !== null &&\n proxy !== undefined &&\n event.source === proxy &&\n event.origin === this.o.origin\n )\n }\n\n receive(\n event: { source: unknown; origin: string; data: unknown },\n proxy: unknown,\n ): McpAppSandboxInput {\n if (this.state === 'broken' || this.state === 'closed' || !this.accepts(event, proxy)) {\n return 'drop'\n }\n const data = event.data\n if (isMcpAppSandboxMessage(data)) {\n const d = data as { jsonrpc?: unknown; method: string }\n if (d.jsonrpc !== '2.0' || d.method !== MCP_APP_SANDBOX_PROXY_READY) return 'drop'\n if (this.state === 'loaded') {\n this.state = 'broken'\n return 'broken'\n }\n this.state = 'loaded'\n const granted = grantedAppCsp(this.o.csp)\n this.o.post(\n {\n jsonrpc: '2.0',\n method: MCP_APP_SANDBOX_RESOURCE_READY,\n params: { html: this.o.html, csp: granted },\n },\n this.o.origin,\n )\n return 'ready'\n }\n return this.state === 'loaded' ? 'app' : 'drop'\n }\n\n /** Send a message to the app, through the proxy, to the sandbox origin. Nothing once broken. */\n post(message: unknown): void {\n if (this.state === 'loaded') this.o.post(message, this.o.origin)\n }\n\n close(): void {\n if (this.state !== 'broken') this.state = 'closed'\n }\n}\n\n/**\n * A pending consent request of THIS frame (`ApprovalView.app.frame`, set by `useAgent`); for a\n * request that names no frame (a host's own gate), one of this app's server and resource.\n */\nexport const isApprovalOfApp = (approval: ApprovalView, app: AppView): boolean =>\n approval.status === 'pending' &&\n approval.app !== undefined &&\n (approval.app.frame !== undefined\n ? approval.app.frame === app.id\n : approval.app.server === app.server && approval.app.resourceUri === app.resourceUri)\n","/**\n * The sandboxed frame's security core: what untrusted HTML (a file the agent wrote, later an\n * MCP App) is wrapped in before it reaches an `<iframe>`. Pure strings - no React, no DOM - so\n * every guard is unit-tested here and proved in a real browser by `e2e/files.spec.ts`.\n *\n * The boundary, in three layers:\n * 1. `sandbox` WITHOUT `allow-same-origin`: the document gets an opaque origin - no access to\n * the page's DOM, storage, IndexedDB (the key vault), cookies. No `allow-top-navigation`,\n * `allow-popups`, `allow-forms`, `allow-modals`, `allow-downloads` either.\n * 2. A Content-Security-Policy with no network source at all, given twice: as the first element\n * of the document itself, and by inheritance from the shell (3) - a `srcdoc` document takes\n * its parent's policy, which nothing inside the document can pre-empt.\n * 3. A shell document of ours between the page and the untrusted one. A frame may always\n * navigate ITSELF (`location = …`, a link, `<meta http-equiv=refresh>`): neither the sandbox\n * nor a document's own CSP stops that, and a navigation is a network request. The only thing\n * that does is the `frame-src` of the document that EMBEDS the frame - so we embed it in one\n * we wrote, whose policy says `frame-src 'none'`.\n */\n\nexport interface SandboxedDocumentOptions {\n /** Let the document's own inline scripts run (default false). */\n scripts?: boolean\n}\n\n/**\n * The policy of the framed document: nothing is fetched from anywhere. Inline styles, and\n * images / fonts / media the document carries inside itself (`data:`, `blob:`), are all it gets;\n * inline scripts only when asked for. `frame-src 'none'` is what stops the frame from navigating.\n */\nexport const sandboxedCsp = (scripts = false): string =>\n [\n \"default-src 'none'\",\n scripts ? \"script-src 'unsafe-inline'\" : \"script-src 'none'\",\n \"style-src 'unsafe-inline'\",\n 'img-src data: blob:',\n 'font-src data:',\n 'media-src data: blob:',\n \"connect-src 'none'\",\n \"frame-src 'none'\",\n \"child-src 'none'\",\n \"object-src 'none'\",\n \"form-action 'none'\",\n \"base-uri 'none'\",\n \"webrtc 'block'\",\n ].join('; ')\n\n/**\n * The `sandbox` attribute: empty (everything off) or `allow-scripts`. Never\n * `allow-same-origin`, never a navigation, popup, form, modal or download token.\n */\nexport const sandboxTokens = (scripts = false): string => (scripts ? 'allow-scripts' : '')\n\n/** A string as the value of a double-quoted HTML attribute. */\nexport const escapeAttribute = (value: string): string =>\n value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n\n/** A `<meta>` that carries a Content-Security-Policy. */\nexport const cspMetaTag = (policy: string): string =>\n `<meta http-equiv=\"Content-Security-Policy\" content=\"${escapeAttribute(policy)}\">`\n\nconst cspMeta = (scripts: boolean): string => cspMetaTag(sandboxedCsp(scripts))\n\n// A DOCTYPE token ends at the first \">\" whatever is inside it (the tokenizer's rule), so this is\n// exactly where the parser leaves it.\nconst DOCTYPE = /^[\\t\\n\\f\\r ]*<!doctype[^>]*>/i\n\n/**\n * The document with our policy as its FIRST element: right after a leading DOCTYPE (so the\n * page stays in standards mode), otherwise before everything. Nothing the document says can\n * come earlier - not its own `<meta>`, not a `<base>`, not a script before `<html>` - and a\n * later policy of its own can only narrow ours.\n */\nexport const withCspFirst = (html: string, scripts = false): string =>\n withPolicyFirst(html, sandboxedCsp(scripts))\n\n/** `withCspFirst` with a policy of the caller's (an MCP App's, built by `mcpAppCsp`). */\nexport const withPolicyFirst = (html: string, policy: string): string => {\n const doctype = DOCTYPE.exec(html)?.[0] ?? ''\n return `${doctype}${cspMetaTag(policy)}${html.slice(doctype.length)}`\n}\n\n/**\n * What goes into the outer frame's `srcdoc`: the shell (ours: the policy, and one inner frame\n * that fills it) carrying the untrusted document, escaped, as the inner frame's `srcdoc`.\n * Give the OUTER `<iframe>` the same `sandboxTokens(scripts)`.\n */\nexport const buildSandboxedDocument = (\n html: string,\n { scripts = false }: SandboxedDocumentOptions = {},\n): string =>\n '<!doctype html><html><head>' +\n cspMeta(scripts) +\n '<style>html,body{margin:0;height:100%;overflow:hidden;background:transparent}' +\n 'iframe{display:block;border:0;width:100%;height:100%}</style></head><body>' +\n `<iframe sandbox=\"${sandboxTokens(scripts)}\" referrerpolicy=\"no-referrer\" ` +\n `srcdoc=\"${escapeAttribute(withCspFirst(html, scripts))}\"></iframe></body></html>`\n\n/** HTML above this many characters is not framed at all - it is shown as source. */\nexport const HTML_PREVIEW_MAX_CHARS = 1_000_000\n\nconst ASSET_ATTR = /\\b(?:src|href)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'>]+))/gi\n\n/**\n * The files a document links to by a relative path (`style.css`, `./app.js`, `img/a.png`): the\n * preview does not load them, and says so. A hint for the user, not a guard - the policy is\n * what keeps them from loading.\n */\nexport const linkedFilesOf = (html: string, max = 4): string[] => {\n const found: string[] = []\n for (const m of html.matchAll(ASSET_ATTR)) {\n const ref = (m[1] ?? m[2] ?? m[3] ?? '').trim()\n if (!ref || /^(?:[a-z][a-z0-9+.-]*:|\\/\\/|#)/i.test(ref)) continue\n if (!found.includes(ref)) found.push(ref)\n if (found.length >= max) break\n }\n return found\n}\n\n/** A piece of HTML source, by what it is (for colouring the Source view). */\nexport interface SourceToken {\n kind: 'text' | 'tag' | 'attr' | 'string' | 'comment'\n text: string\n}\n\nconst RAW_TEXT = /^<(script|style|textarea|title)\\b/i\n\n/**\n * Split HTML source into coloured pieces. Lossless: the pieces joined are the input. It only\n * decides colours - the result is rendered as text nodes, never as markup.\n */\nexport const tokenizeHtml = (source: string): SourceToken[] => {\n const out: SourceToken[] = []\n const push = (kind: SourceToken['kind'], text: string) => {\n if (!text) return\n const last = out[out.length - 1]\n if (last && last.kind === kind) last.text += text\n else out.push({ kind, text })\n }\n let i = 0\n const n = source.length\n while (i < n) {\n const lt = source.indexOf('<', i)\n if (lt < 0) {\n push('text', source.slice(i))\n break\n }\n push('text', source.slice(i, lt))\n i = lt\n if (source.startsWith('<!--', i)) {\n const end = source.indexOf('-->', i + 4)\n const stop = end < 0 ? n : end + 3\n push('comment', source.slice(i, stop))\n i = stop\n continue\n }\n const open = /^<[!/?]?[a-zA-Z][^\\s/>]*/.exec(source.slice(i, i + 80))\n if (!open) {\n push('text', '<')\n i += 1\n continue\n }\n push('tag', open[0])\n const raw = RAW_TEXT.exec(open[0])?.[1].toLowerCase()\n i += open[0].length\n // Inside the tag, up to its \">\".\n while (i < n && source[i] !== '>') {\n const c = source[i]\n if (c === '\"' || c === \"'\") {\n const end = source.indexOf(c, i + 1)\n const stop = end < 0 ? n : end + 1\n push('string', source.slice(i, stop))\n i = stop\n } else if (/[^\\s=/>\"']/.test(c)) {\n const name = /^[^\\s=/>\"']+/.exec(source.slice(i, i + 200))?.[0] ?? c\n // After \"=\" it is an unquoted value; otherwise a name.\n const before = out[out.length - 1]\n push(before?.kind === 'text' && before.text.endsWith('=') ? 'string' : 'attr', name)\n i += name.length\n } else {\n push(c === '/' ? 'tag' : 'text', c)\n i += 1\n }\n }\n if (i < n) {\n push('tag', '>')\n i += 1\n }\n if (raw) {\n // The content of <script> / <style> is not markup: plain, up to its closing tag.\n const close = source.toLowerCase().indexOf(`</${raw}`, i)\n const stop = close < 0 ? n : close\n push('text', source.slice(i, stop))\n i = stop\n }\n }\n return out\n}\n\n/** The frame's height is the host's: a number of pixels between these, never the content's wish. */\nexport const FRAME_MIN_HEIGHT = 120\nexport const FRAME_MAX_HEIGHT = 800\n\nexport const clampFrameHeight = (height: number): number =>\n Math.min(\n FRAME_MAX_HEIGHT,\n Math.max(FRAME_MIN_HEIGHT, Math.round(Number.isFinite(height) ? height : 300)),\n )\n","/**\n * MCP Apps: what the host (the page, `mcp-app.ts`) and the sandbox proxy (a page on ANOTHER\n * origin, `mcp-app-sandbox.ts`) must agree on - the app's Content-Security-Policy, the policy as a\n * path segment of the proxy's URL, and the names of the sandbox messages. Pure code with NO\n * imports at all: the proxy's server bundles it without React or the core (a Worker), so the\n * origin rule below is a copy of the core's `mcpAppOrigin`, and `tests/apps-sandbox.test.ts`\n * holds the two to the same answers.\n */\n\n/** The proxy tells the host it can take the app (Sandbox → Host; content-free). */\nexport const MCP_APP_SANDBOX_PROXY_READY = 'ui/notifications/sandbox-proxy-ready'\n/** The host hands the proxy the app's HTML (Host → Sandbox), once. */\nexport const MCP_APP_SANDBOX_RESOURCE_READY = 'ui/notifications/sandbox-resource-ready'\n\n/** The specification reserves these between a host and its proxy: never relayed to or from an app. */\nexport const isMcpAppSandboxMessage = (data: unknown): boolean =>\n typeof data === 'object' &&\n data !== null &&\n typeof (data as { method?: unknown }).method === 'string' &&\n (data as { method: string }).method.startsWith('ui/notifications/sandbox-')\n\n/**\n * The colour scheme of an app's frame: the theme the app is told when its frame is drawn. Every\n * document between the page and the app declares it (the frame element, the shell, the sandbox\n * page and its frame), because a browser paints an OPAQUE canvas - the canvas colour of the\n * embedded document's own scheme - behind a document whose scheme differs from its frame\n * element's: an app that is dark with a transparent body was drawn on white.\n */\nexport type McpAppColorScheme = 'light' | 'dark'\n\n/** The query parameter of the sandbox page that carries the scheme (`?scheme=dark`). */\nexport const MCP_APP_SCHEME_PARAM = 'scheme'\n\n/** `light` or `dark` exactly; anything else is no scheme (nothing is declared). */\nexport const mcpAppColorScheme = (value: unknown): McpAppColorScheme | undefined =>\n value === 'light' || value === 'dark' ? value : undefined\n\n/** The origins an app's policy grants, each already an origin (`mcpAppPolicyOrigin`). */\nexport interface McpAppPolicyOrigins {\n /** `fetch` / XHR / WebSocket (`connect-src`). */\n connect: string[]\n /** Scripts, styles, images, fonts, media. */\n resources: string[]\n}\n\n/**\n * The policy of an app's document: scripts and styles inline, `data:` / `blob:` media, and the\n * network ONLY where the resource declared it. Nested frames, workers, plugins, forms and `<base>`\n * are refused whatever was declared (a frame the app may embed would also be a place it may\n * navigate itself to). The lists must already be checked origins: nothing here re-checks them.\n *\n * `'wasm-unsafe-eval'` lets the app compile WebAssembly (a tracer, a codec, a parser), which the\n * specification's default policy leaves out and a server cannot ask for (it declares origins, not\n * keywords). It adds no reach: a module only calls what the app's own script hands it, and the\n * network stays `connect-src`. `eval`, `new Function` and string timers stay refused - that is\n * `'unsafe-eval'`, which is never granted.\n */\nexport const mcpAppPolicy = ({ connect, resources }: McpAppPolicyOrigins): string => {\n const from = resources.length > 0 ? ` ${resources.join(' ')}` : ''\n return [\n \"default-src 'none'\",\n `script-src 'unsafe-inline' 'wasm-unsafe-eval'${from}`,\n `style-src 'unsafe-inline'${from}`,\n `img-src data: blob:${from}`,\n `font-src data:${from}`,\n `media-src data: blob:${from}`,\n connect.length > 0 ? `connect-src ${connect.join(' ')}` : \"connect-src 'none'\",\n \"frame-src 'none'\",\n \"child-src 'none'\",\n \"worker-src 'none'\",\n \"object-src 'none'\",\n \"form-action 'none'\",\n \"base-uri 'none'\",\n \"webrtc 'block'\",\n ].join('; ')\n}\n\n// ── The origin rule: a COPY of the core's `mcpAppOrigin` (src/mcp/apps.ts) ──────────────────\n\nconst LABEL = '[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?'\nconst HOST = `(?:\\\\*\\\\.)?${LABEL}(?:\\\\.${LABEL})*`\nconst PORT = '(?::\\\\d{1,5})?'\nconst SECURE_ORIGIN = new RegExp(`^(?:https|wss)://${HOST}${PORT}$`)\nconst LOOPBACK_ORIGIN = new RegExp(`^(?:http|ws)://(?:localhost|127\\\\.0\\\\.0\\\\.1|\\\\[::1\\\\])${PORT}$`)\n\n/**\n * One declared CSP entry as a source expression a policy may carry, or `undefined`: only an\n * origin (`https://` / `wss://`, a `*.` wildcard over at least two labels, or `http://` /\n * `ws://` on loopback). The same answers as the core's `mcpAppOrigin`, for the proxy's server.\n */\nexport const mcpAppPolicyOrigin = (entry: unknown): string | undefined => {\n if (typeof entry !== 'string' || entry.length > 300) return undefined\n const value = entry.trim().toLowerCase().replace(/\\/$/, '')\n if (SECURE_ORIGIN.test(value)) {\n const host = value.replace(/^[a-z]+:\\/\\//, '').replace(/:\\d+$/, '')\n if (host.startsWith('*.') && !host.slice(2).includes('.')) return undefined\n return value\n }\n return LOOPBACK_ORIGIN.test(value) ? value : undefined\n}\n\n// ── The policy in the proxy's URL ────────────────────────────────────────────────────────────\n\n/** At most this many origins per list (the core's `MCP_APP_MAX_DOMAINS`). */\nexport const MCP_APP_POLICY_MAX_ORIGINS = 32\n/** A policy token longer than this is not put in a URL: the app runs without its own origin. */\nexport const MCP_APP_POLICY_TOKEN_MAX_CHARS = 4096\n\nconst B64URL = /^[A-Za-z0-9_-]+$/\n\n/**\n * The policy as one path segment (base64url of `{\"c\":[…],\"r\":[…]}`), or `undefined` when it does\n * not fit. It is in the PATH, not the query, because a `frame-src` source expression matches a\n * path exactly and ignores the query: the host pins the proxy's frame to this one URL, so nothing\n * inside the frame can load the proxy page with a policy of its choosing.\n */\nexport const mcpAppPolicyToken = ({\n connect,\n resources,\n}: McpAppPolicyOrigins): string | undefined => {\n const json = JSON.stringify({ c: connect, r: resources })\n // Origins are ASCII; anything else is not a list of checked origins.\n if (/[^\\x20-\\x7e]/.test(json)) return undefined\n const token = btoa(json).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n return token.length <= MCP_APP_POLICY_TOKEN_MAX_CHARS ? token : undefined\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst originList = (value: unknown): string[] | undefined => {\n if (!Array.isArray(value) || value.length > MCP_APP_POLICY_MAX_ORIGINS) return undefined\n const out: string[] = []\n for (const entry of value) {\n // Exactly an origin as the host writes it: checked, canonical, once.\n if (typeof entry !== 'string' || mcpAppPolicyOrigin(entry) !== entry || out.includes(entry)) {\n return undefined\n }\n out.push(entry)\n }\n return out\n}\n\n/**\n * The policy a token stands for, or `undefined` for anything that is not exactly what\n * `mcpAppPolicyToken` writes: base64url of an object with the two lists and nothing else, every\n * entry an origin by the rule above, no more than `MCP_APP_POLICY_MAX_ORIGINS` each, the\n * canonical encoding (one URL per policy).\n */\nexport const mcpAppPolicyOfToken = (token: unknown): McpAppPolicyOrigins | undefined => {\n if (\n typeof token !== 'string' ||\n token.length === 0 ||\n token.length > MCP_APP_POLICY_TOKEN_MAX_CHARS ||\n !B64URL.test(token)\n ) {\n return undefined\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(atob(token.replace(/-/g, '+').replace(/_/g, '/')))\n } catch {\n return undefined\n }\n if (!isObject(parsed)) return undefined\n const keys = Object.keys(parsed)\n if (keys.length !== 2 || !keys.includes('c') || !keys.includes('r')) return undefined\n const connect = originList(parsed.c)\n const resources = originList(parsed.r)\n if (!connect || !resources) return undefined\n const policy = { connect, resources }\n return mcpAppPolicyToken(policy) === token ? policy : undefined\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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6B,QAAO;AAC5E,UAAI,KAAK,UAAU,UAAU;AAC3B,aAAK,QAAQ;AACb,eAAO;AAAA,MACT;AACA,WAAK,QAAQ;AACb,YAAM,UAAU,cAAc,KAAK,EAAE,GAAG;AACxC,WAAK,EAAE;AAAA,QACL;AAAA,UACE,SAAS;AAAA,UACT,QAAQ;AAAA,UACR,QAAQ,EAAE,MAAM,KAAK,EAAE,MAAM,KAAK,QAAQ;AAAA,QAC5C;AAAA,QACA,KAAK,EAAE;AAAA,MACT;AACA,aAAO;AAAA,IACT;AACA,WAAO,KAAK,UAAU,WAAW,QAAQ;AAAA,EAC3C;AAAA;AAAA,EAGA,KAAK,SAAwB;AAC3B,QAAI,KAAK,UAAU,SAAU,MAAK,EAAE,KAAK,SAAS,KAAK,EAAE,MAAM;AAAA,EACjE;AAAA,EAEA,QAAc;AACZ,QAAI,KAAK,UAAU,SAAU,MAAK,QAAQ;AAAA,EAC5C;AACF;AAMO,IAAM,kBAAkB,CAAC,UAAwB,QACtD,SAAS,WAAW,aACpB,SAAS,QAAQ,WAChB,SAAS,IAAI,UAAU,SACpB,SAAS,IAAI,UAAU,IAAI,KAC3B,SAAS,IAAI,WAAW,IAAI,UAAU,SAAS,IAAI,gBAAgB,IAAI;","names":["isObject"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/mcp-app.ts"],"sourcesContent":["import { mcpAppOrigin, type McpAppCsp } from '@dudko.dev/agent-web'\nimport { cspMetaTag, escapeAttribute, withPolicyFirst } from './html-preview.js'\nimport {\n isMcpAppSandboxMessage,\n MCP_APP_SANDBOX_PROXY_READY,\n MCP_APP_SANDBOX_RESOURCE_READY,\n MCP_APP_SCHEME_PARAM,\n mcpAppColorScheme,\n mcpAppPolicy,\n mcpAppPolicyToken,\n type McpAppColorScheme,\n} from './mcp-app-policy.js'\nimport type { AppView, ApprovalView } from './types.js'\n\n/**\n * MCP Apps, the host's side: the security core of `<McpAppFrame>`, as pure code - no React, no\n * DOM - so every guard is unit-tested (`tests/apps.test.ts`) and proved in a real browser\n * (`e2e/apps.spec.ts`).\n *\n * The frame: an app is third-party HTML WITH scripts that must talk to the page, so it gets the\n * HTML preview's boundary (`html-preview.ts`) and one addition, a relay:\n *\n * 1. The outer `<iframe sandbox=\"allow-scripts\">` (never `allow-same-origin`): an opaque origin,\n * no access to the page's DOM, storage, IndexedDB (the key vault) or cookies; no top\n * navigation, popups, forms, modals, downloads. No `allow` attribute: no camera, microphone,\n * geolocation or clipboard, whatever the app asked for.\n * 2. It holds a SHELL of ours (`buildMcpAppDocument`): the policy built from the resource's\n * declared origins and nothing else (`mcpAppCsp`), one inner frame - the app, also\n * `sandbox=\"allow-scripts\"`, with the same policy first in its own document - and a relay\n * script. The shell's `frame-src 'none'` is what stops the app navigating itself (a frame\n * may always navigate itself; only the EMBEDDING document's policy decides where to).\n * 3. The relay forwards messages between the page and the app, and nothing else: from the\n * app's window to the page, from the page to the app's window, never the\n * `ui/notifications/sandbox-*` messages the specification reserves. The app talks to\n * `window.parent` as the extension's SDK does; the page accepts messages only from the outer\n * frame (`event.source`), so the app writing to `window.top` directly is ignored.\n * 4. The bridge (`McpAppBridge`) answers the app: a method allow-list, checked parameters, a\n * cap on requests in flight, and every request that DOES something (a tool call, a link, a\n * message) handed to the host, which asks the user.\n *\n * That is the default. Opt-in, the app runs on an origin of its own instead, behind a sandbox\n * page the host serves on another origin (the specification's \"sandbox proxy\"): 1 - 3 change\n * (see \"An app on an origin of its own\" below and `mcp-app-policy.ts`), 4 does not.\n */\n\n/** The revision of the extension this host speaks. */\nexport const MCP_APP_PROTOCOL_VERSION = '2026-01-26'\n\n/** An app's frame height, before it says how tall it is. */\nexport const APP_DEFAULT_HEIGHT = 360\n/**\n * The frame's height is the host's: the app's wish, clamped to `APP_MIN_HEIGHT` .. the cap. The\n * cap is `appHeightCap` of the chat's visible height - a few screens, never less than\n * `APP_MAX_HEIGHT` - so an app as tall as its content has no scroller of its own inside the\n * transcript (one scroller: the chat's), and an app that grows forever stops there.\n */\nexport const APP_MIN_HEIGHT = 120\n/** The least the cap is (and the cap where nothing says how tall the chat is). */\nexport const APP_MAX_HEIGHT = 800\n/** The cap is this many of the chat's visible heights. */\nexport const APP_HEIGHT_SCREENS = 3\n/** ... and never more than this, whatever the screen. */\nexport const APP_HEIGHT_CEILING = 6000\n\n/**\n * The tallest an inline app's frame is drawn, for a chat body (or viewport) `viewHeight` px tall:\n * `APP_HEIGHT_SCREENS` of it, rounded down to 100 px (the app is told it in\n * `containerDimensions.maxHeight`, and a resize of a few pixels must not tell it again), at least\n * `APP_MAX_HEIGHT`, at most `APP_HEIGHT_CEILING`.\n */\nexport const appHeightCap = (viewHeight: number | undefined): number => {\n if (typeof viewHeight !== 'number' || !Number.isFinite(viewHeight) || viewHeight <= 0) {\n return APP_MAX_HEIGHT\n }\n const screens = Math.floor((viewHeight * APP_HEIGHT_SCREENS) / 100) * 100\n return Math.min(APP_HEIGHT_CEILING, Math.max(APP_MAX_HEIGHT, screens))\n}\n\n/**\n * The cap of a frame that is already drawn, when the chat's height changes: `appHeightCap` of the\n * new height, but never less than the cap the frame had (`current`) - a rotation, a keyboard\n * resizing the page or a relayout for a touch screen must not give an app that was drawn whole a\n * scroller of its own. The cap only grows while the frame is shown (at most\n * `APP_HEIGHT_CEILING`); a new frame starts from the cap of its moment.\n */\nexport const nextAppHeightCap = (current: number, viewHeight: number | undefined): number => {\n const now = appHeightCap(viewHeight)\n return Number.isFinite(current) && current > now ? Math.min(APP_HEIGHT_CEILING, current) : now\n}\n\n/** At most this many requests of one app wait at once (tool calls, links, messages). */\nexport const MCP_APP_MAX_IN_FLIGHT = 3\n/** A message an app puts in the chat: at most this many characters. */\nexport const MCP_APP_MAX_MESSAGE_CHARS = 4000\n/** A link an app asks to open: at most this many characters. */\nexport const MCP_APP_MAX_URL_CHARS = 2048\n/** The arguments of a tool call an app makes: at most this many characters as JSON. */\nexport const MCP_APP_MAX_ARGS_CHARS = 64_000\n\n/** An app's wish for a height, as the frame draws it: within `APP_MIN_HEIGHT` .. `max` (the cap). */\nexport const clampAppHeight = (height: number, max: number = APP_MAX_HEIGHT): number =>\n Math.min(\n Math.max(\n APP_MIN_HEIGHT,\n Math.min(APP_HEIGHT_CEILING, Number.isFinite(max) ? max : APP_MAX_HEIGHT),\n ),\n Math.max(APP_MIN_HEIGHT, Math.round(Number.isFinite(height) ? height : APP_DEFAULT_HEIGHT)),\n )\n\n/** The declared origins of a list that are origins (re-checked here: whoever built the object). */\nconst origins = (list: readonly string[] | undefined): string[] => {\n const out: string[] = []\n for (const entry of list ?? []) {\n const origin = mcpAppOrigin(entry)\n if (origin && !out.includes(origin)) out.push(origin)\n }\n return out\n}\n\n/**\n * The policy of an app's document: scripts and styles inline, `data:` / `blob:` media, and the\n * network ONLY where the resource declared it - `connectDomains` for `fetch` / XHR / WebSocket,\n * `resourceDomains` for scripts, styles, images, fonts and media. Nothing declared, nothing\n * reached. Nested frames, workers, plugins, forms and `<base>` are refused whatever was declared\n * (`frameDomains` / `baseUriDomains` are not granted: a frame the app may embed would also be a\n * place it may navigate itself to). Each entry is checked again with the core's `mcpAppOrigin`.\n */\nexport const mcpAppCsp = (csp?: Partial<McpAppCsp>): string =>\n mcpAppPolicy({ connect: origins(csp?.connectDomains), resources: origins(csp?.resourceDomains) })\n\n/** The origins the policy actually grants: what the app is told in `hostCapabilities.sandbox`. */\nexport const grantedAppCsp = (\n csp?: Partial<McpAppCsp>,\n): { connectDomains: string[]; resourceDomains: string[] } => ({\n connectDomains: origins(csp?.connectDomains),\n resourceDomains: origins(csp?.resourceDomains),\n})\n\n/**\n * The relay of the shell: the app's messages to the page, the page's to the app - matched by\n * `event.source`, never by anything the message says - and not the reserved\n * `ui/notifications/sandbox-*` ones. It reads nothing else and runs nothing it is sent.\n */\nexport const MCP_APP_RELAY =\n \"(function(){var f=document.getElementById('app');\" +\n \"function reserved(d){return !!d&&typeof d.method==='string'&&d.method.indexOf('ui/notifications/sandbox-')===0}\" +\n \"addEventListener('message',function(e){var w=f&&f.contentWindow;if(!w||reserved(e.data))return;\" +\n \"if(e.source===w){parent.postMessage(e.data,'*')}else if(e.source===parent){w.postMessage(e.data,'*')}})})()\"\n\n/**\n * What a document of ours between the page and the app says about its colour scheme: the\n * `color-scheme` meta and the same on `:root` and on its frame element, so the document, its\n * frame and (for an app that declares the same) the app agree and no canvas is painted opaque\n * between them. Nothing for anything but `light` / `dark`.\n */\nconst schemeMeta = (scheme: McpAppColorScheme | undefined): string =>\n scheme ? `<meta name=\"color-scheme\" content=\"${scheme}\">` : ''\nconst schemeCss = (scheme: McpAppColorScheme | undefined): string =>\n scheme ? `:root{color-scheme:${scheme}}` : ''\nconst schemeOfFrame = (scheme: McpAppColorScheme | undefined): string =>\n scheme ? `;color-scheme:${scheme}` : ''\n\n/**\n * What goes into the OUTER frame's `srcdoc`: the shell (the app's policy first, one inner frame\n * that fills it, the relay) carrying the app, escaped, as the inner frame's `srcdoc` - with the\n * same policy first in it. Give the outer `<iframe>` `sandbox=\"allow-scripts\"` and nothing else.\n * `scheme` (the theme the app is told) is declared by the shell and its inner frame; give the\n * outer `<iframe>` the same `color-scheme`. Only `light` / `dark` are declared.\n */\nexport const buildMcpAppDocument = (\n html: string,\n csp?: Partial<McpAppCsp>,\n scheme?: McpAppColorScheme,\n): string => {\n const policy = mcpAppCsp(csp)\n const s = mcpAppColorScheme(scheme)\n return (\n '<!doctype html><html><head>' +\n `<meta http-equiv=\"Content-Security-Policy\" content=\"${escapeAttribute(policy)}\">` +\n schemeMeta(s) +\n `<style>${schemeCss(s)}html,body{margin:0;height:100%;overflow:hidden;background:transparent}` +\n `iframe{display:block;border:0;width:100%;height:100%${schemeOfFrame(s)}}</style></head><body>` +\n `<iframe id=\"app\" sandbox=\"allow-scripts\" referrerpolicy=\"no-referrer\" ` +\n `srcdoc=\"${escapeAttribute(withPolicyFirst(html, policy))}\"></iframe>` +\n `<script>${MCP_APP_RELAY}</script></body></html>`\n )\n}\n\n/** A link an app asks to open, taken apart for the prompt: the host is what the user checks. */\nexport interface AppLink {\n /** The normalised URL (what is opened). */\n href: string\n /** `https://` */\n scheme: string\n /** The host (and port), as the browser will go there - an internationalised name in punycode. */\n host: string\n /** Everything after the host. */\n rest: string\n}\n\n/** An `http(s)` URL with a host and no credentials, at most `MCP_APP_MAX_URL_CHARS`; else none. */\nexport const appLinkOf = (value: unknown): AppLink | undefined => {\n if (typeof value !== 'string' || value.length > MCP_APP_MAX_URL_CHARS) return undefined\n let url: URL\n try {\n url = new URL(value)\n } catch {\n return undefined\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') return undefined\n if (url.username || url.password || !url.hostname) return undefined\n const scheme = `${url.protocol}//`\n return {\n href: url.href,\n scheme,\n host: url.host,\n rest: url.href.slice(scheme.length + url.host.length),\n }\n}\n\n// Characters that change how text reads without being seen (bidirectional overrides,\n// zero-width) and control characters other than line breaks and tabs.\n// eslint-disable-next-line no-control-regex\nconst HIDDEN = /[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f​-‏‪-‮⁦-⁩]/g\n\n/**\n * The text of a `ui/message` an app sends: text blocks only (one, or a list of at most 20),\n * joined, without invisible characters, at most `MCP_APP_MAX_MESSAGE_CHARS`. Anything else -\n * an image, a resource, an empty or a longer text - is refused (`undefined`).\n */\nexport const appMessageTextOf = (content: unknown): string | undefined => {\n const blocks = Array.isArray(content) ? content : content === undefined ? [] : [content]\n if (blocks.length === 0 || blocks.length > 20) return undefined\n const texts: string[] = []\n for (const block of blocks) {\n if (!isObject(block) || block.type !== 'text' || typeof block.text !== 'string') {\n return undefined\n }\n texts.push(block.text)\n }\n const text = texts.join('\\n\\n').replace(HIDDEN, '').trim()\n return text && text.length <= MCP_APP_MAX_MESSAGE_CHARS ? text : undefined\n}\n\ntype Obj = Record<string, unknown>\nconst isObject = (value: unknown): value is Obj =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** A JSON-RPC message as the bridge sends it. */\nexport type McpAppRpcMessage =\n | { jsonrpc: '2.0'; id: string | number; method: string; params?: unknown }\n | { jsonrpc: '2.0'; method: string; params?: unknown }\n | { jsonrpc: '2.0'; id: string | number; result: unknown }\n | { jsonrpc: '2.0'; id: string | number; error: { code: number; message: string } }\n\n/** The requests an app may make of this host. Any other is answered \"method not found\". */\nexport const MCP_APP_REQUESTS = [\n 'ui/initialize',\n 'ping',\n 'tools/call',\n 'ui/open-link',\n 'ui/message',\n 'ui/request-display-mode',\n] as const\n/**\n * Requests answered only when the host turned the feature on (`downloadFile` / `sampling` in\n * `hostCapabilities`, a handler given to the bridge); otherwise \"method not found\", as before.\n */\nexport const MCP_APP_OPTIONAL_REQUESTS = ['ui/download-file', 'sampling/createMessage'] as const\n/** The notifications this host reads. Any other is dropped. */\nexport const MCP_APP_NOTIFICATIONS = [\n 'ui/notifications/initialized',\n 'ui/notifications/size-changed',\n] as const\n\n/** An error the bridge answers with: a JSON-RPC code and a message for the app. */\nexport class McpAppRpcError extends Error {\n constructor(\n readonly code: number,\n message: string,\n ) {\n super(message)\n this.name = 'McpAppRpcError'\n }\n}\n\nconst METHOD_NOT_FOUND = -32601\nconst INVALID_PARAMS = -32602\nconst INVALID_REQUEST = -32600\n/** The host refused: the user said no, too many requests, not initialized. */\nexport const MCP_APP_REFUSED = -32000\n\n/** How an app is shown (`hostContext.displayMode`). This host offers `inline` and `fullscreen`. */\nexport type McpAppDisplayMode = 'inline' | 'fullscreen' | 'pip'\n/** The modes the extension names (a request for any other is invalid). */\nexport const MCP_APP_DISPLAY_MODES: readonly McpAppDisplayMode[] = ['inline', 'fullscreen', 'pip']\n\n/** A file an app asks the host to save (`ui/download-file`), as checked by `appDownloadOf`. */\nexport type AppDownload =\n | {\n kind: 'embedded'\n /** The file name, sanitized (`appFileNameOf`): what it is saved as. */\n name: string\n /** The type the app declared, if it is a MIME type at all. */\n mimeType?: string\n bytes: Uint8Array\n }\n | {\n /** A `resource_link`: read with `resources/read` on the app's own server, never fetched. */\n kind: 'link'\n uri: string\n name: string\n mimeType?: string\n }\n\n/** What the host does for an app (the user is asked inside these, never by the bridge). */\nexport interface McpAppBridgeHandlers {\n /** A `tools/call`: resolves with the result the app is given; throws when refused. */\n callTool: (name: string, args: Record<string, unknown>) => Promise<unknown>\n /** A link (already checked): resolves true when it was opened, false when the user said no. */\n openLink: (link: AppLink) => Promise<boolean>\n /** A message (already cleaned): resolves true when it was accepted, false when not. */\n message: (text: string) => Promise<boolean>\n /** The app's wish for a height (the caller clamps it). */\n resize: (height: number) => void\n /**\n * `ui/request-display-mode` for a mode the host offers and the app declared (or `inline`):\n * the mode the app is in afterwards - the host may say no and answer the current one.\n * Without it, an app stays where it is.\n */\n displayMode?: (mode: McpAppDisplayMode) => McpAppDisplayMode | Promise<McpAppDisplayMode>\n /**\n * `ui/download-file` (already checked): true once the file was saved, false when the user said\n * no. Without it the method is not offered (`hostCapabilities.downloadFile` absent).\n */\n downloadFile?: (file: AppDownload) => Promise<boolean>\n /**\n * `sampling/createMessage`: the result for the app; throws (an `McpAppRpcError`) when refused.\n * Without it the method is not offered (`hostCapabilities.sampling` absent).\n */\n sample?: (params: Record<string, unknown>) => Promise<unknown>\n}\n\nexport interface McpAppBridgeOptions {\n /** Send a message to the app (the page posts it to the outer frame). */\n post: (message: McpAppRpcMessage) => void\n handlers: McpAppBridgeHandlers\n hostInfo: { name: string; version: string }\n hostCapabilities: Record<string, unknown>\n hostContext: Record<string, unknown>\n /** The tool call's arguments: sent once the app says it is initialized. */\n toolInput: Record<string, unknown>\n /** Its result; `undefined` = the app is told the call was cancelled (`reason`). */\n toolResult?: unknown\n cancelledReason?: string\n maxInFlight?: number\n}\n\nconst validId = (id: unknown): id is string | number =>\n (typeof id === 'string' && id.length > 0 && id.length <= 100) ||\n (typeof id === 'number' && Number.isFinite(id))\n\n/**\n * One app's conversation with the host (the extension's JSON-RPC over `postMessage`). It never\n * touches the DOM: `receive` is given what arrived - from the right frame, the caller checked\n * `event.source` - and `post` sends. Requests outside the allow-list get \"method not found\";\n * before `ui/initialize`, only `ping` is answered; parameters are checked before a handler sees\n * them; at most `maxInFlight` requests run at once. The tool's input and result are sent once,\n * after the app's `ui/notifications/initialized`, as the specification requires.\n */\nexport class McpAppBridge {\n private readonly o: McpAppBridgeOptions\n private initializeSeen = false\n private delivered = false\n private inFlight = 0\n private closed = false\n private seq = 0\n // The display modes the app declared at `ui/initialize` (undefined: none declared).\n private appModes: McpAppDisplayMode[] | undefined\n\n constructor(options: McpAppBridgeOptions) {\n this.o = options\n }\n\n /** The app said it is ready, and was given the tool's input and result. */\n get initialized(): boolean {\n return this.delivered\n }\n\n /** Stop answering: the frame is gone or was reloaded. */\n close(): void {\n this.closed = true\n }\n\n /** Tell the app it is being torn down (not waited for: the frame goes anyway). */\n teardown(reason: string): void {\n if (!this.delivered || this.closed) return\n this.seq += 1\n this.send({\n jsonrpc: '2.0',\n id: `host-teardown-${this.seq}`,\n method: 'ui/resource-teardown',\n params: { reason },\n })\n }\n\n /** The display modes the app declared at `ui/initialize` (undefined: none, or not yet). */\n get appDisplayModes(): readonly McpAppDisplayMode[] | undefined {\n return this.appModes ? [...this.appModes] : undefined\n }\n\n /** How the app is shown now (`hostContext.displayMode`). */\n get displayMode(): McpAppDisplayMode {\n const mode = this.o.hostContext.displayMode\n return MCP_APP_DISPLAY_MODES.includes(mode as McpAppDisplayMode)\n ? (mode as McpAppDisplayMode)\n : 'inline'\n }\n\n /** Tell an initialized app that part of the host context changed (the theme). */\n updateContext(patch: Record<string, unknown>): void {\n Object.assign(this.o.hostContext, patch)\n if (this.delivered && !this.closed) {\n this.send({ jsonrpc: '2.0', method: 'ui/notifications/host-context-changed', params: patch })\n }\n }\n\n /** One message from the app's frame. */\n receive(data: unknown): void {\n if (this.closed || !isObject(data) || data.jsonrpc !== '2.0') return\n const method = data.method\n const id = data.id\n if (method === undefined) return // a response to a request of ours: nothing waits for it\n if (typeof method !== 'string' || method.length === 0 || method.length > 100) {\n if (validId(id)) this.error(id, INVALID_REQUEST, 'Invalid request')\n return\n }\n if (id === undefined) {\n this.notification(method, data.params)\n return\n }\n if (!validId(id)) return\n if (data.params !== undefined && !isObject(data.params)) {\n this.error(id, INVALID_PARAMS, 'params must be an object')\n return\n }\n void this.request(id, method, (data.params ?? {}) as Obj)\n }\n\n private send(message: McpAppRpcMessage): void {\n if (!this.closed) this.o.post(message)\n }\n\n private error(id: string | number, code: number, message: string): void {\n this.send({ jsonrpc: '2.0', id, error: { code, message } })\n }\n\n private notification(method: string, params: unknown): void {\n const p = isObject(params) ? params : {}\n if (method === 'ui/notifications/initialized') {\n if (!this.initializeSeen || this.delivered) return\n this.delivered = true\n this.send({\n jsonrpc: '2.0',\n method: 'ui/notifications/tool-input',\n params: { arguments: this.o.toolInput },\n })\n this.send(\n this.o.toolResult === undefined\n ? {\n jsonrpc: '2.0',\n method: 'ui/notifications/tool-cancelled',\n params: { reason: this.o.cancelledReason ?? 'no result' },\n }\n : { jsonrpc: '2.0', method: 'ui/notifications/tool-result', params: this.o.toolResult },\n )\n return\n }\n if (method === 'ui/notifications/size-changed') {\n if (typeof p.height === 'number' && Number.isFinite(p.height) && p.height > 0) {\n this.o.handlers.resize(p.height)\n }\n }\n // Anything else (a log line, a teardown wish, an unknown one) is dropped.\n }\n\n private async request(id: string | number, method: string, params: Obj): Promise<void> {\n const h = this.o.handlers\n const offered =\n (MCP_APP_REQUESTS as readonly string[]).includes(method) ||\n (method === 'ui/download-file' && typeof h.downloadFile === 'function') ||\n (method === 'sampling/createMessage' && typeof h.sample === 'function')\n if (!offered) {\n this.error(id, METHOD_NOT_FOUND, `Method not found: ${method.slice(0, 60)}`)\n return\n }\n if (method === 'ping') {\n this.send({ jsonrpc: '2.0', id, result: {} })\n return\n }\n if (method === 'ui/initialize') {\n this.initializeSeen = true\n const caps = isObject(params.appCapabilities) ? params.appCapabilities : {}\n this.appModes = Array.isArray(caps.availableDisplayModes)\n ? caps.availableDisplayModes.filter((m): m is McpAppDisplayMode =>\n MCP_APP_DISPLAY_MODES.includes(m as McpAppDisplayMode),\n )\n : undefined\n this.send({\n jsonrpc: '2.0',\n id,\n result: {\n protocolVersion: MCP_APP_PROTOCOL_VERSION,\n hostInfo: this.o.hostInfo,\n hostCapabilities: this.o.hostCapabilities,\n hostContext: this.o.hostContext,\n },\n })\n return\n }\n if (!this.initializeSeen) {\n this.error(id, MCP_APP_REFUSED, 'The app is not initialized (send ui/initialize first)')\n return\n }\n if (method === 'ui/request-display-mode') {\n const requested = params.mode\n if (!MCP_APP_DISPLAY_MODES.includes(requested as McpAppDisplayMode)) {\n this.error(id, INVALID_PARAMS, 'mode must be \"inline\", \"fullscreen\" or \"pip\"')\n return\n }\n // The host decides where an app is shown, and answers the mode it is in afterwards.\n const current = this.displayMode\n const host = Array.isArray(this.o.hostContext.availableDisplayModes)\n ? (this.o.hostContext.availableDisplayModes as McpAppDisplayMode[])\n : ['inline' as const]\n let mode: McpAppDisplayMode = current\n if (\n h.displayMode &&\n appDisplayModeAllowed({\n requested: requested as McpAppDisplayMode,\n current,\n host,\n app: this.appModes,\n })\n ) {\n try {\n const next = await h.displayMode(requested as McpAppDisplayMode)\n mode = MCP_APP_DISPLAY_MODES.includes(next) ? next : current\n } catch {\n mode = this.displayMode\n }\n }\n this.send({ jsonrpc: '2.0', id, result: { mode } })\n return\n }\n // What remains does something the user is asked about: capped, then handed over.\n let run: (() => Promise<unknown>) | undefined\n if (method === 'tools/call') {\n const name = params.name\n const args = params.arguments === undefined ? {} : params.arguments\n if (typeof name !== 'string' || name.length === 0 || name.length > 128) {\n this.error(id, INVALID_PARAMS, 'tools/call needs the name of a tool')\n return\n }\n if (!isObject(args)) {\n this.error(id, INVALID_PARAMS, 'tools/call arguments must be an object')\n return\n }\n let size = Infinity\n try {\n size = JSON.stringify(args).length\n } catch {\n // not serialisable: refused below\n }\n if (size > MCP_APP_MAX_ARGS_CHARS) {\n this.error(id, INVALID_PARAMS, 'tools/call arguments are too large')\n return\n }\n run = () => this.o.handlers.callTool(name, args)\n } else if (method === 'ui/download-file') {\n const file = appDownloadOf(params)\n if (typeof file === 'string') {\n this.error(id, INVALID_PARAMS, file)\n return\n }\n const save = h.downloadFile!\n // Denied (or not saved): a result with `isError`, as the extension's SDK expects.\n run = async () => ((await save(file)) ? {} : { isError: true })\n } else if (method === 'sampling/createMessage') {\n const sample = h.sample!\n run = () => sample(params)\n } else if (method === 'ui/open-link') {\n const link = appLinkOf(params.url)\n if (!link) {\n this.error(id, INVALID_PARAMS, 'Invalid URL: only http(s) links without credentials')\n return\n }\n run = async () => {\n if (!(await this.o.handlers.openLink(link))) {\n throw new McpAppRpcError(MCP_APP_REFUSED, 'Link opening denied by user')\n }\n return {}\n }\n } else {\n const text = params.role === 'user' ? appMessageTextOf(params.content) : undefined\n if (text === undefined) {\n this.error(\n id,\n INVALID_PARAMS,\n 'Invalid message format: one user text, not empty, not too long',\n )\n return\n }\n run = async () => {\n if (!(await this.o.handlers.message(text))) {\n throw new McpAppRpcError(MCP_APP_REFUSED, 'Message sending denied')\n }\n return {}\n }\n }\n const cap = this.o.maxInFlight ?? MCP_APP_MAX_IN_FLIGHT\n if (this.inFlight >= cap) {\n this.error(id, MCP_APP_REFUSED, 'Too many requests of this app are waiting')\n return\n }\n this.inFlight += 1\n try {\n const result = await run()\n this.send({ jsonrpc: '2.0', id, result })\n } catch (err) {\n const code = err instanceof McpAppRpcError ? err.code : MCP_APP_REFUSED\n const message = (err instanceof Error ? err.message : String(err)).slice(0, 300)\n this.error(id, code, message)\n } finally {\n this.inFlight -= 1\n }\n }\n}\n\n/**\n * What this host tells an app it can do (`hostCapabilities` of `ui/initialize`): only what it\n * does. `downloadFile` and `sampling` (never `sampling.tools`) only when the host turned them on.\n */\nexport const mcpAppHostCapabilities = (\n csp?: Partial<McpAppCsp>,\n features: { downloadFile?: boolean; sampling?: boolean } = {},\n): Record<string, unknown> => ({\n openLinks: {},\n serverTools: {},\n message: { text: {} },\n ...(features.downloadFile ? { downloadFile: {} } : {}),\n ...(features.sampling ? { sampling: {} } : {}),\n // What the frame grants: the declared origins it kept; no permission at all.\n sandbox: { permissions: {}, csp: grantedAppCsp(csp) },\n})\n\n// ── Display modes ───────────────────────────────────────────────────────────────────────────\n\n/**\n * Whether a display mode an app asks for may be given: `inline` always (the way back needs no\n * permission); any other only when the host offers it AND the app declared it in\n * `appCapabilities.availableDisplayModes` - an app that declared nothing stays inline (the\n * specification lets a host decline it).\n */\nexport const appDisplayModeAllowed = (o: {\n requested: McpAppDisplayMode\n current: McpAppDisplayMode\n host: readonly McpAppDisplayMode[]\n app: readonly McpAppDisplayMode[] | undefined\n}): boolean =>\n o.requested === o.current ||\n o.requested === 'inline' ||\n (o.host.includes(o.requested) && (o.app?.includes(o.requested) ?? false))\n\n/**\n * Whether the user just acted INSIDE the app's frame: the page's frame element has the focus\n * (a click or a key in a frame focuses it) and the page has transient user activation (an\n * activation in a frame reaches every page above it, for a few seconds). Where the browser has\n * no `navigator.userActivation`, the focus alone.\n */\nexport const appGestureOf = (o: { focused: boolean; activation: boolean | undefined }): boolean =>\n o.focused && o.activation !== false\n\n// ── Downloads: a file the app hands the host to save ────────────────────────────────────────\n\n/** A file an app asks to save: at most this many bytes. */\nexport const MCP_APP_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024\n/** A saved file's name: at most this many characters (the extension kept). */\nexport const MCP_APP_MAX_FILE_NAME_CHARS = 100\n\n/**\n * Extensions this host never saves: programs, scripts, installers, shortcuts, disk images - and\n * documents a browser runs scripts in when they are opened (HTML, SVG, XML).\n */\nexport const MCP_APP_REFUSED_DOWNLOAD_EXTENSIONS: readonly string[] = [\n 'exe',\n 'com',\n 'bat',\n 'cmd',\n 'scr',\n 'pif',\n 'msi',\n 'msp',\n 'mst',\n 'msc',\n 'cpl',\n 'dll',\n 'sys',\n 'ps1',\n 'psm1',\n 'psd1',\n 'vbs',\n 'vbe',\n 'js',\n 'jse',\n 'mjs',\n 'cjs',\n 'wsf',\n 'wsh',\n 'ws',\n 'hta',\n 'jar',\n 'jnlp',\n 'lnk',\n 'reg',\n 'inf',\n 'scf',\n 'url',\n 'website',\n 'application',\n 'gadget',\n 'sh',\n 'bash',\n 'zsh',\n 'csh',\n 'ksh',\n 'command',\n 'tool',\n 'app',\n 'pkg',\n 'mpkg',\n 'dmg',\n 'deb',\n 'rpm',\n 'apk',\n 'xapk',\n 'appimage',\n 'run',\n 'bin',\n 'elf',\n 'out',\n 'py',\n 'pyw',\n 'pyz',\n 'pl',\n 'rb',\n 'php',\n 'html',\n 'htm',\n 'xhtml',\n 'xht',\n 'shtml',\n 'mht',\n 'mhtml',\n 'svg',\n 'svgz',\n 'xml',\n 'xsl',\n 'xslt',\n 'webloc',\n 'desktop',\n 'iso',\n 'img',\n 'vhd',\n 'vhdx',\n 'library-ms',\n 'settingcontent-ms',\n]\n\n/** Types this host never saves (the same kinds), and any `…+xml`. */\nexport const MCP_APP_REFUSED_DOWNLOAD_TYPES: readonly string[] = [\n 'text/html',\n 'application/xhtml+xml',\n 'image/svg+xml',\n 'application/xml',\n 'text/xml',\n 'text/javascript',\n 'application/javascript',\n 'application/ecmascript',\n 'application/x-javascript',\n 'application/x-msdownload',\n 'application/x-msdos-program',\n 'application/x-msi',\n 'application/x-ms-installer',\n 'application/vnd.microsoft.portable-executable',\n 'application/x-executable',\n 'application/x-elf',\n 'application/x-sh',\n 'application/x-shellscript',\n 'application/x-csh',\n 'application/java-archive',\n 'application/x-java-jnlp-file',\n 'application/hta',\n 'application/x-apple-diskimage',\n 'application/vnd.android.package-archive',\n 'application/x-python-code',\n 'text/x-python',\n 'application/x-httpd-php',\n]\n\nconst MIME = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/\n\n/** A declared type as a bare MIME type (`text/plain`), or undefined when it is not one. */\nexport const appMimeTypeOf = (value: unknown): string | undefined => {\n if (typeof value !== 'string') return undefined\n const type = value.split(';')[0]!.trim().toLowerCase()\n return MIME.test(type) ? type : undefined\n}\n\n// Device names Windows will not let a file be called (with any extension).\nconst RESERVED_NAME = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\\..*)?$/i\n\n/**\n * The name a file is saved under: the last segment of a path or URI (`file:///x/report.json` →\n * `report.json`; percent-encoding decoded, and split again), without what cannot be seen or\n * reserved characters (`<>:\"/\\|?*`, controls), no leading dots (a hidden file) or trailing dots\n * and spaces, not a Windows device name, at most `MCP_APP_MAX_FILE_NAME_CHARS` with the extension\n * kept; `download` when nothing is left.\n */\nexport const appFileNameOf = (value: unknown): string => {\n let name = typeof value === 'string' ? value.slice(0, 2048) : ''\n name = name.replace(/[?#].*$/s, '')\n name = name.split(/[\\\\/]/).pop() ?? ''\n try {\n name = decodeURIComponent(name)\n } catch {\n // not percent-encoded: as it is\n }\n name = (name.split(/[\\\\/]/).pop() ?? '')\n .replace(HIDDEN, '')\n // eslint-disable-next-line no-control-regex\n .replace(/[<>:\"|?*\\u0000-\\u001f\\u007f]/g, '_')\n .replace(/\\s+/g, ' ')\n .replace(/^[.\\s]+/, '')\n .replace(/[.\\s]+$/, '')\n if (RESERVED_NAME.test(name)) name = `_${name}`\n if (name.length > MCP_APP_MAX_FILE_NAME_CHARS) {\n const dot = name.lastIndexOf('.')\n const ext = dot > 0 && name.length - dot <= 16 ? name.slice(dot) : ''\n name = name.slice(0, MCP_APP_MAX_FILE_NAME_CHARS - ext.length).replace(/[.\\s]+$/, '') + ext\n }\n return name || 'download'\n}\n\n/** The extension of a (sanitized) file name, lowercased, without the dot; '' when none. */\nexport const appFileExtensionOf = (name: string): string => {\n const dot = name.lastIndexOf('.')\n return dot > 0 ? name.slice(dot + 1).toLowerCase() : ''\n}\n\n/**\n * Why a file may not be saved, or undefined when it may: an extension or a type of the refused\n * lists (a program, a script, a page a browser would run), checked on the sanitized name and\n * the declared type both.\n */\nexport const appDownloadRefusal = (name: string, mimeType?: string): string | undefined => {\n const ext = appFileExtensionOf(name)\n if (MCP_APP_REFUSED_DOWNLOAD_EXTENSIONS.includes(ext)) return `“.${ext}” files are not saved`\n const type = appMimeTypeOf(mimeType)\n if (type && (MCP_APP_REFUSED_DOWNLOAD_TYPES.includes(type) || type.endsWith('+xml'))) {\n return `${type} files are not saved`\n }\n return undefined\n}\n\nconst URI_LINE = /^[^\\u0000-\\u001f\\u007f\\s]{1,2048}$/\n\nconst bytesOfBase64 = (blob: string, maxBytes: number): Uint8Array | string => {\n if (blob.length > Math.ceil((maxBytes * 4) / 3) + 4)\n return `the file is larger than ${maxBytes} bytes`\n if (!/^[A-Za-z0-9+/\\s]*={0,2}\\s*$/.test(blob)) return 'blob must be base64'\n try {\n const binary = atob(blob.replace(/\\s+/g, ''))\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)\n return bytes\n } catch {\n return 'blob must be base64'\n }\n}\n\n/**\n * What `ui/download-file` asks for, checked - or why not (a message for the app): ONE item of\n * `contents` (one file per request, one prompt); an `EmbeddedResource` (`resource.uri` names\n * it, `text` as UTF-8 or base64 `blob`, at most `maxBytes`) or a `ResourceLink` (a one-line URI,\n * read later from the app's own server: the name is its last segment, else its `name`); the\n * name sanitized and the name and type not refused (`appDownloadRefusal`).\n */\nexport const appDownloadOf = (\n params: unknown,\n maxBytes: number = MCP_APP_MAX_DOWNLOAD_BYTES,\n): AppDownload | string => {\n const contents = isObject(params) ? params.contents : undefined\n if (!Array.isArray(contents) || contents.length === 0) return 'contents must list the file'\n if (contents.length > 1) return 'One file per request'\n const item = contents[0]\n if (!isObject(item)) return 'Invalid content'\n if (item.type === 'resource') {\n const r = item.resource\n if (!isObject(r) || typeof r.uri !== 'string' || !URI_LINE.test(r.uri)) {\n return 'Invalid content: resource.uri names the file'\n }\n const name = appFileNameOf(r.uri)\n const mimeType = appMimeTypeOf(r.mimeType)\n const refused = appDownloadRefusal(name, mimeType)\n if (refused) return `Policy violation: ${refused}`\n let bytes: Uint8Array | string\n if (typeof r.text === 'string') {\n bytes =\n r.text.length > maxBytes\n ? `the file is larger than ${maxBytes} bytes`\n : new TextEncoder().encode(r.text)\n } else if (typeof r.blob === 'string') {\n bytes = bytesOfBase64(r.blob, maxBytes)\n } else {\n return 'Invalid content: text or blob'\n }\n if (typeof bytes === 'string') return `Invalid content: ${bytes}`\n if (bytes.length > maxBytes) return `Invalid content: the file is larger than ${maxBytes} bytes`\n return { kind: 'embedded', name, ...(mimeType ? { mimeType } : {}), bytes }\n }\n if (item.type === 'resource_link') {\n if (typeof item.uri !== 'string' || !URI_LINE.test(item.uri)) {\n return 'Invalid content: a resource_link needs a URI'\n }\n const fromUri = appFileNameOf(item.uri)\n const name =\n fromUri !== 'download' || typeof item.name !== 'string' ? fromUri : appFileNameOf(item.name)\n const mimeType = appMimeTypeOf(item.mimeType)\n const refused = appDownloadRefusal(name, mimeType)\n if (refused) return `Policy violation: ${refused}`\n return { kind: 'link', uri: item.uri, name, ...(mimeType ? { mimeType } : {}) }\n }\n return 'Invalid content: a resource or a resource_link'\n}\n\n/** A file ready to be put to the user: its name, type, bytes, and where the bytes came from. */\nexport interface AppReadyDownload {\n name: string\n mimeType?: string\n bytes: Uint8Array\n source: 'embedded' | 'link'\n}\n\n/** How a linked file is read: `resources/read` on the app's OWN server (the connection's). */\nexport type AppResourceReader = (\n server: string,\n uri: string,\n options: { signal?: AbortSignal; maxBytes: number },\n) => Promise<{ mimeType?: string; bytes: Uint8Array }>\n\n/**\n * The bytes of a checked file: an embedded one as it came; a linked one read from `server` -\n * the app's own - through `read` (never a fetch of its URI), at most `maxBytes`, and the type the\n * SERVER gives it judged again (an app cannot pass a page off as a text file through a link).\n * Throws an `McpAppRpcError` for the app: no reader, a failed read, a refused type, too large.\n */\nexport const resolveAppDownload = async (\n file: AppDownload,\n server: string,\n read: AppResourceReader | undefined,\n signal?: AbortSignal,\n maxBytes: number = MCP_APP_MAX_DOWNLOAD_BYTES,\n): Promise<AppReadyDownload> => {\n if (file.kind === 'embedded') {\n return {\n name: file.name,\n ...(file.mimeType ? { mimeType: file.mimeType } : {}),\n bytes: file.bytes,\n source: 'embedded',\n }\n }\n if (!read) throw new McpAppRpcError(MCP_APP_REFUSED, 'This host cannot read a linked file')\n let got: { mimeType?: string; bytes: Uint8Array }\n try {\n got = await read(server, file.uri, { ...(signal ? { signal } : {}), maxBytes })\n } catch (err) {\n const why = err instanceof Error ? err.message : String(err)\n throw new McpAppRpcError(MCP_APP_REFUSED, `Invalid content: ${why.slice(0, 200)}`)\n }\n if (!(got?.bytes instanceof Uint8Array)) {\n throw new McpAppRpcError(MCP_APP_REFUSED, 'Invalid content: no bytes')\n }\n if (got.bytes.length > maxBytes) {\n throw new McpAppRpcError(INVALID_PARAMS, `Invalid content: larger than ${maxBytes} bytes`)\n }\n const mimeType = appMimeTypeOf(got.mimeType) ?? file.mimeType\n const refused = appDownloadRefusal(file.name, mimeType)\n if (refused) throw new McpAppRpcError(INVALID_PARAMS, `Policy violation: ${refused}`)\n return { name: file.name, ...(mimeType ? { mimeType } : {}), bytes: got.bytes, source: 'link' }\n}\n\n/**\n * The error an app is told when the agent did not answer its sampling request: the core's\n * `AppSamplingError` carries its JSON-RPC code (`-1`: the user said no, `-32602`: not a request\n * this host takes, `-32000`: too many); anything else is a refusal.\n */\nexport const appSamplingErrorOf = (err: unknown): McpAppRpcError => {\n if (err instanceof McpAppRpcError) return err\n const rpc = (err as { rpcCode?: unknown } | null)?.rpcCode\n const message = (err instanceof Error ? err.message : String(err)).slice(0, 300)\n return err instanceof Error && err.name === 'AppSamplingError' && typeof rpc === 'number'\n ? new McpAppRpcError(rpc, message)\n : new McpAppRpcError(MCP_APP_REFUSED, message)\n}\n\n/** What `saveAppFile` uses of the page (passed in: this module touches no DOM by itself). */\nexport interface AppFileSaverEnv {\n document: { createElement: (tag: 'a') => HTMLAnchorElement; body: { append: (n: Node) => void } }\n URL: { createObjectURL: (blob: Blob) => string; revokeObjectURL: (url: string) => void }\n setTimeout: (fn: () => void, ms: number) => unknown\n}\n\n/**\n * Save a checked file the user agreed to: a `Blob` of type `application/octet-stream` (the\n * browser never renders or sniffs it as a page), a `blob:` URL of THIS page, an `<a download>`\n * made here and clicked once. No navigation, no `data:` or `javascript:` URL, nothing of the app\n * in the page; the URL is revoked a minute later.\n */\nexport const saveAppFile = (\n file: { name: string; bytes: Uint8Array },\n env: AppFileSaverEnv,\n): void => {\n const blob = new Blob([file.bytes as BlobPart], { type: 'application/octet-stream' })\n const url = env.URL.createObjectURL(blob)\n const a = env.document.createElement('a')\n a.href = url\n a.download = appFileNameOf(file.name)\n a.rel = 'noopener'\n a.style.display = 'none'\n env.document.body.append(a)\n a.click()\n a.remove()\n env.setTimeout(() => env.URL.revokeObjectURL(url), 60_000)\n}\n\n// ── An app on an origin of its own: the sandbox proxy (opt-in) ──────────────────────────────\n//\n// The specification's web-host model: the app is not framed by a `srcdoc` of ours but by a page\n// the host serves on ANOTHER origin (`./mcp-app-sandbox`), so the app gets that origin - storage,\n// cookies, a real `Origin` on its requests - and never the page's. From the page down:\n//\n// your page ── <iframe sandbox=\"allow-scripts allow-same-origin\" srcdoc=SHELL> (your origin)\n// SHELL: no script (`script-src 'none'`); `frame-src` = the proxy's exact URL\n// └─ <iframe sandbox=\"allow-scripts allow-same-origin\" src=PROXY> (the sandbox origin)\n// PROXY: the app's policy as a header; relays messages\n// └─ the app, written into a frame of the proxy (the sandbox origin)\n//\n// The app is same-origin with the proxy and can reach into it - make it navigate, run code in it.\n// So the guards are what the app cannot reach: the frames' sandbox flags (drawn on YOUR side,\n// cross-origin to the app), the shell's `frame-src`, which pins the proxy's frame to its one URL\n// (any other navigation of it is refused, so nothing leaves for an origin the app did not\n// declare), the policy in that URL's PATH (which the pin covers; a query would not be), and the\n// page's checks below: messages only from the proxy's window AND the sandbox origin, posted to\n// that origin only, one handshake. A second `sandbox-proxy-ready` means the proxy was loaded again\n// - by the app - and the app is stopped. Without a sandbox URL, or when its page does not answer,\n// the app runs in the opaque frame above: the stricter of the two.\n\n/** `<AgentChat appSandbox>` / `useMcpAppHost({ sandbox })`. */\nexport interface McpAppSandboxOptions {\n /**\n * The sandbox page's base URL on another origin you serve (`mcpAppSandboxResponse` of the\n * `./mcp-app-sandbox` entry), e.g. `https://apps.example.com/sandbox/v1`; an app's frame loads\n * `<url>/<policy>`. `{server}` in the host name gives each server an origin of its own\n * (`https://{server}.apps.example.com/sandbox/v1`; the server's name must be a DNS label - it\n * needs a wildcard certificate). `https://` only; `http://` on `localhost` / `127.0.0.1`.\n */\n url: string\n /** How long a frame waits for the page's handshake before it falls back (default 5000 ms). */\n timeoutMs?: number\n}\n\n/** Why an app runs in the opaque frame although a sandbox URL is set. */\nexport type McpAppSandboxReason =\n | 'invalid'\n | 'insecure'\n | 'same-origin'\n | 'no-page-origin'\n | 'server-name'\n | 'too-many-origins'\n | 'no-answer'\n\nexport type McpAppSandboxTarget =\n { ok: true; origin: string; base: string } | { ok: false; reason: McpAppSandboxReason }\n\n/** The placeholder for the server's name in `McpAppSandboxOptions.url`. */\nexport const MCP_APP_SANDBOX_SERVER = '{server}'\nexport const MCP_APP_SANDBOX_TIMEOUT_MS = 5000\n/** After the shell has loaded (the proxy loaded or failed), the handshake gets this much longer. */\nexport const MCP_APP_SANDBOX_GRACE_MS = 1000\n/**\n * The sandbox flags of the shell's frame and of the proxy's: scripts and an origin - the shell\n * must keep YOUR origin (else the proxy below it would get an opaque one) and runs no script; the\n * proxy is on the sandbox origin. Nothing else: no navigation, popup, form, modal, download.\n */\nexport const MCP_APP_SANDBOX_FRAME_TOKENS = 'allow-scripts allow-same-origin'\n\nconst DNS_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/\n// CSP cannot name an IPv6 literal (`[::1]`): the proxy's frame could not be pinned.\nconst LOOPBACK_HOSTS = ['localhost', '127.0.0.1']\n// What a `frame-src` source expression's path may hold, and a URL keeps as it is.\nconst SAFE_PATH = /^\\/[A-Za-z0-9\\-._~/%]*$/\n\nconst no = (reason: McpAppSandboxReason): McpAppSandboxTarget => ({ ok: false, reason })\n\n/**\n * Where an app of `server` runs, for a page on `pageOrigin`: the sandbox's origin and base URL,\n * or why not. Refused: not a URL; credentials, a query or a fragment; not `https://` (`http://`\n * only on `localhost` / `127.0.0.1`); a path a policy cannot name; `{server}` anywhere but the\n * host name, more than once, or a server name that is not a lowercase DNS label; a page without\n * an origin; and the sandbox on the PAGE'S OWN origin - `allow-same-origin` there would hand the\n * app your storage and the key vault.\n */\nexport const mcpAppSandboxTarget = (\n options: McpAppSandboxOptions | undefined,\n server: string,\n pageOrigin: string | undefined,\n): McpAppSandboxTarget => {\n const template = options?.url\n if (typeof template !== 'string' || template.length === 0 || template.length > 2048) {\n return no('invalid')\n }\n const parts = template.split(MCP_APP_SANDBOX_SERVER)\n if (parts.length > 2) return no('invalid')\n let raw = template\n if (parts.length === 2) {\n const authority = /^[a-z][a-z0-9+.-]*:\\/\\/([^/?#]*)/i.exec(template)?.[1] ?? ''\n if (!authority.replace(/:\\d*$/, '').includes(MCP_APP_SANDBOX_SERVER)) return no('invalid')\n if (typeof server !== 'string' || !DNS_LABEL.test(server)) return no('server-name')\n raw = template.replace(MCP_APP_SANDBOX_SERVER, server)\n }\n if (/[?#\\s]/.test(raw)) return no('invalid')\n let url: URL\n try {\n url = new URL(raw)\n } catch {\n return no('invalid')\n }\n const loopback = LOOPBACK_HOSTS.includes(url.hostname)\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) return no('insecure')\n if (url.username || url.password || !url.hostname) return no('invalid')\n if (!url.hostname.split('.').every((label) => DNS_LABEL.test(label))) {\n return no(parts.length === 2 ? 'server-name' : 'invalid')\n }\n if (!SAFE_PATH.test(url.pathname)) return no('invalid')\n if (!pageOrigin || pageOrigin === 'null') return no('no-page-origin')\n if (url.origin === pageOrigin) return no('same-origin')\n return { ok: true, origin: url.origin, base: `${url.origin}${url.pathname.replace(/\\/+$/, '')}` }\n}\n\n/** The proxy page's URL for an app's declared origins (`<base>/<policy>`), or none if too long. */\nexport const mcpAppSandboxProxyUrl = (\n base: string,\n csp?: Partial<McpAppCsp>,\n): string | undefined => {\n const granted = grantedAppCsp(csp)\n const token = mcpAppPolicyToken({\n connect: granted.connectDomains,\n resources: granted.resourceDomains,\n })\n return token ? `${base}/${token}` : undefined\n}\n\nconst PROXY_URL = /^https?:\\/\\/[A-Za-z0-9.-]+(?::\\d{1,5})?\\/[A-Za-z0-9\\-._~/%]*$/\n\n/**\n * The policy of the shell: no script at all, and frames from the proxy's exact URL only - a\n * `frame-src` with a path matches that path and nothing else (the query is not part of the\n * match), so the proxy's frame can never be navigated anywhere else.\n */\nexport const mcpAppSandboxShellCsp = (proxyUrl: string): string =>\n [\n \"default-src 'none'\",\n \"script-src 'none'\",\n \"style-src 'unsafe-inline'\",\n `frame-src ${proxyUrl}`,\n \"child-src 'none'\",\n \"worker-src 'none'\",\n \"object-src 'none'\",\n \"form-action 'none'\",\n \"base-uri 'none'\",\n ].join('; ')\n\n/**\n * What goes into the OUTER frame's `srcdoc` in sandbox mode: the shell - its policy first, one\n * frame of the proxy page, no script, nothing of the app. Give the outer `<iframe>`\n * `sandbox={MCP_APP_SANDBOX_FRAME_TOKENS}` and nothing else. Throws on a URL that is not a proxy\n * URL this package builds (`mcpAppSandboxProxyUrl`). `scheme` is declared by the shell and its\n * frame, and handed to the proxy page as `?scheme=` on its frame's `src` ONLY: the shell's\n * `frame-src` stays the path (a source expression carries no query, and a path source ignores\n * one), so the pin is the same with or without it.\n */\nexport const buildMcpAppSandboxShell = (proxyUrl: string, scheme?: McpAppColorScheme): string => {\n if (!PROXY_URL.test(proxyUrl)) throw new Error('not a sandbox proxy URL')\n const s = mcpAppColorScheme(scheme)\n const src = s ? `${proxyUrl}?${MCP_APP_SCHEME_PARAM}=${s}` : proxyUrl\n return (\n '<!doctype html><html><head>' +\n cspMetaTag(mcpAppSandboxShellCsp(proxyUrl)) +\n schemeMeta(s) +\n `<style>${schemeCss(s)}html,body{margin:0;height:100%;overflow:hidden;background:transparent}` +\n `iframe{display:block;border:0;width:100%;height:100%${schemeOfFrame(s)}}</style></head><body>` +\n `<iframe id=\"proxy\" sandbox=\"${MCP_APP_SANDBOX_FRAME_TOKENS}\" referrerpolicy=\"no-referrer\" ` +\n `src=\"${escapeAttribute(src)}\"></iframe></body></html>`\n )\n}\n\n/** What one message from the proxy's frame is, for the page (`McpAppSandboxLink.receive`). */\nexport type McpAppSandboxInput = 'drop' | 'ready' | 'broken' | 'app'\n\nexport interface McpAppSandboxLinkOptions {\n /** The sandbox origin (`mcpAppSandboxTarget(…).origin`). */\n origin: string\n /** The app, as read from its server: sent once, on the proxy's first ready. */\n html: string\n csp?: Partial<McpAppCsp>\n /** Post to the proxy's window. Always called with the sandbox origin as the target - never `*`. */\n post: (message: unknown, targetOrigin: string) => void\n}\n\n/**\n * The page's side of the sandbox proxy, without the DOM: which messages are the proxy's, the\n * handshake, and every post to the sandbox origin. A message is the proxy's only when it comes\n * from the proxy's window (`event.source`) AND from the sandbox origin (`event.origin`). The\n * first `sandbox-proxy-ready` is answered with the app (`sandbox-resource-ready`); another one\n * means the proxy page was loaded again - by the app - and the link breaks (`'broken'`: stop the\n * app). Every other `ui/notifications/sandbox-*` message is dropped; nothing reaches the bridge\n * (`'app'`) before the app was handed over.\n */\nexport class McpAppSandboxLink {\n private readonly o: McpAppSandboxLinkOptions\n private state: 'waiting' | 'loaded' | 'broken' | 'closed' = 'waiting'\n\n constructor(options: McpAppSandboxLinkOptions) {\n this.o = options\n }\n\n /** The proxy answered and was given the app. */\n get ready(): boolean {\n return this.state === 'loaded'\n }\n\n /** The proxy page was loaded a second time: the app must be stopped. */\n get broken(): boolean {\n return this.state === 'broken'\n }\n\n /** Whether a message event is the proxy's: its window, and the sandbox origin. */\n accepts(event: { source: unknown; origin: string }, proxy: unknown): boolean {\n return (\n proxy !== null &&\n proxy !== undefined &&\n event.source === proxy &&\n event.origin === this.o.origin\n )\n }\n\n receive(\n event: { source: unknown; origin: string; data: unknown },\n proxy: unknown,\n ): McpAppSandboxInput {\n if (this.state === 'broken' || this.state === 'closed' || !this.accepts(event, proxy)) {\n return 'drop'\n }\n const data = event.data\n if (isMcpAppSandboxMessage(data)) {\n const d = data as { jsonrpc?: unknown; method: string }\n if (d.jsonrpc !== '2.0' || d.method !== MCP_APP_SANDBOX_PROXY_READY) return 'drop'\n if (this.state === 'loaded') {\n this.state = 'broken'\n return 'broken'\n }\n this.state = 'loaded'\n const granted = grantedAppCsp(this.o.csp)\n this.o.post(\n {\n jsonrpc: '2.0',\n method: MCP_APP_SANDBOX_RESOURCE_READY,\n params: { html: this.o.html, csp: granted },\n },\n this.o.origin,\n )\n return 'ready'\n }\n return this.state === 'loaded' ? 'app' : 'drop'\n }\n\n /** Send a message to the app, through the proxy, to the sandbox origin. Nothing once broken. */\n post(message: unknown): void {\n if (this.state === 'loaded') this.o.post(message, this.o.origin)\n }\n\n close(): void {\n if (this.state !== 'broken') this.state = 'closed'\n }\n}\n\n/**\n * A pending consent request of THIS frame (`ApprovalView.app.frame`, set by `useAgent`); for a\n * request that names no frame (a host's own gate), one of this app's server and resource.\n */\nexport const isApprovalOfApp = (approval: ApprovalView, app: AppView): boolean =>\n approval.status === 'pending' &&\n approval.app !== undefined &&\n (approval.app.frame !== undefined\n ? approval.app.frame === app.id\n : approval.app.server === app.server && approval.app.resourceUri === app.resourceUri)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,oBAAoC;AA8CtC,IAAM,2BAA2B;AAGjC,IAAM,qBAAqB;AAO3B,IAAM,iBAAiB;AAEvB,IAAM,iBAAiB;AAEvB,IAAM,qBAAqB;AAE3B,IAAM,qBAAqB;AAQ3B,IAAM,eAAe,CAAC,eAA2C;AACtE,MAAI,OAAO,eAAe,YAAY,CAAC,OAAO,SAAS,UAAU,KAAK,cAAc,GAAG;AACrF,WAAO;AAAA,EACT;AACA,QAAM,UAAU,KAAK,MAAO,aAAa,qBAAsB,GAAG,IAAI;AACtE,SAAO,KAAK,IAAI,oBAAoB,KAAK,IAAI,gBAAgB,OAAO,CAAC;AACvE;AASO,IAAM,mBAA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