skybridge 1.1.2 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/dist/commands/dev.js +1 -3
  2. package/dist/commands/dev.js.map +1 -1
  3. package/dist/server/auth/discovery.d.ts +32 -0
  4. package/dist/server/auth/discovery.js +56 -0
  5. package/dist/server/auth/discovery.js.map +1 -0
  6. package/dist/server/auth/discovery.test.d.ts +1 -0
  7. package/dist/server/auth/discovery.test.js +93 -0
  8. package/dist/server/auth/discovery.test.js.map +1 -0
  9. package/dist/server/auth/index.d.ts +18 -0
  10. package/dist/server/auth/index.js +2 -0
  11. package/dist/server/auth/index.js.map +1 -0
  12. package/dist/server/auth/providers/auth0.d.ts +18 -0
  13. package/dist/server/auth/providers/auth0.js +31 -0
  14. package/dist/server/auth/providers/auth0.js.map +1 -0
  15. package/dist/server/auth/providers/auth0.test.d.ts +1 -0
  16. package/dist/server/auth/providers/auth0.test.js +48 -0
  17. package/dist/server/auth/providers/auth0.test.js.map +1 -0
  18. package/dist/server/auth/providers/clerk.d.ts +14 -0
  19. package/dist/server/auth/providers/clerk.js +16 -0
  20. package/dist/server/auth/providers/clerk.js.map +1 -0
  21. package/dist/server/auth/providers/clerk.test.d.ts +1 -0
  22. package/dist/server/auth/providers/clerk.test.js +28 -0
  23. package/dist/server/auth/providers/clerk.test.js.map +1 -0
  24. package/dist/server/auth/providers/custom.d.ts +24 -0
  25. package/dist/server/auth/providers/custom.js +37 -0
  26. package/dist/server/auth/providers/custom.js.map +1 -0
  27. package/dist/server/auth/providers/custom.test.d.ts +1 -0
  28. package/dist/server/auth/providers/custom.test.js +107 -0
  29. package/dist/server/auth/providers/custom.test.js.map +1 -0
  30. package/dist/server/auth/providers/descope.d.ts +15 -0
  31. package/dist/server/auth/providers/descope.js +33 -0
  32. package/dist/server/auth/providers/descope.js.map +1 -0
  33. package/dist/server/auth/providers/descope.test.d.ts +1 -0
  34. package/dist/server/auth/providers/descope.test.js +37 -0
  35. package/dist/server/auth/providers/descope.test.js.map +1 -0
  36. package/dist/server/auth/providers/shared.d.ts +2 -0
  37. package/dist/server/auth/providers/shared.js +6 -0
  38. package/dist/server/auth/providers/shared.js.map +1 -0
  39. package/dist/server/auth/providers/shared.test.d.ts +1 -0
  40. package/dist/server/auth/providers/shared.test.js +10 -0
  41. package/dist/server/auth/providers/shared.test.js.map +1 -0
  42. package/dist/server/auth/providers/stytch.d.ts +12 -0
  43. package/dist/server/auth/providers/stytch.js +13 -0
  44. package/dist/server/auth/providers/stytch.js.map +1 -0
  45. package/dist/server/auth/providers/workos.d.ts +11 -0
  46. package/dist/server/auth/providers/workos.js +12 -0
  47. package/dist/server/auth/providers/workos.js.map +1 -0
  48. package/dist/server/auth/setup.d.ts +4 -0
  49. package/dist/server/auth/setup.js +51 -0
  50. package/dist/server/auth/setup.js.map +1 -0
  51. package/dist/server/auth/setup.test.d.ts +1 -0
  52. package/dist/server/auth/setup.test.js +185 -0
  53. package/dist/server/auth/setup.test.js.map +1 -0
  54. package/dist/server/auth/verify.d.ts +12 -0
  55. package/dist/server/auth/verify.js +38 -0
  56. package/dist/server/auth/verify.js.map +1 -0
  57. package/dist/server/auth/verify.test.d.ts +1 -0
  58. package/dist/server/auth/verify.test.js +100 -0
  59. package/dist/server/auth/verify.test.js.map +1 -0
  60. package/dist/server/express.test.js +31 -0
  61. package/dist/server/express.test.js.map +1 -1
  62. package/dist/server/index.d.ts +8 -1
  63. package/dist/server/index.js +6 -0
  64. package/dist/server/index.js.map +1 -1
  65. package/dist/server/requestOrigin.d.ts +7 -0
  66. package/dist/server/requestOrigin.js +25 -0
  67. package/dist/server/requestOrigin.js.map +1 -0
  68. package/dist/server/server.d.ts +30 -7
  69. package/dist/server/server.js +79 -123
  70. package/dist/server/server.js.map +1 -1
  71. package/dist/server/view-resource-resolution.test.js +24 -9
  72. package/dist/server/view-resource-resolution.test.js.map +1 -1
  73. package/dist/test/view.test.js +69 -101
  74. package/dist/test/view.test.js.map +1 -1
  75. package/dist/web/bridges/adaptor.d.ts +51 -0
  76. package/dist/web/bridges/adaptor.js +310 -0
  77. package/dist/web/bridges/adaptor.js.map +1 -0
  78. package/dist/web/bridges/adaptor.test.d.ts +1 -0
  79. package/dist/web/bridges/adaptor.test.js +197 -0
  80. package/dist/web/bridges/adaptor.test.js.map +1 -0
  81. package/dist/web/bridges/apps-sdk/bridge.d.ts +6 -2
  82. package/dist/web/bridges/apps-sdk/bridge.js +15 -4
  83. package/dist/web/bridges/apps-sdk/bridge.js.map +1 -1
  84. package/dist/web/bridges/apps-sdk/index.d.ts +0 -1
  85. package/dist/web/bridges/apps-sdk/index.js +0 -1
  86. package/dist/web/bridges/apps-sdk/index.js.map +1 -1
  87. package/dist/web/bridges/get-adaptor.d.ts +4 -4
  88. package/dist/web/bridges/get-adaptor.js +6 -11
  89. package/dist/web/bridges/get-adaptor.js.map +1 -1
  90. package/dist/web/bridges/get-adaptor.test.d.ts +1 -0
  91. package/dist/web/bridges/get-adaptor.test.js +32 -0
  92. package/dist/web/bridges/get-adaptor.test.js.map +1 -0
  93. package/dist/web/bridges/mcp-app/bridge.d.ts +13 -2
  94. package/dist/web/bridges/mcp-app/bridge.js +46 -4
  95. package/dist/web/bridges/mcp-app/bridge.js.map +1 -1
  96. package/dist/web/bridges/mcp-app/bridge.test.d.ts +1 -0
  97. package/dist/web/bridges/mcp-app/bridge.test.js +17 -0
  98. package/dist/web/bridges/mcp-app/bridge.test.js.map +1 -0
  99. package/dist/web/bridges/mcp-app/index.d.ts +0 -1
  100. package/dist/web/bridges/mcp-app/index.js +0 -1
  101. package/dist/web/bridges/mcp-app/index.js.map +1 -1
  102. package/dist/web/bridges/mcp-app/view-tools.test.js +5 -6
  103. package/dist/web/bridges/mcp-app/view-tools.test.js.map +1 -1
  104. package/dist/web/bridges/types.d.ts +10 -0
  105. package/dist/web/bridges/types.js +14 -1
  106. package/dist/web/bridges/types.js.map +1 -1
  107. package/dist/web/bridges/types.test.d.ts +1 -0
  108. package/dist/web/bridges/types.test.js +19 -0
  109. package/dist/web/bridges/types.test.js.map +1 -0
  110. package/dist/web/components/modal-provider.js +4 -3
  111. package/dist/web/components/modal-provider.js.map +1 -1
  112. package/dist/web/create-store.test.js +8 -5
  113. package/dist/web/create-store.test.js.map +1 -1
  114. package/dist/web/data-llm.test.js +9 -5
  115. package/dist/web/data-llm.test.js.map +1 -1
  116. package/dist/web/hooks/use-call-tool.test.js +37 -23
  117. package/dist/web/hooks/use-call-tool.test.js.map +1 -1
  118. package/dist/web/hooks/use-display-mode.test.js +56 -20
  119. package/dist/web/hooks/use-display-mode.test.js.map +1 -1
  120. package/dist/web/hooks/use-download.test.js +11 -3
  121. package/dist/web/hooks/use-download.test.js.map +1 -1
  122. package/dist/web/hooks/use-files.test.js +10 -2
  123. package/dist/web/hooks/use-files.test.js.map +1 -1
  124. package/dist/web/hooks/use-layout.test.js +59 -26
  125. package/dist/web/hooks/use-layout.test.js.map +1 -1
  126. package/dist/web/hooks/use-open-external.test.js +13 -3
  127. package/dist/web/hooks/use-open-external.test.js.map +1 -1
  128. package/dist/web/hooks/use-request-close.test.js +35 -40
  129. package/dist/web/hooks/use-request-close.test.js.map +1 -1
  130. package/dist/web/hooks/use-request-modal.test.js +10 -0
  131. package/dist/web/hooks/use-request-modal.test.js.map +1 -1
  132. package/dist/web/hooks/use-request-size.test.js +35 -53
  133. package/dist/web/hooks/use-request-size.test.js.map +1 -1
  134. package/dist/web/hooks/use-set-open-in-app-url.test.js +28 -8
  135. package/dist/web/hooks/use-set-open-in-app-url.test.js.map +1 -1
  136. package/dist/web/hooks/use-tool-info.test.js +37 -27
  137. package/dist/web/hooks/use-tool-info.test.js.map +1 -1
  138. package/dist/web/hooks/use-user.test.js +81 -35
  139. package/dist/web/hooks/use-user.test.js.map +1 -1
  140. package/dist/web/hooks/use-view-state.test.js +6 -2
  141. package/dist/web/hooks/use-view-state.test.js.map +1 -1
  142. package/package.json +3 -2
  143. package/dist/cli/use-open-tunnel-browser.d.ts +0 -6
  144. package/dist/cli/use-open-tunnel-browser.js +0 -19
  145. package/dist/cli/use-open-tunnel-browser.js.map +0 -1
  146. package/dist/web/bridges/apps-sdk/adaptor.d.ts +0 -29
  147. package/dist/web/bridges/apps-sdk/adaptor.js +0 -117
  148. package/dist/web/bridges/apps-sdk/adaptor.js.map +0 -1
  149. package/dist/web/bridges/mcp-app/adaptor.d.ts +0 -53
  150. package/dist/web/bridges/mcp-app/adaptor.js +0 -283
  151. package/dist/web/bridges/mcp-app/adaptor.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"bridge.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/bridge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,gCAAgC,CAAC;AACrD,OAAO,EAEL,sBAAsB,GACvB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC;AASzB,6GAA6G;AAC7G,MAAM,OAAO,YAAY;IACf,MAAM,CAAC,QAAQ,GAAwB,IAAI,CAAC;IAC7C,OAAO,GAAkB;QAC9B,SAAS,EAAE,IAAI;QACf,aAAa,EAAE,IAAI;QACnB,UAAU,EAAE,IAAI;KACjB,CAAC;IACM,SAAS,GAAG,IAAI,GAAG,EAAqC,CAAC;IACzD,GAAG,CAAM;IACT,cAAc,CAAgB;IAEtC,YAAY,OAAoC;QAC9C,IAAI,CAAC,GAAG,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;QAEtE,IAAI,CAAC,GAAG,CAAC,iBAAiB,CAAC,sBAAsB,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC;YAC9D,KAAK,EAAE,EAAE;SACV,CAAC,CAAC,CAAC;QAEJ,IAAI,CAAC,GAAG,CAAC,WAAW,GAAG,CAAC,MAAM,EAAE,EAAE;YA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AE,CAAC;YAChC,YAAY,CAAC,QAAQ,GAAG,IAAI,CAAC;QAC/B,CAAC;IACH,CAAC;IAEO,IAAI,CAAC,GAAqB;QAChC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE;YAC5C,QAAQ,EAAE,CAAC;QACb,CAAC,CAAC,CAAC;IACL,CAAC;IAEO,aAAa,CAAC,OAA+B;QACnD,IAAI,CAAC,OAAO,GAAG,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC;QAC/C,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;YACvC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACjB,CAAC;IACH,CAAC","sourcesContent":["import { App } from \"@modelcontextprotocol/ext-apps\";\nimport {\n type Implementation,\n ListToolsRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport * as z from \"zod\";\nimport type {\n AnyViewToolHandler,\n Bridge,\n Subscribe,\n ViewToolConfig,\n} from \"../types.js\";\nimport type { McpAppContext, McpAppContextKey } from \"./types.js\";\n\n/** @internal Singleton bridge over the `ext-apps` JSON-RPC App connection. Used by {@link McpAppAdaptor}. */\nexport class McpAppBridge implements Bridge<McpAppContext> {\n private static instance: McpAppBridge | null = null;\n public context: McpAppContext = {\n toolInput: null,\n toolCancelled: null,\n toolResult: null,\n };\n private listeners = new Map<McpAppContextKey, Set<() => void>>();\n private app: App;\n private connectPromise: Promise<void>;\n\n constructor(options: { appInfo: Implementation }) {\n this.app = new App(options.appInfo, { tools: { listChanged: true } });\n\n this.app.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: [],\n }));\n\n this.app.ontoolinput = (params) => {\n this.updateContext({ toolInput: params.arguments ?? {} });\n };\n\n this.app.ontoolinputpartial = (params) => {\n this.updateContext({ toolInput: params.arguments ?? {} });\n };\n\n this.app.ontoolresult = (params) => {\n this.updateContext({ toolResult: params });\n };\n\n this.app.ontoolcancelled = (params) => {\n this.updateContext({ toolCancelled: params });\n };\n\n this.app.onhostcontextchanged = (params) => {\n this.updateContext(params);\n };\n\n this.connectPromise = this.connect();\n }\n\n private async connect() {\n try {\n await this.app.connect();\n const hostContext = this.app.getHostContext();\n if (hostContext) {\n this.updateContext(hostContext);\n }\n } catch (err) {\n console.error(err);\n }\n }\n\n public async getApp(): Promise<App> {\n await this.connectPromise;\n return this.app;\n }\n\n public registerViewTool(\n config: ViewToolConfig,\n handler: AnyViewToolHandler,\n ): () => void {\n const inputSchema = config.inputSchema\n ? z.object(config.inputSchema)\n : z.object({});\n\n const registered = this.app.registerTool(\n config.name,\n {\n ...(config.title !== undefined ? { title: config.title } : {}),\n ...(config.description !== undefined\n ? { description: config.description }\n : {}),\n inputSchema,\n ...(config.annotations ? { annotations: config.annotations } : {}),\n },\n handler,\n );\n\n return () => {\n registered.remove();\n };\n }\n\n public static getInstance(\n options?: Partial<{ appInfo: Implementation }>,\n ): McpAppBridge {\n if (window.skybridge.hostType !== \"mcp-app\") {\n throw new Error(\"MCP App Bridge can only be used in the mcp-app runtime\");\n }\n if (McpAppBridge.instance && options) {\n console.warn(\n \"McpAppBridge.getInstance: options ignored, instance already exists\",\n );\n }\n if (!McpAppBridge.instance) {\n const defaultOptions = {\n appInfo: { name: \"skybridge-app\", version: \"0.0.1\" },\n };\n McpAppBridge.instance = new McpAppBridge({\n ...defaultOptions,\n ...options,\n });\n }\n return McpAppBridge.instance;\n }\n\n public subscribe(key: McpAppContextKey): Subscribe;\n public subscribe(keys: readonly McpAppContextKey[]): Subscribe;\n public subscribe(\n keyOrKeys: McpAppContextKey | readonly McpAppContextKey[],\n ): Subscribe {\n const keys = Array.isArray(keyOrKeys) ? keyOrKeys : [keyOrKeys];\n return (onChange: () => void) => {\n for (const key of keys) {\n this.listeners.set(\n key,\n new Set([...(this.listeners.get(key) || []), onChange]),\n );\n }\n return () => {\n for (const key of keys) {\n this.listeners.get(key)?.delete(onChange);\n }\n };\n };\n }\n\n public getSnapshot<K extends keyof McpAppContext>(key: K): McpAppContext[K] {\n return this.context[key];\n }\n\n public cleanup = () => {\n this.listeners.clear();\n };\n\n public static resetInstance(): void {\n if (McpAppBridge.instance) {\n McpAppBridge.instance.cleanup();\n McpAppBridge.instance = null;\n }\n }\n\n private emit(key: McpAppContextKey) {\n this.listeners.get(key)?.forEach((listener) => {\n listener();\n });\n }\n\n private updateContext(context: Partial<McpAppContext>) {\n this.context = { ...this.context, ...context };\n for (const key of Object.keys(context)) {\n this.emit(key);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"bridge.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/bridge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,gCAAgC,CAAC;AACrD,OAAO,EAEL,sBAAsB,GACvB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC;AAczB,SAAS,cAAc,CACrB,MAAoB,EACpB,IAAU,EACV,eAAkD;IAElD,IAAI,WAA0B,CAAC;IAC/B,OAAO;QACL,SAAS,EAAE,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC;QACjC,WAAW,EAAE,GAAG,EAAE;YAChB,MAAM,OAAO,GAAG,MAAM,CAAC,WAAW,CAChC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CACvB,CAAC;YACvB,MAAM,QAAQ,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;YAC1C,IAAI,WAAW,KAAK,SAAS,IAAI,MAAM,CAAC,WAAW,EAAE,QAAQ,CAAC,EAAE,CAAC;gBAC/D,OAAO,WAAW,CAAC;YACrB,CAAC;YACD,WAAW,GAAG,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;QAChC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE;YAC5C,QAAQ,EAAE,CAAC;QACb,CAAC,CAAC,CAAC;IACL,CAAC;IAEO,aAAa,CAAC,OAA+B;QACnD,IAAI,CAAC,OAAO,GAAG,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC;QAC/C,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;YACvC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACjB,CAAC;IACH,CAAC","sourcesContent":["import { App } from \"@modelcontextprotocol/ext-apps\";\nimport {\n type Implementation,\n ListToolsRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { dequal } from \"dequal/lite\";\nimport * as z from \"zod\";\nimport type {\n AnyViewToolHandler,\n Bridge,\n HostContextStore,\n Subscribe,\n ViewToolConfig,\n} from \"../types.js\";\nimport type { McpAppContext, McpAppContextKey } from \"./types.js\";\n\ntype PickContext<K extends readonly McpAppContextKey[]> = {\n [P in K[number]]: McpAppContext[P];\n};\n\nfunction createMcpStore<const Keys extends readonly McpAppContextKey[], R>(\n bridge: McpAppBridge,\n keys: Keys,\n computeSnapshot: (context: PickContext<Keys>) => R,\n) {\n let cachedValue: R | undefined;\n return {\n subscribe: bridge.subscribe(keys),\n getSnapshot: () => {\n const context = Object.fromEntries(\n keys.map((k) => [k, bridge.getSnapshot(k)]),\n ) as PickContext<Keys>;\n const newValue = computeSnapshot(context);\n if (cachedValue !== undefined && dequal(cachedValue, newValue)) {\n return cachedValue;\n }\n cachedValue = newValue;\n return newValue;\n },\n };\n}\n\n/** @internal Singleton bridge over the `ext-apps` JSON-RPC App connection. Used by `HostAdaptor`. */\nexport class McpAppBridge implements Bridge<McpAppContext> {\n private static instance: McpAppBridge | null = null;\n public context: McpAppContext = {\n toolInput: null,\n toolCancelled: null,\n toolResult: null,\n };\n private listeners = new Map<McpAppContextKey, Set<() => void>>();\n private app: App;\n private connectPromise: Promise<void>;\n\n constructor(options: { appInfo: Implementation }) {\n this.app = new App(options.appInfo, { tools: { listChanged: true } });\n\n this.app.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: [],\n }));\n\n this.app.ontoolinput = (params) => {\n this.updateContext({ toolInput: params.arguments ?? {} });\n };\n\n this.app.ontoolinputpartial = (params) => {\n this.updateContext({ toolInput: params.arguments ?? {} });\n };\n\n this.app.ontoolresult = (params) => {\n this.updateContext({ toolResult: params });\n };\n\n this.app.ontoolcancelled = (params) => {\n this.updateContext({ toolCancelled: params });\n };\n\n this.app.onhostcontextchanged = (params) => {\n this.updateContext(params);\n };\n\n this.connectPromise = this.connect();\n }\n\n private async connect() {\n try {\n await this.app.connect();\n const hostContext = this.app.getHostContext();\n if (hostContext) {\n this.updateContext(hostContext);\n }\n } catch (err) {\n console.error(err);\n }\n }\n\n public async getApp(): Promise<App> {\n await this.connectPromise;\n return this.app;\n }\n\n public registerViewTool(\n config: ViewToolConfig,\n handler: AnyViewToolHandler,\n ): () => void {\n const inputSchema = config.inputSchema\n ? z.object(config.inputSchema)\n : z.object({});\n\n const registered = this.app.registerTool(\n config.name,\n {\n ...(config.title !== undefined ? { title: config.title } : {}),\n ...(config.description !== undefined\n ? { description: config.description }\n : {}),\n inputSchema,\n ...(config.annotations ? { annotations: config.annotations } : {}),\n },\n handler,\n );\n\n return () => {\n registered.remove();\n };\n }\n\n public static getInstance(\n options?: Partial<{ appInfo: Implementation }>,\n ): McpAppBridge {\n if (McpAppBridge.instance && options) {\n console.warn(\n \"McpAppBridge.getInstance: options ignored, instance already exists\",\n );\n }\n if (!McpAppBridge.instance) {\n const defaultOptions = {\n appInfo: { name: \"skybridge-app\", version: \"0.0.1\" },\n };\n McpAppBridge.instance = new McpAppBridge({\n ...defaultOptions,\n ...options,\n });\n }\n return McpAppBridge.instance;\n }\n\n public subscribe(key: McpAppContextKey): Subscribe;\n public subscribe(keys: readonly McpAppContextKey[]): Subscribe;\n public subscribe(\n keyOrKeys: McpAppContextKey | readonly McpAppContextKey[],\n ): Subscribe {\n const keys = Array.isArray(keyOrKeys) ? keyOrKeys : [keyOrKeys];\n return (onChange: () => void) => {\n for (const key of keys) {\n this.listeners.set(\n key,\n new Set([...(this.listeners.get(key) || []), onChange]),\n );\n }\n return () => {\n for (const key of keys) {\n this.listeners.get(key)?.delete(onChange);\n }\n };\n };\n }\n\n public getSnapshot<K extends keyof McpAppContext>(key: K): McpAppContext[K] {\n return this.context[key];\n }\n\n public createContextStores(): {\n theme: HostContextStore<\"theme\">;\n locale: HostContextStore<\"locale\">;\n safeArea: HostContextStore<\"safeArea\">;\n displayMode: HostContextStore<\"displayMode\">;\n maxHeight: HostContextStore<\"maxHeight\">;\n userAgent: HostContextStore<\"userAgent\">;\n toolInput: HostContextStore<\"toolInput\">;\n toolOutput: HostContextStore<\"toolOutput\">;\n toolResponseMetadata: HostContextStore<\"toolResponseMetadata\">;\n } {\n return {\n theme: createMcpStore(this, [\"theme\"], ({ theme }) => theme ?? \"light\"),\n locale: createMcpStore(\n this,\n [\"locale\"],\n ({ locale }) => locale ?? \"en-US\",\n ),\n safeArea: createMcpStore(\n this,\n [\"safeAreaInsets\"],\n ({ safeAreaInsets }) => ({\n insets: safeAreaInsets ?? { top: 0, right: 0, bottom: 0, left: 0 },\n }),\n ),\n displayMode: createMcpStore(\n this,\n [\"displayMode\"],\n ({ displayMode }) => displayMode ?? \"inline\",\n ),\n maxHeight: createMcpStore(\n this,\n [\"containerDimensions\"],\n ({ containerDimensions }) => {\n if (containerDimensions && \"maxHeight\" in containerDimensions) {\n return containerDimensions.maxHeight;\n }\n return undefined;\n },\n ),\n userAgent: createMcpStore(\n this,\n [\"platform\", \"deviceCapabilities\"],\n ({ platform, deviceCapabilities }) => ({\n device: {\n type: platform === \"web\" ? \"desktop\" : (platform ?? \"unknown\"),\n },\n capabilities: {\n hover: true,\n touch: true,\n ...deviceCapabilities,\n },\n }),\n ),\n toolInput: createMcpStore(\n this,\n [\"toolInput\"],\n ({ toolInput }) => toolInput ?? null,\n ),\n toolOutput: createMcpStore(\n this,\n [\"toolResult\"],\n ({ toolResult }) => toolResult?.structuredContent ?? null,\n ),\n toolResponseMetadata: createMcpStore(\n this,\n [\"toolResult\"],\n ({ toolResult }) => toolResult?._meta ?? null,\n ),\n };\n }\n\n public cleanup = () => {\n this.listeners.clear();\n };\n\n public static resetInstance(): void {\n if (McpAppBridge.instance) {\n McpAppBridge.instance.cleanup();\n McpAppBridge.instance = null;\n }\n }\n\n private emit(key: McpAppContextKey) {\n this.listeners.get(key)?.forEach((listener) => {\n listener();\n });\n }\n\n private updateContext(context: Partial<McpAppContext>) {\n this.context = { ...this.context, ...context };\n for (const key of Object.keys(context)) {\n this.emit(key);\n }\n }\n}\n"]}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,17 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { McpAppBridge } from "./bridge.js";
3
+ describe("McpAppBridge.getInstance", () => {
4
+ beforeEach(() => {
5
+ McpAppBridge.resetInstance();
6
+ vi.stubGlobal("parent", { postMessage: vi.fn() });
7
+ });
8
+ afterEach(() => {
9
+ vi.unstubAllGlobals();
10
+ McpAppBridge.resetInstance();
11
+ });
12
+ it("instantiates regardless of injected hostType", () => {
13
+ vi.stubGlobal("skybridge", { hostType: "apps-sdk" });
14
+ expect(() => McpAppBridge.getInstance()).not.toThrow();
15
+ });
16
+ });
17
+ //# sourceMappingURL=bridge.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bridge.test.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/bridge.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AACzE,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,QAAQ,CAAC,0BAA0B,EAAE,GAAG,EAAE;IACxC,UAAU,CAAC,GAAG,EAAE;QACd,YAAY,CAAC,aAAa,EAAE,CAAC;QAC7B,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,EAAE,WAAW,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IACpD,CAAC,CAAC,CAAC;IACH,SAAS,CAAC,GAAG,EAAE;QACb,EAAE,CAAC,gBAAgB,EAAE,CAAC;QACtB,YAAY,CAAC,aAAa,EAAE,CAAC;IAC/B,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,8CAA8C,EAAE,GAAG,EAAE;QACtD,EAAE,CAAC,UAAU,CAAC,WAAW,EAAE,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC,CAAC;QACrD,MAAM,CAAC,GAAG,EAAE,CAAC,YAAY,CAAC,WAAW,EAAE,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { afterEach, beforeEach, describe, expect, it, vi } from \"vitest\";\nimport { McpAppBridge } from \"./bridge.js\";\n\ndescribe(\"McpAppBridge.getInstance\", () => {\n beforeEach(() => {\n McpAppBridge.resetInstance();\n vi.stubGlobal(\"parent\", { postMessage: vi.fn() });\n });\n afterEach(() => {\n vi.unstubAllGlobals();\n McpAppBridge.resetInstance();\n });\n\n it(\"instantiates regardless of injected hostType\", () => {\n vi.stubGlobal(\"skybridge\", { hostType: \"apps-sdk\" });\n expect(() => McpAppBridge.getInstance()).not.toThrow();\n });\n});\n"]}
@@ -1,4 +1,3 @@
1
- export { McpAppAdaptor } from "./adaptor.js";
2
1
  export { McpAppBridge } from "./bridge.js";
3
2
  export type { McpAppContext, McpAppContextKey, McpToolState, } from "./types.js";
4
3
  export { useMcpAppContext } from "./use-mcp-app-context.js";
@@ -1,4 +1,3 @@
1
- export { McpAppAdaptor } from "./adaptor.js";
2
1
  export { McpAppBridge } from "./bridge.js";
3
2
  export { useMcpAppContext } from "./use-mcp-app-context.js";
4
3
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAM3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC","sourcesContent":["export { McpAppAdaptor } from \"./adaptor.js\";\nexport { McpAppBridge } from \"./bridge.js\";\nexport type {\n McpAppContext,\n McpAppContextKey,\n McpToolState,\n} from \"./types.js\";\nexport { useMcpAppContext } from \"./use-mcp-app-context.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAM3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC","sourcesContent":["export { McpAppBridge } from \"./bridge.js\";\nexport type {\n McpAppContext,\n McpAppContextKey,\n McpToolState,\n} from \"./types.js\";\nexport { useMcpAppContext } from \"./use-mcp-app-context.js\";\n"]}
@@ -3,7 +3,7 @@ import { act } from "react";
3
3
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
4
  import * as z from "zod";
5
5
  import { MockResizeObserver } from "../../hooks/test/utils.js";
6
- import { McpAppAdaptor } from "./adaptor.js";
6
+ import { HostAdaptor } from "../adaptor.js";
7
7
  import { McpAppBridge } from "./bridge.js";
8
8
  const outgoing = [];
9
9
  /**
@@ -54,7 +54,6 @@ describe("McpApp view tools", () => {
54
54
  vi.stubGlobal("skybridge", { hostType: "mcp-app" });
55
55
  vi.stubGlobal("ResizeObserver", MockResizeObserver);
56
56
  McpAppBridge.resetInstance();
57
- McpAppAdaptor.resetInstance();
58
57
  installHostMock();
59
58
  });
60
59
  afterEach(() => {
@@ -69,7 +68,7 @@ describe("McpApp view tools", () => {
69
68
  });
70
69
  });
71
70
  it("lists a registered view tool with its input schema", async () => {
72
- const adaptor = McpAppAdaptor.getInstance();
71
+ const adaptor = new HostAdaptor();
73
72
  await McpAppBridge.getInstance().getApp();
74
73
  adaptor.registerViewTool({
75
74
  name: "chess_make_move",
@@ -87,7 +86,7 @@ describe("McpApp view tools", () => {
87
86
  expect(tool?.annotations?.readOnlyHint).toBe(false);
88
87
  });
89
88
  it("invokes the handler with validated args and returns its result", async () => {
90
- const adaptor = McpAppAdaptor.getInstance();
89
+ const adaptor = new HostAdaptor();
91
90
  await McpAppBridge.getInstance().getApp();
92
91
  const handler = vi.fn(({ san }) => ({
93
92
  content: [{ type: "text", text: `played ${san}` }],
@@ -106,7 +105,7 @@ describe("McpApp view tools", () => {
106
105
  expect(result?.content).toEqual([{ type: "text", text: "played e4" }]);
107
106
  });
108
107
  it("rejects the call without invoking the handler when args are invalid", async () => {
109
- const adaptor = McpAppAdaptor.getInstance();
108
+ const adaptor = new HostAdaptor();
110
109
  await McpAppBridge.getInstance().getApp();
111
110
  const handler = vi.fn(() => ({ content: [] }));
112
111
  adaptor.registerViewTool({ name: "chess_make_move", inputSchema: { san: z.string() } }, handler);
@@ -128,7 +127,7 @@ describe("McpApp view tools", () => {
128
127
  expect(response?.error).toBeDefined();
129
128
  });
130
129
  it("removes the tool and notifies the host when unregistered", async () => {
131
- const adaptor = McpAppAdaptor.getInstance();
130
+ const adaptor = new HostAdaptor();
132
131
  await McpAppBridge.getInstance().getApp();
133
132
  const unregister = adaptor.registerViewTool({ name: "chess_reset" }, () => ({ content: [{ type: "text", text: "reset" }] }));
134
133
  await waitFor(() => {
@@ -1 +1 @@
1
- {"version":3,"file":"view-tools.test.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/view-tools.test.ts"],"names":[],"mappings":"AAAA,OAA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AC","sourcesContent":["import { waitFor } from \"@testing-library/react\";\nimport { act } from \"react\";\nimport { afterEach, beforeEach, describe, expect, it, vi } from \"vitest\";\nimport * as z from \"zod\";\nimport { MockResizeObserver } from \"../../hooks/test/utils.js\";\nimport { McpAppAdaptor } from \"./adaptor.js\";\nimport { McpAppBridge } from \"./bridge.js\";\n\ntype JsonRpcMessage = {\n jsonrpc: \"2.0\";\n id?: number;\n method?: string;\n params?: Record<string, unknown>;\n result?: Record<string, unknown>;\n error?: { message: string };\n};\n\nconst outgoing: JsonRpcMessage[] = [];\n\n/**\n * Stand-in MCP Apps host: replies to `ui/initialize` and records every message\n * the app posts so tests can assert on responses and notifications.\n */\nfunction installHostMock() {\n outgoing.length = 0;\n const postMessage = vi.fn((message: JsonRpcMessage) => {\n outgoing.push(message);\n if (message.method === \"ui/initialize\" && message.id !== undefined) {\n act(() => {\n window.dispatchEvent(\n new MessageEvent(\"message\", {\n source: window.parent,\n data: {\n jsonrpc: \"2.0\",\n id: message.id,\n result: {\n protocolVersion: \"2025-06-18\",\n hostInfo: { name: \"test-host\", version: \"1.0.0\" },\n hostCapabilities: {},\n hostContext: {},\n },\n },\n }),\n );\n });\n }\n });\n vi.stubGlobal(\"parent\", { postMessage });\n}\n\nlet nextId = 1000;\n\n/** Send a host → app JSON-RPC request and resolve with the full response (result or error). */\nasync function callHost(method: string, params: Record<string, unknown> = {}) {\n const id = ++nextId;\n act(() => {\n window.dispatchEvent(\n new MessageEvent(\"message\", {\n source: window.parent,\n data: { jsonrpc: \"2.0\", id, method, params },\n }),\n );\n });\n await waitFor(() => {\n expect(outgoing.some((m) => m.id === id)).toBe(true);\n });\n return outgoing.find((m) => m.id === id);\n}\n\ndescribe(\"McpApp view tools\", () => {\n beforeEach(() => {\n vi.stubGlobal(\"skybridge\", { hostType: \"mcp-app\" });\n vi.stubGlobal(\"ResizeObserver\", MockResizeObserver);\n McpAppBridge.resetInstance();\n McpAppAdaptor.resetInstance();\n installHostMock();\n });\n\n afterEach(() => {\n vi.unstubAllGlobals();\n vi.clearAllMocks();\n });\n\n it(\"advertises the tools capability during ui/initialize\", async () => {\n await McpAppBridge.getInstance().getApp();\n const init = outgoing.find((m) => m.method === \"ui/initialize\");\n expect(init?.params?.appCapabilities).toMatchObject({\n tools: { listChanged: true },\n });\n });\n\n it(\"lists a registered view tool with its input schema\", async () => {\n const adaptor = McpAppAdaptor.getInstance();\n await McpAppBridge.getInstance().getApp();\n\n adaptor.registerViewTool(\n {\n name: \"chess_make_move\",\n description: \"Play a move\",\n inputSchema: { san: z.string() },\n annotations: { readOnlyHint: false },\n },\n () => ({ content: [{ type: \"text\", text: \"ok\" }] }),\n );\n\n const response = await callHost(\"tools/list\");\n const tools = response?.result?.tools as Array<{\n name: string;\n description?: string;\n inputSchema: { properties?: Record<string, unknown> };\n annotations?: { readOnlyHint?: boolean };\n }>;\n expect(tools).toHaveLength(1);\n const [tool] = tools;\n expect(tool?.name).toBe(\"chess_make_move\");\n expect(tool?.description).toBe(\"Play a move\");\n expect(tool?.inputSchema.properties).toHaveProperty(\"san\");\n expect(tool?.annotations?.readOnlyHint).toBe(false);\n });\n\n it(\"invokes the handler with validated args and returns its result\", async () => {\n const adaptor = McpAppAdaptor.getInstance();\n await McpAppBridge.getInstance().getApp();\n\n const handler = vi.fn(({ san }: { san: string }) => ({\n content: [{ type: \"text\" as const, text: `played ${san}` }],\n structuredContent: { lastMove: san },\n }));\n\n adaptor.registerViewTool(\n { name: \"chess_make_move\", inputSchema: { san: z.string() } },\n handler as never,\n );\n\n const response = await callHost(\"tools/call\", {\n name: \"chess_make_move\",\n arguments: { san: \"e4\" },\n });\n const result = response?.result;\n\n // ext-apps invokes the callback as `(args, extra)`; assert on the args only.\n expect(handler.mock.calls[0]?.[0]).toEqual({ san: \"e4\" });\n expect(result?.structuredContent).toEqual({ lastMove: \"e4\" });\n expect(result?.isError).toBeFalsy();\n expect(result?.content).toEqual([{ type: \"text\", text: \"played e4\" }]);\n });\n\n it(\"rejects the call without invoking the handler when args are invalid\", async () => {\n const adaptor = McpAppAdaptor.getInstance();\n await McpAppBridge.getInstance().getApp();\n\n const handler = vi.fn(() => ({ content: [] }));\n adaptor.registerViewTool(\n { name: \"chess_make_move\", inputSchema: { san: z.string() } },\n handler as never,\n );\n\n // ext-apps validates input against the schema and rejects with a JSON-RPC\n // error before the handler runs.\n const response = await callHost(\"tools/call\", {\n name: \"chess_make_move\",\n arguments: { san: 42 },\n });\n\n expect(handler).not.toHaveBeenCalled();\n expect(response?.error).toBeDefined();\n });\n\n it(\"rejects a call to an unknown tool\", async () => {\n await McpAppBridge.getInstance().getApp();\n const response = await callHost(\"tools/call\", {\n name: \"nope\",\n arguments: {},\n });\n expect(response?.error).toBeDefined();\n });\n\n it(\"removes the tool and notifies the host when unregistered\", async () => {\n const adaptor = McpAppAdaptor.getInstance();\n await McpAppBridge.getInstance().getApp();\n\n const unregister = adaptor.registerViewTool(\n { name: \"chess_reset\" },\n () => ({ content: [{ type: \"text\", text: \"reset\" }] }),\n );\n\n await waitFor(() => {\n expect(\n outgoing.some((m) => m.method === \"notifications/tools/list_changed\"),\n ).toBe(true);\n });\n\n let listed = await callHost(\"tools/list\");\n expect(listed?.result?.tools).toHaveLength(1);\n\n unregister();\n listed = await callHost(\"tools/list\");\n expect(listed?.result?.tools).toHaveLength(0);\n });\n});\n"]}
1
+ {"version":3,"file":"view-tools.test.js","sourceRoot":"","sources":["../../../../src/web/bridges/mcp-app/view-tools.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAC5B,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AACzE,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC;AACzB,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC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,CAAC;QAClC,MAAM,YAAY,CAAC,WAAW,EAAE,CAAC,MAAM,EAAE,CAAC;QAE1C,MAAM,UAAU,GAAG,OAAO,CAAC,gBAAgB,CACzC,EAAE,IAAI,EAAE,aAAa,EAAE,EACvB,GAAG,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC,CACvD,CAAC;QAEF,MAAM,OAAO,CAAC,GAAG,EAAE;YACjB,MAAM,CACJ,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,kCAAkC,CAAC,CACtE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACf,CAAC,CAAC,CAAC;QAEH,IAAI,MAAM,GAAG,MAAM,QAAQ,CAAC,YAAY,CAAC,CAAC;QAC1C,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;QAE9C,UAAU,EAAE,CAAC;QACb,MAAM,GAAG,MAAM,QAAQ,CAAC,YAAY,CAAC,CAAC;QACtC,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;IAChD,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { waitFor } from \"@testing-library/react\";\nimport { act } from \"react\";\nimport { afterEach, beforeEach, describe, expect, it, vi } from \"vitest\";\nimport * as z from \"zod\";\nimport { MockResizeObserver } from \"../../hooks/test/utils.js\";\nimport { HostAdaptor } from \"../adaptor.js\";\nimport { McpAppBridge } from \"./bridge.js\";\n\ntype JsonRpcMessage = {\n jsonrpc: \"2.0\";\n id?: number;\n method?: string;\n params?: Record<string, unknown>;\n result?: Record<string, unknown>;\n error?: { message: string };\n};\n\nconst outgoing: JsonRpcMessage[] = [];\n\n/**\n * Stand-in MCP Apps host: replies to `ui/initialize` and records every message\n * the app posts so tests can assert on responses and notifications.\n */\nfunction installHostMock() {\n outgoing.length = 0;\n const postMessage = vi.fn((message: JsonRpcMessage) => {\n outgoing.push(message);\n if (message.method === \"ui/initialize\" && message.id !== undefined) {\n act(() => {\n window.dispatchEvent(\n new MessageEvent(\"message\", {\n source: window.parent,\n data: {\n jsonrpc: \"2.0\",\n id: message.id,\n result: {\n protocolVersion: \"2025-06-18\",\n hostInfo: { name: \"test-host\", version: \"1.0.0\" },\n hostCapabilities: {},\n hostContext: {},\n },\n },\n }),\n );\n });\n }\n });\n vi.stubGlobal(\"parent\", { postMessage });\n}\n\nlet nextId = 1000;\n\n/** Send a host → app JSON-RPC request and resolve with the full response (result or error). */\nasync function callHost(method: string, params: Record<string, unknown> = {}) {\n const id = ++nextId;\n act(() => {\n window.dispatchEvent(\n new MessageEvent(\"message\", {\n source: window.parent,\n data: { jsonrpc: \"2.0\", id, method, params },\n }),\n );\n });\n await waitFor(() => {\n expect(outgoing.some((m) => m.id === id)).toBe(true);\n });\n return outgoing.find((m) => m.id === id);\n}\n\ndescribe(\"McpApp view tools\", () => {\n beforeEach(() => {\n vi.stubGlobal(\"skybridge\", { hostType: \"mcp-app\" });\n vi.stubGlobal(\"ResizeObserver\", MockResizeObserver);\n McpAppBridge.resetInstance();\n installHostMock();\n });\n\n afterEach(() => {\n vi.unstubAllGlobals();\n vi.clearAllMocks();\n });\n\n it(\"advertises the tools capability during ui/initialize\", async () => {\n await McpAppBridge.getInstance().getApp();\n const init = outgoing.find((m) => m.method === \"ui/initialize\");\n expect(init?.params?.appCapabilities).toMatchObject({\n tools: { listChanged: true },\n });\n });\n\n it(\"lists a registered view tool with its input schema\", async () => {\n const adaptor = new HostAdaptor();\n await McpAppBridge.getInstance().getApp();\n\n adaptor.registerViewTool(\n {\n name: \"chess_make_move\",\n description: \"Play a move\",\n inputSchema: { san: z.string() },\n annotations: { readOnlyHint: false },\n },\n () => ({ content: [{ type: \"text\", text: \"ok\" }] }),\n );\n\n const response = await callHost(\"tools/list\");\n const tools = response?.result?.tools as Array<{\n name: string;\n description?: string;\n inputSchema: { properties?: Record<string, unknown> };\n annotations?: { readOnlyHint?: boolean };\n }>;\n expect(tools).toHaveLength(1);\n const [tool] = tools;\n expect(tool?.name).toBe(\"chess_make_move\");\n expect(tool?.description).toBe(\"Play a move\");\n expect(tool?.inputSchema.properties).toHaveProperty(\"san\");\n expect(tool?.annotations?.readOnlyHint).toBe(false);\n });\n\n it(\"invokes the handler with validated args and returns its result\", async () => {\n const adaptor = new HostAdaptor();\n await McpAppBridge.getInstance().getApp();\n\n const handler = vi.fn(({ san }: { san: string }) => ({\n content: [{ type: \"text\" as const, text: `played ${san}` }],\n structuredContent: { lastMove: san },\n }));\n\n adaptor.registerViewTool(\n { name: \"chess_make_move\", inputSchema: { san: z.string() } },\n handler as never,\n );\n\n const response = await callHost(\"tools/call\", {\n name: \"chess_make_move\",\n arguments: { san: \"e4\" },\n });\n const result = response?.result;\n\n // ext-apps invokes the callback as `(args, extra)`; assert on the args only.\n expect(handler.mock.calls[0]?.[0]).toEqual({ san: \"e4\" });\n expect(result?.structuredContent).toEqual({ lastMove: \"e4\" });\n expect(result?.isError).toBeFalsy();\n expect(result?.content).toEqual([{ type: \"text\", text: \"played e4\" }]);\n });\n\n it(\"rejects the call without invoking the handler when args are invalid\", async () => {\n const adaptor = new HostAdaptor();\n await McpAppBridge.getInstance().getApp();\n\n const handler = vi.fn(() => ({ content: [] }));\n adaptor.registerViewTool(\n { name: \"chess_make_move\", inputSchema: { san: z.string() } },\n handler as never,\n );\n\n // ext-apps validates input against the schema and rejects with a JSON-RPC\n // error before the handler runs.\n const response = await callHost(\"tools/call\", {\n name: \"chess_make_move\",\n arguments: { san: 42 },\n });\n\n expect(handler).not.toHaveBeenCalled();\n expect(response?.error).toBeDefined();\n });\n\n it(\"rejects a call to an unknown tool\", async () => {\n await McpAppBridge.getInstance().getApp();\n const response = await callHost(\"tools/call\", {\n name: \"nope\",\n arguments: {},\n });\n expect(response?.error).toBeDefined();\n });\n\n it(\"removes the tool and notifies the host when unregistered\", async () => {\n const adaptor = new HostAdaptor();\n await McpAppBridge.getInstance().getApp();\n\n const unregister = adaptor.registerViewTool(\n { name: \"chess_reset\" },\n () => ({ content: [{ type: \"text\", text: \"reset\" }] }),\n );\n\n await waitFor(() => {\n expect(\n outgoing.some((m) => m.method === \"notifications/tools/list_changed\"),\n ).toBe(true);\n });\n\n let listed = await callHost(\"tools/list\");\n expect(listed?.result?.tools).toHaveLength(1);\n\n unregister();\n listed = await callHost(\"tools/list\");\n expect(listed?.result?.tools).toHaveLength(0);\n });\n});\n"]}
@@ -200,5 +200,15 @@ export interface Adaptor {
200
200
  selectFiles(): Promise<FileMetadata[]>;
201
201
  openModal(options: RequestModalOptions): void;
202
202
  setOpenInAppUrl(href: string): Promise<void>;
203
+ closeModal(): void;
203
204
  registerViewTool(config: ViewToolConfig, handler: AnyViewToolHandler): () => void;
204
205
  }
206
+ /**
207
+ * Thrown when a host bridge method is called in a runtime that doesn't
208
+ * support it (e.g. `uploadFile` outside the Apps SDK runtime).
209
+ */
210
+ export declare class NotSupportedError extends Error {
211
+ readonly method: string;
212
+ readonly reason?: string | undefined;
213
+ constructor(method: string, reason?: string | undefined);
214
+ }
@@ -1,2 +1,15 @@
1
- export {};
1
+ /**
2
+ * Thrown when a host bridge method is called in a runtime that doesn't
3
+ * support it (e.g. `uploadFile` outside the Apps SDK runtime).
4
+ */
5
+ export class NotSupportedError extends Error {
6
+ method;
7
+ reason;
8
+ constructor(method, reason) {
9
+ super(`${method} is not supported in this runtime${reason ? `: ${reason}` : ""}`);
10
+ this.method = method;
11
+ this.reason = reason;
12
+ this.name = "NotSupportedError";
13
+ }
14
+ }
2
15
  //# sourceMappingURL=types.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/web/bridges/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n SchemaOutput,\n ZodRawShapeCompat,\n} from \"@modelcontextprotocol/sdk/server/zod-compat.js\";\nimport type {\n CallToolResult,\n EmbeddedResource,\n ResourceLink,\n ToolAnnotations,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { useSyncExternalStore } from \"react\";\nimport type { ViewHostType } from \"../../server/index.js\";\n\n/**\n * Globals injected on `window.skybridge` by the host. Tells the view which\n * runtime it's running under and where to reach the MCP server.\n */\nexport type SkybridgeProperties = {\n hostType: ViewHostType;\n serverUrl: string;\n};\n\ndeclare global {\n interface Window {\n skybridge: SkybridgeProperties;\n }\n}\n\n/** Arguments passed to a tool call. `null` for tools that take no input. */\nexport type CallToolArgs = Record<string, unknown> | null;\n\n/**\n * Result of a tool call as surfaced to the view: MCP `content` blocks plus\n * the typed `structuredContent` and optional `meta`. `isError` is set when\n * the server marks the call as failed.\n */\nexport type CallToolResponse = {\n content: CallToolResult[\"content\"];\n structuredContent: NonNullable<CallToolResult[\"structuredContent\"]>;\n isError: NonNullable<CallToolResult[\"isError\"]>;\n meta?: CallToolResult[\"_meta\"];\n};\n\n/**\n * How the view is laid out by the host. `\"modal\"` is host-driven (see\n * {@link useRequestModal}); `\"pip\"`, `\"inline\"`, and `\"fullscreen\"` are\n * requestable via {@link useDisplayMode}.\n */\nexport type DisplayMode = \"pip\" | \"inline\" | \"fullscreen\" | \"modal\";\n/** Subset of {@link DisplayMode} that the view can request from the host. */\nexport type RequestDisplayMode = Exclude<DisplayMode, \"modal\">;\n\n/** Host theme. Mirror this in your view's styling for a native feel. */\nexport type Theme = \"light\" | \"dark\";\n\n/** Coarse device class reported by the host. `\"unknown\"` when unavailable. */\nexport type DeviceType = \"mobile\" | \"tablet\" | \"desktop\" | \"unknown\";\n\n/** Pixel insets the view should keep clear of (notches, home indicators, etc.). */\nexport type SafeAreaInsets = {\n top: number;\n right: number;\n bottom: number;\n left: number;\n};\n\n/** Wrapper around {@link SafeAreaInsets} exposed via {@link useLayout}. */\nexport type SafeArea = {\n insets: SafeAreaInsets;\n};\n\n/** Device and input-capability hints exposed via {@link useUser}. */\nexport type UserAgent = {\n device: {\n type: DeviceType;\n };\n capabilities: {\n hover: boolean;\n touch: boolean;\n };\n};\n\n/**\n * Full snapshot of state the host exposes to the view. Most fields are\n * better accessed through their dedicated hooks (`useLayout`, `useUser`,\n * `useToolInfo`, etc.) — read this directly only for advanced cases.\n */\nexport interface HostContext {\n theme: Theme;\n locale: string;\n displayMode: DisplayMode;\n safeArea: SafeArea;\n maxHeight: number | undefined;\n userAgent: UserAgent;\n toolInput: Record<string, unknown> | null;\n toolOutput: Record<string, unknown> | null;\n toolResponseMetadata: Record<string, unknown> | null;\n display: {\n mode: DisplayMode;\n params?: Record<string, unknown>;\n };\n viewState: Record<string, unknown> | null;\n}\n\n/** @internal `useSyncExternalStore` subscribe signature, re-exported for bridge implementations. */\nexport type Subscribe = Parameters<typeof useSyncExternalStore>[0];\n\n/** @internal Bridge contract implemented by per-host bridge classes. */\nexport interface Bridge<Context> {\n subscribe(key: keyof Context): Subscribe;\n subscribe(keys: readonly (keyof Context)[]): Subscribe;\n getSnapshot<K extends keyof Context>(key: K): Context[K] | undefined;\n}\n\n/** @internal Per-key snapshot store backing {@link useHostContext}. */\nexport type HostContextStore<K extends keyof HostContext> = {\n subscribe: Subscribe;\n getSnapshot: () => HostContext[K];\n};\n\n/** Persisted view state shape (a plain object). See {@link useViewState}. */\nexport type ViewState = Record<string, unknown>;\n\n/** Updater form accepted when writing to view state. */\nexport type SetViewStateAction =\n | ViewState\n | ((prevState: ViewState | null) => ViewState);\n\n/** Reference to a host-managed file (returned by {@link useFiles}). */\nexport type FileMetadata = {\n fileId: string;\n fileName?: string;\n mimeType?: string;\n};\n\n/** Options for {@link useFiles}'s `upload`. `library: true` saves into the user's library when supported. */\nexport type UploadFileOptions = { library?: boolean };\n\n/** Options for {@link useRequestModal}'s `open` call. */\nexport type RequestModalOptions = {\n title?: string;\n params?: Record<string, unknown>;\n template?: string;\n anchor?: { top?: number; left?: number; width?: number; height?: number };\n};\n\n/**\n * Options for {@link useOpenExternal}. Set `redirectUrl: false` to tell the\n * host not to append its `?redirectUrl=…` tracking query parameter when\n * opening allowlisted targets.\n */\nexport type OpenExternalOptions = {\n redirectUrl?: false;\n};\n\n/** Options for {@link useSendFollowUpMessage}. */\nexport type SendFollowUpMessageOptions = { scrollToBottom?: boolean };\n\n/** Options for {@link useRequestSize}. Omit a dimension to leave it unchanged. */\nexport type RequestSizeOptions = {\n width?: number;\n height?: number;\n};\n\nexport type DownloadParams = {\n contents: (EmbeddedResource | ResourceLink)[];\n};\n\nexport type DownloadResult = {\n isError?: boolean;\n};\n\n/**\n * Args passed to a {@link ViewToolHandler}, inferred from the tool's\n * `inputSchema` (optionality preserved). Mirrors the server's `registerTool`.\n */\nexport type InferViewToolArgs<Shape extends ZodRawShapeCompat> = {\n [K in keyof Shape as undefined extends SchemaOutput<Shape[K]>\n ? never\n : K]: SchemaOutput<Shape[K]>;\n} & {\n [K in keyof Shape as undefined extends SchemaOutput<Shape[K]>\n ? K\n : never]?: SchemaOutput<Shape[K]>;\n};\n\n/**\n * Declares a tool the view exposes to the host/model (the MCP Apps\n * \"app-provided tools\" feature). Mirrors the server-side `registerTool` config.\n * Namespace `name` (e.g. `chess_make_move`) to avoid clashing with server tools.\n */\nexport type ViewToolConfig<\n TInput extends ZodRawShapeCompat = ZodRawShapeCompat,\n> = {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: TInput;\n annotations?: ToolAnnotations;\n};\n\n/**\n * Value a {@link ViewToolHandler} returns — a standard MCP `CallToolResult`\n * (`content` blocks plus optional `structuredContent` / `isError` / `_meta`),\n * exactly as `ext-apps`' app tool callbacks return it.\n */\nexport type ViewToolResult = CallToolResult;\n\n/** Handler run when the host calls a view tool. Receives validated, typed args. */\nexport type ViewToolHandler<\n TInput extends ZodRawShapeCompat = ZodRawShapeCompat,\n> = (\n args: InferViewToolArgs<TInput>,\n) => ViewToolResult | Promise<ViewToolResult>;\n\n/** @internal Untyped handler signature stored by the adaptor/bridge after type erasure. */\nexport type AnyViewToolHandler = (\n args: Record<string, unknown>,\n) => ViewToolResult | Promise<ViewToolResult>;\n\n/**\n * @internal\n * Low-level interface every host bridge implements. End-user code should use\n * the React hooks (`useCallTool`, `useViewState`, `useFiles`, …) rather than\n * calling this directly.\n */\nexport interface Adaptor {\n getHostContextStore<K extends keyof HostContext>(key: K): HostContextStore<K>;\n callTool<\n ToolArgs extends CallToolArgs = null,\n ToolResponse extends CallToolResponse = CallToolResponse,\n >(name: string, args: ToolArgs): Promise<ToolResponse>;\n requestDisplayMode(mode: RequestDisplayMode): Promise<{\n mode: RequestDisplayMode;\n }>;\n requestClose(): Promise<void>;\n requestSize(size: RequestSizeOptions): Promise<void>;\n sendFollowUpMessage(\n prompt: string,\n options?: SendFollowUpMessageOptions,\n ): Promise<void>;\n openExternal(href: string, options?: OpenExternalOptions): void;\n download(params: DownloadParams): Promise<DownloadResult>;\n setViewState(stateOrUpdater: SetViewStateAction): Promise<void>;\n uploadFile(file: File, options?: UploadFileOptions): Promise<FileMetadata>;\n getFileDownloadUrl(file: FileMetadata): Promise<{ downloadUrl: string }>;\n selectFiles(): Promise<FileMetadata[]>;\n openModal(options: RequestModalOptions): void;\n setOpenInAppUrl(href: string): Promise<void>;\n registerViewTool(\n config: ViewToolConfig,\n handler: AnyViewToolHandler,\n ): () => void;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/web/bridges/types.ts"],"names":[],"mappings":"AAgQA;;;GAGG;AACH,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IAExB;IACA;IAFlB,YACkB,MAAc,EACd,MAAe;QAE/B,KAAK,CACH,GAAG,MAAM,oCAAoC,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAC3E,CAAC;QALc,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,CAAS;QAK/B,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;IAClC,CAAC;CACF","sourcesContent":["import type {\n SchemaOutput,\n ZodRawShapeCompat,\n} from \"@modelcontextprotocol/sdk/server/zod-compat.js\";\nimport type {\n CallToolResult,\n EmbeddedResource,\n ResourceLink,\n ToolAnnotations,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { useSyncExternalStore } from \"react\";\nimport type { ViewHostType } from \"../../server/index.js\";\n\n/**\n * Globals injected on `window.skybridge` by the host. Tells the view which\n * runtime it's running under and where to reach the MCP server.\n */\nexport type SkybridgeProperties = {\n hostType: ViewHostType;\n serverUrl: string;\n};\n\ndeclare global {\n interface Window {\n skybridge: SkybridgeProperties;\n }\n}\n\n/** Arguments passed to a tool call. `null` for tools that take no input. */\nexport type CallToolArgs = Record<string, unknown> | null;\n\n/**\n * Result of a tool call as surfaced to the view: MCP `content` blocks plus\n * the typed `structuredContent` and optional `meta`. `isError` is set when\n * the server marks the call as failed.\n */\nexport type CallToolResponse = {\n content: CallToolResult[\"content\"];\n structuredContent: NonNullable<CallToolResult[\"structuredContent\"]>;\n isError: NonNullable<CallToolResult[\"isError\"]>;\n meta?: CallToolResult[\"_meta\"];\n};\n\n/**\n * How the view is laid out by the host. `\"modal\"` is host-driven (see\n * {@link useRequestModal}); `\"pip\"`, `\"inline\"`, and `\"fullscreen\"` are\n * requestable via {@link useDisplayMode}.\n */\nexport type DisplayMode = \"pip\" | \"inline\" | \"fullscreen\" | \"modal\";\n/** Subset of {@link DisplayMode} that the view can request from the host. */\nexport type RequestDisplayMode = Exclude<DisplayMode, \"modal\">;\n\n/** Host theme. Mirror this in your view's styling for a native feel. */\nexport type Theme = \"light\" | \"dark\";\n\n/** Coarse device class reported by the host. `\"unknown\"` when unavailable. */\nexport type DeviceType = \"mobile\" | \"tablet\" | \"desktop\" | \"unknown\";\n\n/** Pixel insets the view should keep clear of (notches, home indicators, etc.). */\nexport type SafeAreaInsets = {\n top: number;\n right: number;\n bottom: number;\n left: number;\n};\n\n/** Wrapper around {@link SafeAreaInsets} exposed via {@link useLayout}. */\nexport type SafeArea = {\n insets: SafeAreaInsets;\n};\n\n/** Device and input-capability hints exposed via {@link useUser}. */\nexport type UserAgent = {\n device: {\n type: DeviceType;\n };\n capabilities: {\n hover: boolean;\n touch: boolean;\n };\n};\n\n/**\n * Full snapshot of state the host exposes to the view. Most fields are\n * better accessed through their dedicated hooks (`useLayout`, `useUser`,\n * `useToolInfo`, etc.) — read this directly only for advanced cases.\n */\nexport interface HostContext {\n theme: Theme;\n locale: string;\n displayMode: DisplayMode;\n safeArea: SafeArea;\n maxHeight: number | undefined;\n userAgent: UserAgent;\n toolInput: Record<string, unknown> | null;\n toolOutput: Record<string, unknown> | null;\n toolResponseMetadata: Record<string, unknown> | null;\n display: {\n mode: DisplayMode;\n params?: Record<string, unknown>;\n };\n viewState: Record<string, unknown> | null;\n}\n\n/** @internal `useSyncExternalStore` subscribe signature, re-exported for bridge implementations. */\nexport type Subscribe = Parameters<typeof useSyncExternalStore>[0];\n\n/** @internal Bridge contract implemented by per-host bridge classes. */\nexport interface Bridge<Context> {\n subscribe(key: keyof Context): Subscribe;\n subscribe(keys: readonly (keyof Context)[]): Subscribe;\n getSnapshot<K extends keyof Context>(key: K): Context[K] | undefined;\n}\n\n/** @internal Per-key snapshot store backing {@link useHostContext}. */\nexport type HostContextStore<K extends keyof HostContext> = {\n subscribe: Subscribe;\n getSnapshot: () => HostContext[K];\n};\n\n/** Persisted view state shape (a plain object). See {@link useViewState}. */\nexport type ViewState = Record<string, unknown>;\n\n/** Updater form accepted when writing to view state. */\nexport type SetViewStateAction =\n | ViewState\n | ((prevState: ViewState | null) => ViewState);\n\n/** Reference to a host-managed file (returned by {@link useFiles}). */\nexport type FileMetadata = {\n fileId: string;\n fileName?: string;\n mimeType?: string;\n};\n\n/** Options for {@link useFiles}'s `upload`. `library: true` saves into the user's library when supported. */\nexport type UploadFileOptions = { library?: boolean };\n\n/** Options for {@link useRequestModal}'s `open` call. */\nexport type RequestModalOptions = {\n title?: string;\n params?: Record<string, unknown>;\n template?: string;\n anchor?: { top?: number; left?: number; width?: number; height?: number };\n};\n\n/**\n * Options for {@link useOpenExternal}. Set `redirectUrl: false` to tell the\n * host not to append its `?redirectUrl=…` tracking query parameter when\n * opening allowlisted targets.\n */\nexport type OpenExternalOptions = {\n redirectUrl?: false;\n};\n\n/** Options for {@link useSendFollowUpMessage}. */\nexport type SendFollowUpMessageOptions = { scrollToBottom?: boolean };\n\n/** Options for {@link useRequestSize}. Omit a dimension to leave it unchanged. */\nexport type RequestSizeOptions = {\n width?: number;\n height?: number;\n};\n\nexport type DownloadParams = {\n contents: (EmbeddedResource | ResourceLink)[];\n};\n\nexport type DownloadResult = {\n isError?: boolean;\n};\n\n/**\n * Args passed to a {@link ViewToolHandler}, inferred from the tool's\n * `inputSchema` (optionality preserved). Mirrors the server's `registerTool`.\n */\nexport type InferViewToolArgs<Shape extends ZodRawShapeCompat> = {\n [K in keyof Shape as undefined extends SchemaOutput<Shape[K]>\n ? never\n : K]: SchemaOutput<Shape[K]>;\n} & {\n [K in keyof Shape as undefined extends SchemaOutput<Shape[K]>\n ? K\n : never]?: SchemaOutput<Shape[K]>;\n};\n\n/**\n * Declares a tool the view exposes to the host/model (the MCP Apps\n * \"app-provided tools\" feature). Mirrors the server-side `registerTool` config.\n * Namespace `name` (e.g. `chess_make_move`) to avoid clashing with server tools.\n */\nexport type ViewToolConfig<\n TInput extends ZodRawShapeCompat = ZodRawShapeCompat,\n> = {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: TInput;\n annotations?: ToolAnnotations;\n};\n\n/**\n * Value a {@link ViewToolHandler} returns — a standard MCP `CallToolResult`\n * (`content` blocks plus optional `structuredContent` / `isError` / `_meta`),\n * exactly as `ext-apps`' app tool callbacks return it.\n */\nexport type ViewToolResult = CallToolResult;\n\n/** Handler run when the host calls a view tool. Receives validated, typed args. */\nexport type ViewToolHandler<\n TInput extends ZodRawShapeCompat = ZodRawShapeCompat,\n> = (\n args: InferViewToolArgs<TInput>,\n) => ViewToolResult | Promise<ViewToolResult>;\n\n/** @internal Untyped handler signature stored by the adaptor/bridge after type erasure. */\nexport type AnyViewToolHandler = (\n args: Record<string, unknown>,\n) => ViewToolResult | Promise<ViewToolResult>;\n\n/**\n * @internal\n * Low-level interface every host bridge implements. End-user code should use\n * the React hooks (`useCallTool`, `useViewState`, `useFiles`, …) rather than\n * calling this directly.\n */\nexport interface Adaptor {\n getHostContextStore<K extends keyof HostContext>(key: K): HostContextStore<K>;\n callTool<\n ToolArgs extends CallToolArgs = null,\n ToolResponse extends CallToolResponse = CallToolResponse,\n >(name: string, args: ToolArgs): Promise<ToolResponse>;\n requestDisplayMode(mode: RequestDisplayMode): Promise<{\n mode: RequestDisplayMode;\n }>;\n requestClose(): Promise<void>;\n requestSize(size: RequestSizeOptions): Promise<void>;\n sendFollowUpMessage(\n prompt: string,\n options?: SendFollowUpMessageOptions,\n ): Promise<void>;\n openExternal(href: string, options?: OpenExternalOptions): void;\n download(params: DownloadParams): Promise<DownloadResult>;\n setViewState(stateOrUpdater: SetViewStateAction): Promise<void>;\n uploadFile(file: File, options?: UploadFileOptions): Promise<FileMetadata>;\n getFileDownloadUrl(file: FileMetadata): Promise<{ downloadUrl: string }>;\n selectFiles(): Promise<FileMetadata[]>;\n openModal(options: RequestModalOptions): void;\n setOpenInAppUrl(href: string): Promise<void>;\n closeModal(): void;\n registerViewTool(\n config: ViewToolConfig,\n handler: AnyViewToolHandler,\n ): () => void;\n}\n\n/**\n * Thrown when a host bridge method is called in a runtime that doesn't\n * support it (e.g. `uploadFile` outside the Apps SDK runtime).\n */\nexport class NotSupportedError extends Error {\n constructor(\n public readonly method: string,\n public readonly reason?: string,\n ) {\n super(\n `${method} is not supported in this runtime${reason ? `: ${reason}` : \"\"}`,\n );\n this.name = \"NotSupportedError\";\n }\n}\n"]}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { NotSupportedError } from "./types.js";
3
+ describe("NotSupportedError", () => {
4
+ it("includes method name in message", () => {
5
+ const err = new NotSupportedError("uploadFile");
6
+ expect(err.message).toBe("uploadFile is not supported in this runtime");
7
+ expect(err.name).toBe("NotSupportedError");
8
+ expect(err.method).toBe("uploadFile");
9
+ });
10
+ it("includes reason when provided", () => {
11
+ const err = new NotSupportedError("callTool", "MCP transport unavailable");
12
+ expect(err.message).toBe("callTool is not supported in this runtime: MCP transport unavailable");
13
+ expect(err.reason).toBe("MCP transport unavailable");
14
+ });
15
+ it("is an instance of Error", () => {
16
+ expect(new NotSupportedError("x")).toBeInstanceOf(Error);
17
+ });
18
+ });
19
+ //# sourceMappingURL=types.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.test.js","sourceRoot":"","sources":["../../../src/web/bridges/types.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAE/C,QAAQ,CAAC,mBAAmB,EAAE,GAAG,EAAE;IACjC,EAAE,CAAC,iCAAiC,EAAE,GAAG,EAAE;QACzC,MAAM,GAAG,GAAG,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAAC;QAChD,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,6CAA6C,CAAC,CAAC;QACxE,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;QAC3C,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACxC,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,+BAA+B,EAAE,GAAG,EAAE;QACvC,MAAM,GAAG,GAAG,IAAI,iBAAiB,CAAC,UAAU,EAAE,2BAA2B,CAAC,CAAC;QAC3E,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,IAAI,CACtB,sEAAsE,CACvE,CAAC;QACF,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,2BAA2B,CAAC,CAAC;IACvD,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,yBAAyB,EAAE,GAAG,EAAE;QACjC,MAAM,CAAC,IAAI,iBAAiB,CAAC,GAAG,CAAC,CAAC,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC3D,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { describe, expect, it } from \"vitest\";\nimport { NotSupportedError } from \"./types.js\";\n\ndescribe(\"NotSupportedError\", () => {\n it(\"includes method name in message\", () => {\n const err = new NotSupportedError(\"uploadFile\");\n expect(err.message).toBe(\"uploadFile is not supported in this runtime\");\n expect(err.name).toBe(\"NotSupportedError\");\n expect(err.method).toBe(\"uploadFile\");\n });\n\n it(\"includes reason when provided\", () => {\n const err = new NotSupportedError(\"callTool\", \"MCP transport unavailable\");\n expect(err.message).toBe(\n \"callTool is not supported in this runtime: MCP transport unavailable\",\n );\n expect(err.reason).toBe(\"MCP transport unavailable\");\n });\n\n it(\"is an instance of Error\", () => {\n expect(new NotSupportedError(\"x\")).toBeInstanceOf(Error);\n });\n});\n"]}
@@ -1,6 +1,6 @@
1
1
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useEffect, useSyncExternalStore } from "react";
3
- import { McpAppAdaptor } from "../bridges/index.js";
3
+ import { getAdaptor } from "../bridges/index.js";
4
4
  const modalStyles = `
5
5
  .sb-modal-backdrop {
6
6
  position: fixed;
@@ -20,8 +20,9 @@ const modalStyles = `
20
20
  }
21
21
  `;
22
22
  export function ModalProvider({ children }) {
23
- const adaptor = McpAppAdaptor.getInstance();
24
- const { mode } = useSyncExternalStore(adaptor.getHostContextStore("display").subscribe, adaptor.getHostContextStore("display").getSnapshot);
23
+ const adaptor = getAdaptor();
24
+ const displayStore = adaptor.getHostContextStore("display");
25
+ const { mode } = useSyncExternalStore(displayStore.subscribe, displayStore.getSnapshot);
25
26
  const isOpen = mode === "modal";
26
27
  const handleBackdropClick = (e) => {
27
28
  if (e.target === e.currentTarget) {
@@ -1 +1 @@
1
- {"version":3,"file":"modal-provider.js","sourceRoot":"","sources":["../../../src/web/components/modal-provider.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAkB,SAAS,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AACxE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,MAAM,WAAW,GAAG;;;;;;;;;;;;;;;;;CAiBnB,CAAC;AAEF,MAAM,UAAU,aAAa,CAAC,EAAE,QAAQ,EAA2B;IACjE,MAAM,OAAO,GAAG,aAAa,CAAC,WAAW,EAAE,CAAC;IAE5C,MAAM,EAAE,IAAI,EAAE,GAAG,oBAAoB,CACnC,OAAO,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC,SAAS,EAChD,OAAO,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC,WAAW,CACnD,CAAC;IACF,MAAM,MAAM,GAAG,IAAI,KAAK,OAAO,CAAC;IAEhC,MAAM,mBAAmB,GAAG,CAAC,CAAmB,EAAE,EAAE;QAClD,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,aAAa,EAAE,CAAC;YACjC,OAAO,CAAC,UAAU,EAAE,CAAC;QACvB,CAAC;IACH,CAAC,CAAC;IAEF,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,OAAO;QACT,CAAC;QACD,MAAM,OAAO,GAAG,CAAC,CAAgB,EAAE,EAAE;YACnC,IAAI,CAAC,CAAC,GAAG,KAAK,QAAQ,EAAE,CAAC;gBACvB,OAAO,CAAC,UAAU,EAAE,CAAC;YACvB,CAAC;QACH,CAAC,CAAC;QACF,QAAQ,CAAC,gBAAgB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAC9C,OAAO,GAAG,EAAE,CAAC,QAAQ,CAAC,mBAAmB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;IAChE,CAAC,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAEtB,OAAO,CACL,8BACE,0BAAQ,WAAW,GAAS,EAC3B,MAAM,IAAI,CAET,cACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,mBAAmB,EAC7B,OAAO,EAAE,mBAAmB,GAC5B,CACH,EACD,cAAK,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,SAAS,YACtD,QAAQ,GACL,IACL,CACJ,CAAC;AACJ,CAAC","sourcesContent":["import { type ReactNode, useEffect, useSyncExternalStore } from \"react\";\nimport { McpAppAdaptor } from \"../bridges/index.js\";\n\nconst modalStyles = `\n.sb-modal-backdrop {\n position: fixed;\n inset: 0;\n background: rgba(0, 0, 0, 0.5);\n z-index: 9998;\n}\n.sb-modal-container {\n border-radius: 12px;\n position: fixed;\n inset: 0;\n margin: auto;\n width: fit-content;\n height: fit-content;\n background: white;\n z-index: 9999;\n}\n`;\n\nexport function ModalProvider({ children }: { children: ReactNode }) {\n const adaptor = McpAppAdaptor.getInstance();\n\n const { mode } = useSyncExternalStore(\n adaptor.getHostContextStore(\"display\").subscribe,\n adaptor.getHostContextStore(\"display\").getSnapshot,\n );\n const isOpen = mode === \"modal\";\n\n const handleBackdropClick = (e: React.MouseEvent) => {\n if (e.target === e.currentTarget) {\n adaptor.closeModal();\n }\n };\n\n useEffect(() => {\n if (!isOpen) {\n return;\n }\n const handler = (e: KeyboardEvent) => {\n if (e.key === \"Escape\") {\n adaptor.closeModal();\n }\n };\n document.addEventListener(\"keydown\", handler);\n return () => document.removeEventListener(\"keydown\", handler);\n }, [isOpen, adaptor]);\n\n return (\n <>\n <style>{modalStyles}</style>\n {isOpen && (\n // biome-ignore lint/a11y/useKeyWithClickEvents: backdrop isn't focusable\n <div\n role=\"dialog\"\n className=\"sb-modal-backdrop\"\n onClick={handleBackdropClick}\n />\n )}\n <div className={isOpen ? \"sb-modal-container\" : undefined}>\n {children}\n </div>\n </>\n );\n}\n"]}
1
+ {"version":3,"file":"modal-provider.js","sourceRoot":"","sources":["../../../src/web/components/modal-provider.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAkB,SAAS,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AACxE,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEjD,MAAM,WAAW,GAAG;;;;;;;;;;;;;;;;;CAiBnB,CAAC;AAEF,MAAM,UAAU,aAAa,CAAC,EAAE,QAAQ,EAA2B;IACjE,MAAM,OAAO,GAAG,UAAU,EAAE,CAAC;IAC7B,MAAM,YAAY,GAAG,OAAO,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC;IAC5D,MAAM,EAAE,IAAI,EAAE,GAAG,oBAAoB,CACnC,YAAY,CAAC,SAAS,EACtB,YAAY,CAAC,WAAW,CACzB,CAAC;IACF,MAAM,MAAM,GAAG,IAAI,KAAK,OAAO,CAAC;IAEhC,MAAM,mBAAmB,GAAG,CAAC,CAAmB,EAAE,EAAE;QAClD,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,aAAa,EAAE,CAAC;YACjC,OAAO,CAAC,UAAU,EAAE,CAAC;QACvB,CAAC;IACH,CAAC,CAAC;IAEF,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,OAAO;QACT,CAAC;QACD,MAAM,OAAO,GAAG,CAAC,CAAgB,EAAE,EAAE;YACnC,IAAI,CAAC,CAAC,GAAG,KAAK,QAAQ,EAAE,CAAC;gBACvB,OAAO,CAAC,UAAU,EAAE,CAAC;YACvB,CAAC;QACH,CAAC,CAAC;QACF,QAAQ,CAAC,gBAAgB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAC9C,OAAO,GAAG,EAAE,CAAC,QAAQ,CAAC,mBAAmB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;IAChE,CAAC,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAEtB,OAAO,CACL,8BACE,0BAAQ,WAAW,GAAS,EAC3B,MAAM,IAAI,CAET,cACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,mBAAmB,EAC7B,OAAO,EAAE,mBAAmB,GAC5B,CACH,EACD,cAAK,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,SAAS,YACtD,QAAQ,GACL,IACL,CACJ,CAAC;AACJ,CAAC","sourcesContent":["import { type ReactNode, useEffect, useSyncExternalStore } from \"react\";\nimport { getAdaptor } from \"../bridges/index.js\";\n\nconst modalStyles = `\n.sb-modal-backdrop {\n position: fixed;\n inset: 0;\n background: rgba(0, 0, 0, 0.5);\n z-index: 9998;\n}\n.sb-modal-container {\n border-radius: 12px;\n position: fixed;\n inset: 0;\n margin: auto;\n width: fit-content;\n height: fit-content;\n background: white;\n z-index: 9999;\n}\n`;\n\nexport function ModalProvider({ children }: { children: ReactNode }) {\n const adaptor = getAdaptor();\n const displayStore = adaptor.getHostContextStore(\"display\");\n const { mode } = useSyncExternalStore(\n displayStore.subscribe,\n displayStore.getSnapshot,\n );\n const isOpen = mode === \"modal\";\n\n const handleBackdropClick = (e: React.MouseEvent) => {\n if (e.target === e.currentTarget) {\n adaptor.closeModal();\n }\n };\n\n useEffect(() => {\n if (!isOpen) {\n return;\n }\n const handler = (e: KeyboardEvent) => {\n if (e.key === \"Escape\") {\n adaptor.closeModal();\n }\n };\n document.addEventListener(\"keydown\", handler);\n return () => document.removeEventListener(\"keydown\", handler);\n }, [isOpen, adaptor]);\n\n return (\n <>\n <style>{modalStyles}</style>\n {isOpen && (\n // biome-ignore lint/a11y/useKeyWithClickEvents: backdrop isn't focusable\n <div\n role=\"dialog\"\n className=\"sb-modal-backdrop\"\n onClick={handleBackdropClick}\n />\n )}\n <div className={isOpen ? \"sb-modal-container\" : undefined}>\n {children}\n </div>\n </>\n );\n}\n"]}
@@ -1,12 +1,14 @@
1
1
  import { cleanup } from "@testing-library/react";
2
2
  import { afterEach, beforeEach, describe, expect, it, vi, } from "vitest";
3
- import { McpAppAdaptor } from "./bridges/mcp-app/adaptor.js";
3
+ import { HostAdaptor } from "./bridges/adaptor.js";
4
+ import { getAdaptor } from "./bridges/get-adaptor.js";
4
5
  import { McpAppBridge } from "./bridges/mcp-app/bridge.js";
5
6
  import { createStore } from "./create-store.js";
6
7
  import { VIEW_CONTEXT_KEY } from "./data-llm.js";
7
8
  import { getMcpAppHostPostMessageMock, MockResizeObserver, } from "./hooks/test/utils.js";
8
9
  describe("createStore", () => {
9
10
  afterEach(() => {
11
+ HostAdaptor.resetInstance();
10
12
  vi.unstubAllGlobals();
11
13
  vi.resetAllMocks();
12
14
  });
@@ -78,16 +80,17 @@ describe("createStore", () => {
78
80
  });
79
81
  describe("mcp-app mode", () => {
80
82
  beforeEach(() => {
83
+ vi.stubGlobal("openai", undefined);
81
84
  vi.stubGlobal("skybridge", { hostType: "mcp-app" });
82
85
  vi.stubGlobal("ResizeObserver", MockResizeObserver);
83
86
  });
84
87
  afterEach(async () => {
85
88
  cleanup();
89
+ HostAdaptor.resetInstance();
86
90
  McpAppBridge.resetInstance();
87
- McpAppAdaptor.resetInstance();
88
91
  });
89
92
  it("should initialize with null viewState", () => {
90
- const adaptor = McpAppAdaptor.getInstance();
93
+ const adaptor = getAdaptor();
91
94
  const viewState = adaptor.getHostContextStore("viewState").getSnapshot();
92
95
  expect(viewState).toBeNull();
93
96
  });
@@ -99,7 +102,7 @@ describe("createStore", () => {
99
102
  expect(store.getState()).toEqual({ count: 0 });
100
103
  });
101
104
  it("should update in-memory state via setViewState", async () => {
102
- const adaptor = McpAppAdaptor.getInstance();
105
+ const adaptor = getAdaptor();
103
106
  vi.spyOn(adaptor, "setViewState").mockResolvedValue(undefined);
104
107
  const storeCreator = (set) => ({
105
108
  count: 0,
@@ -114,7 +117,7 @@ describe("createStore", () => {
114
117
  it("should notify listeners when view state changes", async () => {
115
118
  const postMessageMock = getMcpAppHostPostMessageMock();
116
119
  vi.stubGlobal("parent", { postMessage: postMessageMock });
117
- const adaptor = McpAppAdaptor.getInstance();
120
+ const adaptor = getAdaptor();
118
121
  const listener = vi.fn();
119
122
  adaptor.getHostContextStore("viewState").subscribe(listener);
120
123
  await adaptor.setViewState({ count: 42 });
@@ -1 +1 @@
1
- {"version":3,"file":"create-store.test.js","sourceRoot":"","sources":["../../src/web/create-store.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EACL,SAAS,EACT,UAAU,EACV,QAAQ,EACR,MAAM,EACN,EAAE,EAEF,EAAE,GACH,MAAM,QAAQ,CAAC;AAEhB,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EACL,4BAA4B,EAC5B,kBAAkB,GACnB,MAAM,uBAAuB,CAAC;AAE/B,QAAQ,CAAC,aAAa,EAAE,GAAG,EAAE;IAC3B,SAAS,CAAC,GAAG,EAAE;QACb,EAAE,CAAC,gBAAgB,EAAE,CAAC;QACtB,EAAE,CAAC,aAAa,EAAE,CAAC;IACrB,CAAC,CAAC,CAAC;IAEH,QAAQ,CAAC,eAAe,EAAE,GAAG,EAAE;QAC7B,IAAI,UAGH,CAAC;QAEF,UAAU,CAAC,GAAG,EAAE;YACd,UAAU,GAAG;gBACX,WAAW,EAAE,IAAI;gBACjB,cAAc,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,iBAAiB,CAAC,SAAS,CAAC;aACrD,CAAC;YACF,EAAE,CAAC,UAAU,CAAC,Q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,QAAQ,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;YAEzB,OAAO,CAAC,mBAAmB,CAAC,WAAW,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;YAC7D,MAAM,OAAO,CAAC,YAAY,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;YAE1C,MAAM,CAAC,eAAe,CAAC,CAAC,oBAAoB,CAC1C,MAAM,CAAC,gBAAgB,CAAC,EAAE,MAAM,EAAE,yBAAyB,EAAE,CAAC,EAC9D,GAAG,CACJ,CAAC;YACF,MAAM,CAAC,QAAQ,CAAC,CAAC,gBAAgB,EAAE,CAAC;YACpC,MAAM,CAAC,OAAO,CAAC,mBAAmB,CAAC,WAAW,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,OAAO,CAAC;gBACrE,KAAK,EAAE,EAAE;aACV,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { cleanup } from \"@testing-library/react\";\nimport {\n afterEach,\n beforeEach,\n describe,\n expect,\n it,\n type Mock,\n vi,\n} from \"vitest\";\nimport type { StateCreator } from \"zustand\";\nimport { McpAppAdaptor } from \"./bridges/mcp-app/adaptor.js\";\nimport { McpAppBridge } from \"./bridges/mcp-app/bridge.js\";\nimport { createStore } from \"./create-store.js\";\nimport { VIEW_CONTEXT_KEY } from \"./data-llm.js\";\nimport {\n getMcpAppHostPostMessageMock,\n MockResizeObserver,\n} from \"./hooks/test/utils.js\";\n\ndescribe(\"createStore\", () => {\n afterEach(() => {\n vi.unstubAllGlobals();\n vi.resetAllMocks();\n });\n\n describe(\"apps-sdk mode\", () => {\n let OpenaiMock: {\n widgetState: unknown;\n setWidgetState: Mock;\n };\n\n beforeEach(() => {\n OpenaiMock = {\n widgetState: null,\n setWidgetState: vi.fn().mockResolvedValue(undefined),\n };\n vi.stubGlobal(\"openai\", OpenaiMock);\n vi.stubGlobal(\"skybridge\", { hostType: \"apps-sdk\" });\n });\n\n it(\"should create a store without default state\", () => {\n type TestState = { count: number };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n });\n\n const store = createStore(storeCreator);\n\n expect(store.getState()).toEqual({ count: 0 });\n });\n\n it(\"should create a store with default state\", () => {\n type TestState = { count: number; name: string };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n name: \"initial\",\n });\n const defaultState = { count: 5, name: \"default\" };\n\n const store = createStore(storeCreator, defaultState);\n\n expect(store.getState()).toEqual({ count: 5, name: \"default\" });\n });\n\n it(\"should initialize from window.openai.widgetState when available\", () => {\n type TestState = { count: number; name: string };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n name: \"initial\",\n });\n const windowState = { count: 20, name: \"window\" };\n OpenaiMock.widgetState = { modelContent: windowState };\n\n const store = createStore(storeCreator);\n\n expect(store.getState()).toEqual({ count: 20, name: \"window\" });\n });\n\n it(\"should persist state changes to window.openai.setWidgetState\", async () => {\n type TestState = { count: number; increment: () => void };\n const storeCreator: StateCreator<TestState, [], [], TestState> = (\n set,\n ) => ({\n count: 0,\n increment: () => set((state) => ({ count: state.count + 1 })),\n });\n\n const store = createStore(storeCreator);\n store.getState().increment();\n\n await vi.waitFor(() => {\n expect(OpenaiMock.setWidgetState).toHaveBeenCalled();\n });\n\n const callArgs = OpenaiMock.setWidgetState.mock.calls[0]?.[0];\n expect(callArgs).toEqual({\n modelContent: { count: 1 },\n privateContent: {},\n });\n });\n\n it(\"should filter view context from initial state\", () => {\n type TestState = { count: number };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n });\n const windowState = {\n count: 5,\n [VIEW_CONTEXT_KEY]: \"context-value\",\n };\n OpenaiMock.widgetState = { modelContent: windowState };\n\n const store = createStore(storeCreator);\n\n expect(store.getState()).toEqual({ count: 5 });\n expect(\n (store.getState() as Record<string, unknown>)[VIEW_CONTEXT_KEY],\n ).toBeUndefined();\n });\n });\n\n describe(\"mcp-app mode\", () => {\n beforeEach(() => {\n vi.stubGlobal(\"skybridge\", { hostType: \"mcp-app\" });\n vi.stubGlobal(\"ResizeObserver\", MockResizeObserver);\n });\n\n afterEach(async () => {\n cleanup();\n McpAppBridge.resetInstance();\n McpAppAdaptor.resetInstance();\n });\n\n it(\"should initialize with null viewState\", () => {\n const adaptor = McpAppAdaptor.getInstance();\n const viewState = adaptor.getHostContextStore(\"viewState\").getSnapshot();\n\n expect(viewState).toBeNull();\n });\n\n it(\"should create a store with default state when no persisted state exists\", () => {\n type TestState = { count: number };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n });\n\n const store = createStore(storeCreator);\n\n expect(store.getState()).toEqual({ count: 0 });\n });\n\n it(\"should update in-memory state via setViewState\", async () => {\n const adaptor = McpAppAdaptor.getInstance();\n vi.spyOn(adaptor, \"setViewState\").mockResolvedValue(undefined);\n\n type TestState = { count: number; increment: () => void };\n const storeCreator: StateCreator<TestState, [], [], TestState> = (\n set,\n ) => ({\n count: 0,\n increment: () => set((state) => ({ count: state.count + 1 })),\n });\n\n const store = createStore(storeCreator);\n store.getState().increment();\n\n await vi.waitFor(() => {\n expect(adaptor.setViewState).toHaveBeenCalledWith({ count: 1 });\n });\n });\n\n it(\"should notify listeners when view state changes\", async () => {\n const postMessageMock = getMcpAppHostPostMessageMock();\n vi.stubGlobal(\"parent\", { postMessage: postMessageMock });\n\n const adaptor = McpAppAdaptor.getInstance();\n const listener = vi.fn();\n\n adaptor.getHostContextStore(\"viewState\").subscribe(listener);\n await adaptor.setViewState({ count: 42 });\n\n expect(postMessageMock).toHaveBeenCalledWith(\n expect.objectContaining({ method: \"ui/update-model-context\" }),\n \"*\",\n );\n expect(listener).toHaveBeenCalled();\n expect(adaptor.getHostContextStore(\"viewState\").getSnapshot()).toEqual({\n count: 42,\n });\n });\n });\n});\n"]}
1
+ {"version":3,"file":"create-store.test.js","sourceRoot":"","sources":["../../src/web/create-store.test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C,oBAAoB,CAC1C,MAAM,CAAC,gBAAgB,CAAC,EAAE,MAAM,EAAE,yBAAyB,EAAE,CAAC,EAC9D,GAAG,CACJ,CAAC;YACF,MAAM,CAAC,QAAQ,CAAC,CAAC,gBAAgB,EAAE,CAAC;YACpC,MAAM,CAAC,OAAO,CAAC,mBAAmB,CAAC,WAAW,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,OAAO,CAAC;gBACrE,KAAK,EAAE,EAAE;aACV,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { cleanup } from \"@testing-library/react\";\nimport {\n afterEach,\n beforeEach,\n describe,\n expect,\n it,\n type Mock,\n vi,\n} from \"vitest\";\nimport type { StateCreator } from \"zustand\";\nimport { HostAdaptor } from \"./bridges/adaptor.js\";\nimport { getAdaptor } from \"./bridges/get-adaptor.js\";\nimport { McpAppBridge } from \"./bridges/mcp-app/bridge.js\";\nimport { createStore } from \"./create-store.js\";\nimport { VIEW_CONTEXT_KEY } from \"./data-llm.js\";\nimport {\n getMcpAppHostPostMessageMock,\n MockResizeObserver,\n} from \"./hooks/test/utils.js\";\n\ndescribe(\"createStore\", () => {\n afterEach(() => {\n HostAdaptor.resetInstance();\n vi.unstubAllGlobals();\n vi.resetAllMocks();\n });\n\n describe(\"apps-sdk mode\", () => {\n let OpenaiMock: {\n widgetState: unknown;\n setWidgetState: Mock;\n };\n\n beforeEach(() => {\n OpenaiMock = {\n widgetState: null,\n setWidgetState: vi.fn().mockResolvedValue(undefined),\n };\n vi.stubGlobal(\"openai\", OpenaiMock);\n vi.stubGlobal(\"skybridge\", { hostType: \"apps-sdk\" });\n });\n\n it(\"should create a store without default state\", () => {\n type TestState = { count: number };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n });\n\n const store = createStore(storeCreator);\n\n expect(store.getState()).toEqual({ count: 0 });\n });\n\n it(\"should create a store with default state\", () => {\n type TestState = { count: number; name: string };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n name: \"initial\",\n });\n const defaultState = { count: 5, name: \"default\" };\n\n const store = createStore(storeCreator, defaultState);\n\n expect(store.getState()).toEqual({ count: 5, name: \"default\" });\n });\n\n it(\"should initialize from window.openai.widgetState when available\", () => {\n type TestState = { count: number; name: string };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n name: \"initial\",\n });\n const windowState = { count: 20, name: \"window\" };\n OpenaiMock.widgetState = { modelContent: windowState };\n\n const store = createStore(storeCreator);\n\n expect(store.getState()).toEqual({ count: 20, name: \"window\" });\n });\n\n it(\"should persist state changes to window.openai.setWidgetState\", async () => {\n type TestState = { count: number; increment: () => void };\n const storeCreator: StateCreator<TestState, [], [], TestState> = (\n set,\n ) => ({\n count: 0,\n increment: () => set((state) => ({ count: state.count + 1 })),\n });\n\n const store = createStore(storeCreator);\n store.getState().increment();\n\n await vi.waitFor(() => {\n expect(OpenaiMock.setWidgetState).toHaveBeenCalled();\n });\n\n const callArgs = OpenaiMock.setWidgetState.mock.calls[0]?.[0];\n expect(callArgs).toEqual({\n modelContent: { count: 1 },\n privateContent: {},\n });\n });\n\n it(\"should filter view context from initial state\", () => {\n type TestState = { count: number };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n });\n const windowState = {\n count: 5,\n [VIEW_CONTEXT_KEY]: \"context-value\",\n };\n OpenaiMock.widgetState = { modelContent: windowState };\n\n const store = createStore(storeCreator);\n\n expect(store.getState()).toEqual({ count: 5 });\n expect(\n (store.getState() as Record<string, unknown>)[VIEW_CONTEXT_KEY],\n ).toBeUndefined();\n });\n });\n\n describe(\"mcp-app mode\", () => {\n beforeEach(() => {\n vi.stubGlobal(\"openai\", undefined);\n vi.stubGlobal(\"skybridge\", { hostType: \"mcp-app\" });\n vi.stubGlobal(\"ResizeObserver\", MockResizeObserver);\n });\n\n afterEach(async () => {\n cleanup();\n HostAdaptor.resetInstance();\n McpAppBridge.resetInstance();\n });\n\n it(\"should initialize with null viewState\", () => {\n const adaptor = getAdaptor();\n const viewState = adaptor.getHostContextStore(\"viewState\").getSnapshot();\n\n expect(viewState).toBeNull();\n });\n\n it(\"should create a store with default state when no persisted state exists\", () => {\n type TestState = { count: number };\n const storeCreator: StateCreator<TestState, [], [], TestState> = () => ({\n count: 0,\n });\n\n const store = createStore(storeCreator);\n\n expect(store.getState()).toEqual({ count: 0 });\n });\n\n it(\"should update in-memory state via setViewState\", async () => {\n const adaptor = getAdaptor();\n vi.spyOn(adaptor, \"setViewState\").mockResolvedValue(undefined);\n\n type TestState = { count: number; increment: () => void };\n const storeCreator: StateCreator<TestState, [], [], TestState> = (\n set,\n ) => ({\n count: 0,\n increment: () => set((state) => ({ count: state.count + 1 })),\n });\n\n const store = createStore(storeCreator);\n store.getState().increment();\n\n await vi.waitFor(() => {\n expect(adaptor.setViewState).toHaveBeenCalledWith({ count: 1 });\n });\n });\n\n it(\"should notify listeners when view state changes\", async () => {\n const postMessageMock = getMcpAppHostPostMessageMock();\n vi.stubGlobal(\"parent\", { postMessage: postMessageMock });\n\n const adaptor = getAdaptor();\n const listener = vi.fn();\n\n adaptor.getHostContextStore(\"viewState\").subscribe(listener);\n await adaptor.setViewState({ count: 42 });\n\n expect(postMessageMock).toHaveBeenCalledWith(\n expect.objectContaining({ method: \"ui/update-model-context\" }),\n \"*\",\n );\n expect(listener).toHaveBeenCalled();\n expect(adaptor.getHostContextStore(\"viewState\").getSnapshot()).toEqual({\n count: 42,\n });\n });\n });\n});\n"]}
@@ -1,13 +1,16 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { cleanup, render } from "@testing-library/react";
3
3
  import { afterEach, beforeEach, describe, expect, it, vi, } from "vitest";
4
- import { McpAppAdaptor, McpAppBridge } from "./bridges/mcp-app/index.js";
4
+ import { HostAdaptor } from "./bridges/adaptor.js";
5
+ import { getAdaptor } from "./bridges/get-adaptor.js";
6
+ import { McpAppBridge } from "./bridges/mcp-app/index.js";
5
7
  import { DataLLM } from "./data-llm.js";
6
8
  import { getMcpAppHostPostMessageMock, MockResizeObserver, } from "./hooks/test/utils.js";
7
9
  describe("DataLLM", () => {
8
10
  afterEach(() => {
9
11
  // Clean up React components BEFORE unstubbing globals
10
12
  cleanup();
13
+ HostAdaptor.resetInstance();
11
14
  vi.unstubAllGlobals();
12
15
  vi.resetAllMocks();
13
16
  });
@@ -88,6 +91,7 @@ describe("DataLLM", () => {
88
91
  let postMessageMock;
89
92
  beforeEach(() => {
90
93
  vi.stubGlobal("skybridge", { hostType: "mcp-app" });
94
+ vi.stubGlobal("openai", undefined);
91
95
  vi.stubGlobal("ResizeObserver", MockResizeObserver);
92
96
  postMessageMock = getMcpAppHostPostMessageMock();
93
97
  vi.stubGlobal("parent", { postMessage: postMessageMock });
@@ -95,10 +99,10 @@ describe("DataLLM", () => {
95
99
  afterEach(() => {
96
100
  cleanup();
97
101
  McpAppBridge.resetInstance();
98
- McpAppAdaptor.resetInstance();
102
+ HostAdaptor.resetInstance();
99
103
  });
100
104
  it("should register a node and update view state via adaptor", async () => {
101
- const adaptor = McpAppAdaptor.getInstance();
105
+ const adaptor = getAdaptor();
102
106
  render(_jsx(DataLLM, { content: "Test content", children: _jsx("div", { children: "Child" }) }));
103
107
  await vi.waitFor(() => {
104
108
  const viewState = adaptor
@@ -108,7 +112,7 @@ describe("DataLLM", () => {
108
112
  });
109
113
  });
110
114
  it("should preserve existing view state when updating context", async () => {
111
- const adaptor = McpAppAdaptor.getInstance();
115
+ const adaptor = getAdaptor();
112
116
  await adaptor.setViewState({ existingKey: "existingValue" });
113
117
  render(_jsx(DataLLM, { content: "Test content", children: _jsx("div", { children: "Child" }) }));
114
118
  await vi.waitFor(() => {
@@ -120,7 +124,7 @@ describe("DataLLM", () => {
120
124
  });
121
125
  });
122
126
  it("should handle multiple DataLLM components sharing state through adaptor", async () => {
123
- const adaptor = McpAppAdaptor.getInstance();
127
+ const adaptor = getAdaptor();
124
128
  render(_jsxs(_Fragment, { children: [_jsx(DataLLM, { content: "First component", children: _jsx("div", { children: "First" }) }), _jsx(DataLLM, { content: "Second component", children: _jsx("div", { children: "Second" }) })] }));
125
129
  await vi.waitFor(() => {
126
130
  const viewState = adaptor