skybridge 0.0.0-dev.defd82e → 0.0.0-dev.df033f6

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 (321) hide show
  1. package/README.md +123 -124
  2. package/dist/cli/build-helpers.d.ts +7 -0
  3. package/dist/cli/build-helpers.js +82 -0
  4. package/dist/cli/build-helpers.js.map +1 -0
  5. package/dist/cli/build-helpers.test.js +64 -0
  6. package/dist/cli/build-helpers.test.js.map +1 -0
  7. package/dist/cli/detect-port.d.ts +2 -2
  8. package/dist/cli/detect-port.js +9 -20
  9. package/dist/cli/detect-port.js.map +1 -1
  10. package/dist/cli/header.js +1 -1
  11. package/dist/cli/header.js.map +1 -1
  12. package/dist/cli/resolve-views-dir.d.ts +1 -0
  13. package/dist/cli/resolve-views-dir.js +17 -0
  14. package/dist/cli/resolve-views-dir.js.map +1 -0
  15. package/dist/cli/run-command.js.map +1 -1
  16. package/dist/cli/telemetry.js.map +1 -1
  17. package/dist/cli/tunnel-control-server.d.ts +9 -0
  18. package/dist/cli/tunnel-control-server.js +31 -0
  19. package/dist/cli/tunnel-control-server.js.map +1 -0
  20. package/dist/cli/tunnel-control-server.test.js +39 -0
  21. package/dist/cli/tunnel-control-server.test.js.map +1 -0
  22. package/dist/cli/tunnel-handler.d.ts +3 -0
  23. package/dist/cli/tunnel-handler.js +48 -0
  24. package/dist/cli/tunnel-handler.js.map +1 -0
  25. package/dist/cli/tunnel-handler.test.js +105 -0
  26. package/dist/cli/tunnel-handler.test.js.map +1 -0
  27. package/dist/cli/tunnel.d.ts +57 -0
  28. package/dist/cli/tunnel.js +154 -0
  29. package/dist/cli/tunnel.js.map +1 -0
  30. package/dist/cli/tunnel.test.d.ts +1 -0
  31. package/dist/cli/tunnel.test.js +190 -0
  32. package/dist/cli/tunnel.test.js.map +1 -0
  33. package/dist/cli/types.js.map +1 -1
  34. package/dist/cli/use-execute-steps.js.map +1 -1
  35. package/dist/cli/use-messages.d.ts +3 -0
  36. package/dist/cli/use-messages.js +11 -0
  37. package/dist/cli/use-messages.js.map +1 -0
  38. package/dist/cli/use-nodemon.d.ts +2 -2
  39. package/dist/cli/use-nodemon.js +18 -25
  40. package/dist/cli/use-nodemon.js.map +1 -1
  41. package/dist/cli/use-open-browser.d.ts +1 -0
  42. package/dist/cli/use-open-browser.js +44 -0
  43. package/dist/cli/use-open-browser.js.map +1 -0
  44. package/dist/cli/use-tunnel.d.ts +13 -7
  45. package/dist/cli/use-tunnel.js +103 -73
  46. package/dist/cli/use-tunnel.js.map +1 -1
  47. package/dist/cli/use-typescript-check.d.ts +1 -0
  48. package/dist/cli/use-typescript-check.js +42 -7
  49. package/dist/cli/use-typescript-check.js.map +1 -1
  50. package/dist/commands/build.d.ts +0 -1
  51. package/dist/commands/build.js +52 -8
  52. package/dist/commands/build.js.map +1 -1
  53. package/dist/commands/create.d.ts +9 -0
  54. package/dist/commands/create.js +30 -0
  55. package/dist/commands/create.js.map +1 -0
  56. package/dist/commands/dev.d.ts +2 -0
  57. package/dist/commands/dev.js +58 -6
  58. package/dist/commands/dev.js.map +1 -1
  59. package/dist/commands/start.js +13 -10
  60. package/dist/commands/start.js.map +1 -1
  61. package/dist/commands/telemetry/disable.js.map +1 -1
  62. package/dist/commands/telemetry/enable.js.map +1 -1
  63. package/dist/commands/telemetry/status.js.map +1 -1
  64. package/dist/server/asset-base-url-transform-plugin.d.ts +1 -0
  65. package/dist/server/asset-base-url-transform-plugin.js +17 -2
  66. package/dist/server/asset-base-url-transform-plugin.js.map +1 -1
  67. package/dist/server/asset-base-url-transform-plugin.test.js +80 -1
  68. package/dist/server/asset-base-url-transform-plugin.test.js.map +1 -1
  69. package/dist/server/auth.d.ts +20 -0
  70. package/dist/server/auth.js +28 -0
  71. package/dist/server/auth.js.map +1 -0
  72. package/dist/server/build-manifest.test.d.ts +1 -0
  73. package/dist/server/build-manifest.test.js +27 -0
  74. package/dist/server/build-manifest.test.js.map +1 -0
  75. package/dist/server/content-helpers.d.ts +67 -0
  76. package/dist/server/content-helpers.js +79 -0
  77. package/dist/server/content-helpers.js.map +1 -0
  78. package/dist/server/content-helpers.test.d.ts +1 -0
  79. package/dist/server/content-helpers.test.js +70 -0
  80. package/dist/server/content-helpers.test.js.map +1 -0
  81. package/dist/server/express.d.ts +2 -6
  82. package/dist/server/express.js +34 -10
  83. package/dist/server/express.js.map +1 -1
  84. package/dist/server/express.test.js +310 -71
  85. package/dist/server/express.test.js.map +1 -1
  86. package/dist/server/file-ref.d.ts +28 -0
  87. package/dist/server/file-ref.js +27 -0
  88. package/dist/server/file-ref.js.map +1 -0
  89. package/dist/server/index.d.ts +6 -3
  90. package/dist/server/index.js +5 -2
  91. package/dist/server/index.js.map +1 -1
  92. package/dist/server/inferUtilityTypes.d.ts +6 -6
  93. package/dist/server/inferUtilityTypes.js.map +1 -1
  94. package/dist/server/metric.d.ts +14 -0
  95. package/dist/server/metric.js +62 -0
  96. package/dist/server/metric.js.map +1 -0
  97. package/dist/server/middleware.d.ts +16 -3
  98. package/dist/server/middleware.js.map +1 -1
  99. package/dist/server/middleware.test-d.js.map +1 -1
  100. package/dist/server/middleware.test.js +12 -9
  101. package/dist/server/middleware.test.js.map +1 -1
  102. package/dist/server/server.d.ts +323 -73
  103. package/dist/server/server.js +495 -127
  104. package/dist/server/server.js.map +1 -1
  105. package/dist/server/templateHelper.d.ts +5 -7
  106. package/dist/server/templateHelper.js +3 -22
  107. package/dist/server/templateHelper.js.map +1 -1
  108. package/dist/server/templates.generated.d.ts +4 -0
  109. package/dist/server/templates.generated.js +47 -0
  110. package/dist/server/templates.generated.js.map +1 -0
  111. package/dist/server/tunnel-proxy-router.d.ts +7 -0
  112. package/dist/server/tunnel-proxy-router.js +110 -0
  113. package/dist/server/tunnel-proxy-router.js.map +1 -0
  114. package/dist/server/tunnel-proxy-router.test.d.ts +1 -0
  115. package/dist/server/tunnel-proxy-router.test.js +229 -0
  116. package/dist/server/tunnel-proxy-router.test.js.map +1 -0
  117. package/dist/server/view-resource-resolution.test.d.ts +6 -0
  118. package/dist/server/view-resource-resolution.test.js +88 -0
  119. package/dist/server/view-resource-resolution.test.js.map +1 -0
  120. package/dist/server/viewsDevServer.d.ts +14 -0
  121. package/dist/server/viewsDevServer.js +45 -0
  122. package/dist/server/viewsDevServer.js.map +1 -0
  123. package/dist/test/utils.d.ts +13 -21
  124. package/dist/test/utils.js +42 -37
  125. package/dist/test/utils.js.map +1 -1
  126. package/dist/test/view.test.d.ts +1 -0
  127. package/dist/test/view.test.js +568 -0
  128. package/dist/test/view.test.js.map +1 -0
  129. package/dist/version.d.ts +1 -0
  130. package/dist/version.js +3 -0
  131. package/dist/version.js.map +1 -0
  132. package/dist/web/bridges/apps-sdk/adaptor.d.ts +11 -4
  133. package/dist/web/bridges/apps-sdk/adaptor.js +59 -17
  134. package/dist/web/bridges/apps-sdk/adaptor.js.map +1 -1
  135. package/dist/web/bridges/apps-sdk/bridge.d.ts +1 -0
  136. package/dist/web/bridges/apps-sdk/bridge.js +1 -0
  137. package/dist/web/bridges/apps-sdk/bridge.js.map +1 -1
  138. package/dist/web/bridges/apps-sdk/index.js.map +1 -1
  139. package/dist/web/bridges/apps-sdk/types.d.ts +18 -6
  140. package/dist/web/bridges/apps-sdk/types.js.map +1 -1
  141. package/dist/web/bridges/apps-sdk/use-apps-sdk-context.d.ts +11 -0
  142. package/dist/web/bridges/apps-sdk/use-apps-sdk-context.js +11 -0
  143. package/dist/web/bridges/apps-sdk/use-apps-sdk-context.js.map +1 -1
  144. package/dist/web/bridges/get-adaptor.d.ts +7 -0
  145. package/dist/web/bridges/get-adaptor.js +7 -0
  146. package/dist/web/bridges/get-adaptor.js.map +1 -1
  147. package/dist/web/bridges/index.js.map +1 -1
  148. package/dist/web/bridges/mcp-app/adaptor.d.ts +21 -6
  149. package/dist/web/bridges/mcp-app/adaptor.js +127 -28
  150. package/dist/web/bridges/mcp-app/adaptor.js.map +1 -1
  151. package/dist/web/bridges/mcp-app/bridge.d.ts +4 -2
  152. package/dist/web/bridges/mcp-app/bridge.js +23 -1
  153. package/dist/web/bridges/mcp-app/bridge.js.map +1 -1
  154. package/dist/web/bridges/mcp-app/index.js.map +1 -1
  155. package/dist/web/bridges/mcp-app/types.js.map +1 -1
  156. package/dist/web/bridges/mcp-app/use-mcp-app-context.d.ts +12 -0
  157. package/dist/web/bridges/mcp-app/use-mcp-app-context.js +12 -0
  158. package/dist/web/bridges/mcp-app/use-mcp-app-context.js.map +1 -1
  159. package/dist/web/bridges/mcp-app/use-mcp-app-context.test.js.map +1 -1
  160. package/dist/web/bridges/mcp-app/view-tools.test.d.ts +1 -0
  161. package/dist/web/bridges/mcp-app/view-tools.test.js +144 -0
  162. package/dist/web/bridges/mcp-app/view-tools.test.js.map +1 -0
  163. package/dist/web/bridges/types.d.ts +112 -11
  164. package/dist/web/bridges/types.js.map +1 -1
  165. package/dist/web/bridges/use-host-context.d.ts +5 -0
  166. package/dist/web/bridges/use-host-context.js +5 -0
  167. package/dist/web/bridges/use-host-context.js.map +1 -1
  168. package/dist/web/components/modal-provider.js +2 -2
  169. package/dist/web/components/modal-provider.js.map +1 -1
  170. package/dist/web/create-store.d.ts +26 -0
  171. package/dist/web/create-store.js +43 -3
  172. package/dist/web/create-store.js.map +1 -1
  173. package/dist/web/create-store.test.js +14 -16
  174. package/dist/web/create-store.test.js.map +1 -1
  175. package/dist/web/data-llm.d.ts +34 -1
  176. package/dist/web/data-llm.js +31 -3
  177. package/dist/web/data-llm.js.map +1 -1
  178. package/dist/web/data-llm.test.js +22 -22
  179. package/dist/web/data-llm.test.js.map +1 -1
  180. package/dist/web/generate-helpers.d.ts +22 -18
  181. package/dist/web/generate-helpers.js +22 -18
  182. package/dist/web/generate-helpers.js.map +1 -1
  183. package/dist/web/generate-helpers.test-d.js +30 -28
  184. package/dist/web/generate-helpers.test-d.js.map +1 -1
  185. package/dist/web/generate-helpers.test.js.map +1 -1
  186. package/dist/web/helpers/state.d.ts +2 -2
  187. package/dist/web/helpers/state.js +11 -11
  188. package/dist/web/helpers/state.js.map +1 -1
  189. package/dist/web/helpers/state.test.js +9 -9
  190. package/dist/web/helpers/state.test.js.map +1 -1
  191. package/dist/web/hooks/index.d.ts +5 -1
  192. package/dist/web/hooks/index.js +5 -1
  193. package/dist/web/hooks/index.js.map +1 -1
  194. package/dist/web/hooks/test/utils.d.ts +6 -2
  195. package/dist/web/hooks/test/utils.js +13 -2
  196. package/dist/web/hooks/test/utils.js.map +1 -1
  197. package/dist/web/hooks/use-call-tool.d.ts +45 -0
  198. package/dist/web/hooks/use-call-tool.js +28 -0
  199. package/dist/web/hooks/use-call-tool.js.map +1 -1
  200. package/dist/web/hooks/use-call-tool.test-d.js.map +1 -1
  201. package/dist/web/hooks/use-call-tool.test.js +27 -6
  202. package/dist/web/hooks/use-call-tool.test.js.map +1 -1
  203. package/dist/web/hooks/use-display-mode.d.ts +20 -0
  204. package/dist/web/hooks/use-display-mode.js +20 -0
  205. package/dist/web/hooks/use-display-mode.js.map +1 -1
  206. package/dist/web/hooks/use-display-mode.test-d.js.map +1 -1
  207. package/dist/web/hooks/use-display-mode.test.js.map +1 -1
  208. package/dist/web/hooks/use-download.d.ts +5 -0
  209. package/dist/web/hooks/use-download.js +8 -0
  210. package/dist/web/hooks/use-download.js.map +1 -0
  211. package/dist/web/hooks/use-download.test.d.ts +1 -0
  212. package/dist/web/hooks/use-download.test.js +95 -0
  213. package/dist/web/hooks/use-download.test.js.map +1 -0
  214. package/dist/web/hooks/use-files.d.ts +34 -1
  215. package/dist/web/hooks/use-files.js +33 -0
  216. package/dist/web/hooks/use-files.js.map +1 -1
  217. package/dist/web/hooks/use-files.test.js +22 -2
  218. package/dist/web/hooks/use-files.test.js.map +1 -1
  219. package/dist/web/hooks/use-layout.d.ts +2 -0
  220. package/dist/web/hooks/use-layout.js +2 -0
  221. package/dist/web/hooks/use-layout.js.map +1 -1
  222. package/dist/web/hooks/use-layout.test.js.map +1 -1
  223. package/dist/web/hooks/use-open-external.d.ts +17 -0
  224. package/dist/web/hooks/use-open-external.js +16 -0
  225. package/dist/web/hooks/use-open-external.js.map +1 -1
  226. package/dist/web/hooks/use-open-external.test.js.map +1 -1
  227. package/dist/web/hooks/use-register-view-tool.d.ts +38 -0
  228. package/dist/web/hooks/use-register-view-tool.js +50 -0
  229. package/dist/web/hooks/use-register-view-tool.js.map +1 -0
  230. package/dist/web/hooks/use-request-close.d.ts +16 -0
  231. package/dist/web/hooks/use-request-close.js +21 -0
  232. package/dist/web/hooks/use-request-close.js.map +1 -0
  233. package/dist/web/hooks/use-request-close.test.d.ts +1 -0
  234. package/dist/web/hooks/use-request-close.test.js +52 -0
  235. package/dist/web/hooks/use-request-close.test.js.map +1 -0
  236. package/dist/web/hooks/use-request-modal.d.ts +16 -1
  237. package/dist/web/hooks/use-request-modal.js +19 -4
  238. package/dist/web/hooks/use-request-modal.js.map +1 -1
  239. package/dist/web/hooks/use-request-modal.test.js +1 -1
  240. package/dist/web/hooks/use-request-modal.test.js.map +1 -1
  241. package/dist/web/hooks/use-request-size.d.ts +20 -0
  242. package/dist/web/hooks/use-request-size.js +24 -0
  243. package/dist/web/hooks/use-request-size.js.map +1 -0
  244. package/dist/web/hooks/use-request-size.test.d.ts +1 -0
  245. package/dist/web/hooks/use-request-size.test.js +65 -0
  246. package/dist/web/hooks/use-request-size.test.js.map +1 -0
  247. package/dist/web/hooks/use-send-follow-up-message.d.ts +19 -1
  248. package/dist/web/hooks/use-send-follow-up-message.js +19 -2
  249. package/dist/web/hooks/use-send-follow-up-message.js.map +1 -1
  250. package/dist/web/hooks/use-set-open-in-app-url.d.ts +17 -0
  251. package/dist/web/hooks/use-set-open-in-app-url.js +17 -0
  252. package/dist/web/hooks/use-set-open-in-app-url.js.map +1 -1
  253. package/dist/web/hooks/use-set-open-in-app-url.test.js.map +1 -1
  254. package/dist/web/hooks/use-tool-info.d.ts +53 -2
  255. package/dist/web/hooks/use-tool-info.js +30 -7
  256. package/dist/web/hooks/use-tool-info.js.map +1 -1
  257. package/dist/web/hooks/use-tool-info.test-d.js +11 -29
  258. package/dist/web/hooks/use-tool-info.test-d.js.map +1 -1
  259. package/dist/web/hooks/use-tool-info.test.js +5 -5
  260. package/dist/web/hooks/use-tool-info.test.js.map +1 -1
  261. package/dist/web/hooks/use-user.d.ts +2 -0
  262. package/dist/web/hooks/use-user.js +2 -0
  263. package/dist/web/hooks/use-user.js.map +1 -1
  264. package/dist/web/hooks/use-user.test.js.map +1 -1
  265. package/dist/web/hooks/use-view-state.d.ts +25 -0
  266. package/dist/web/hooks/use-view-state.js +32 -0
  267. package/dist/web/hooks/use-view-state.js.map +1 -0
  268. package/dist/web/hooks/use-view-state.test.d.ts +1 -0
  269. package/dist/web/hooks/use-view-state.test.js +177 -0
  270. package/dist/web/hooks/use-view-state.test.js.map +1 -0
  271. package/dist/web/index.d.ts +1 -2
  272. package/dist/web/index.js +1 -2
  273. package/dist/web/index.js.map +1 -1
  274. package/dist/web/mount-view.d.ts +20 -0
  275. package/dist/web/{mount-widget.js → mount-view.js} +21 -2
  276. package/dist/web/mount-view.js.map +1 -0
  277. package/dist/web/plugin/data-llm.test.js.map +1 -1
  278. package/dist/web/plugin/plugin.d.ts +32 -1
  279. package/dist/web/plugin/plugin.js +160 -25
  280. package/dist/web/plugin/plugin.js.map +1 -1
  281. package/dist/web/plugin/scan-views.d.ts +16 -0
  282. package/dist/web/plugin/scan-views.js +88 -0
  283. package/dist/web/plugin/scan-views.js.map +1 -0
  284. package/dist/web/plugin/scan-views.test.d.ts +1 -0
  285. package/dist/web/plugin/scan-views.test.js +99 -0
  286. package/dist/web/plugin/scan-views.test.js.map +1 -0
  287. package/dist/web/plugin/transform-data-llm.js.map +1 -1
  288. package/dist/web/plugin/transform-data-llm.test.js.map +1 -1
  289. package/dist/web/plugin/validate-view.d.ts +1 -0
  290. package/dist/web/plugin/validate-view.js +9 -0
  291. package/dist/web/plugin/validate-view.js.map +1 -0
  292. package/dist/web/plugin/validate-view.test.d.ts +1 -0
  293. package/dist/web/plugin/validate-view.test.js +24 -0
  294. package/dist/web/plugin/validate-view.test.js.map +1 -0
  295. package/dist/web/proxy.js.map +1 -1
  296. package/dist/web/types.d.ts +4 -0
  297. package/dist/web/types.js.map +1 -1
  298. package/package.json +25 -10
  299. package/tsconfig.base.json +2 -0
  300. package/dist/server/templates/development.hbs +0 -12
  301. package/dist/server/templates/production.hbs +0 -6
  302. package/dist/server/widgetsDevServer.d.ts +0 -13
  303. package/dist/server/widgetsDevServer.js +0 -52
  304. package/dist/server/widgetsDevServer.js.map +0 -1
  305. package/dist/test/widget.test.js +0 -263
  306. package/dist/test/widget.test.js.map +0 -1
  307. package/dist/web/hooks/use-widget-state.d.ts +0 -4
  308. package/dist/web/hooks/use-widget-state.js +0 -32
  309. package/dist/web/hooks/use-widget-state.js.map +0 -1
  310. package/dist/web/hooks/use-widget-state.test.js +0 -64
  311. package/dist/web/hooks/use-widget-state.test.js.map +0 -1
  312. package/dist/web/mount-widget.d.ts +0 -1
  313. package/dist/web/mount-widget.js.map +0 -1
  314. package/dist/web/plugin/validate-widget.d.ts +0 -5
  315. package/dist/web/plugin/validate-widget.js +0 -27
  316. package/dist/web/plugin/validate-widget.js.map +0 -1
  317. package/dist/web/plugin/validate-widget.test.js +0 -42
  318. package/dist/web/plugin/validate-widget.test.js.map +0 -1
  319. /package/dist/{test/widget.test.d.ts → cli/build-helpers.test.d.ts} +0 -0
  320. /package/dist/{web/hooks/use-widget-state.test.d.ts → cli/tunnel-control-server.test.d.ts} +0 -0
  321. /package/dist/{web/plugin/validate-widget.test.d.ts → cli/tunnel-handler.test.d.ts} +0 -0
@@ -2,9 +2,12 @@ import crypto from "node:crypto";
2
2
  import { readFileSync } from "node:fs";
3
3
  import http from "node:http";
4
4
  import path from "node:path";
5
- import { McpServer as McpServerBase, } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { Server as SdkServer, } from "@modelcontextprotocol/sdk/server/index.js";
6
+ import { McpServer as McpServerBase } from "@modelcontextprotocol/sdk/server/mcp.js";
6
7
  import { mergeWith, union } from "es-toolkit";
8
+ import express, {} from "express";
7
9
  import { createApp } from "./express.js";
10
+ import { createMiddlewareEntry } from "./metric.js";
8
11
  import { buildMiddlewareChain, getHandlerMaps } from "./middleware.js";
9
12
  import { templateHelper } from "./templateHelper.js";
10
13
  const mergeWithUnion = (target, source) => {
@@ -14,23 +17,134 @@ const mergeWithUnion = (target, source) => {
14
17
  }
15
18
  });
16
19
  };
17
- export class McpServer extends McpServerBase {
20
+ /**
21
+ * Drop the query string from a `ui://` view URI, leaving the bare path. The
22
+ * `?v=` cache key is the only query we append, so a plain split is enough and
23
+ * sidesteps `URL` normalization quirks on the non-special `ui:` scheme.
24
+ */
25
+ function stripQuery(uri) {
26
+ const queryIndex = uri.indexOf("?");
27
+ return queryIndex === -1 ? uri : uri.slice(0, queryIndex);
28
+ }
29
+ /**
30
+ * Coerce a tool handler's return value into an MCP `content` array. Strings
31
+ * become a single `TextContent`; a single block is wrapped in an array;
32
+ * `undefined` produces `[]`. Mostly used internally — exported so consumers
33
+ * who build content lazily can apply the same normalization.
34
+ */
35
+ export function normalizeContent(content) {
36
+ if (content === undefined) {
37
+ return [];
38
+ }
39
+ if (typeof content === "string") {
40
+ return [{ type: "text", text: content }];
41
+ }
42
+ if (Array.isArray(content)) {
43
+ return content;
44
+ }
45
+ return [content];
46
+ }
47
+ const McpServerBaseOmitted = McpServerBase;
48
+ /**
49
+ * The Skybridge server. Extends the MCP SDK's `McpServer` with a typed tool
50
+ * registry, view resources, an embedded Express app, and protocol-level
51
+ * middleware. Construct it with the same `Implementation` info you would pass
52
+ * to the SDK, chain {@link McpServer.registerTool} calls to declare tools,
53
+ * then call {@link McpServer.run} to start the HTTP server.
54
+ *
55
+ * The `TTools` generic accumulates each registered tool's input/output/meta
56
+ * shape, so `typeof server` carries enough information for view-side helpers
57
+ * like {@link generateHelpers} to produce fully-typed hooks.
58
+ *
59
+ * @typeParam TTools - Accumulated tool registry. Filled in by `registerTool`
60
+ * chaining; you almost never set this manually.
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * const server = new McpServer({ name: "my-app", version: "1.0.0" }, {})
65
+ * .registerTool({
66
+ * name: "search",
67
+ * inputSchema: { query: z.string() },
68
+ * view: { component: "search" },
69
+ * }, async ({ query }) => ({ content: `Results for ${query}` }));
70
+ *
71
+ * await server.run();
72
+ * export type AppType = typeof server;
73
+ * ```
74
+ *
75
+ * @see https://docs.skybridge.tech/api-reference/mcp-server
76
+ */
77
+ // Side channel populated by `dist/__entry.js` before user code is imported.
78
+ // Set at module scope rather than passed through the constructor because the
79
+ // wrapper has the manifest before the user's `new McpServer(...)` runs, and
80
+ // threading it through every call site (including user templates) is exactly
81
+ // the boilerplate this design is trying to hide.
82
+ let pendingBuildManifest = null;
83
+ /**
84
+ * Prime the build-time Vite manifest before user code constructs its
85
+ * `McpServer`. Called from the generated `dist/__entry.js`; not part of the
86
+ * user-facing API.
87
+ *
88
+ * @internal
89
+ */
90
+ export function __setBuildManifest(manifest) {
91
+ pendingBuildManifest = manifest;
92
+ }
93
+ export class McpServer extends McpServerBaseOmitted {
94
+ /**
95
+ * The underlying Express app. Use this to extend the HTTP server with
96
+ * custom routes, middleware, or settings — e.g.
97
+ * `server.express.get("/health", ...)`.
98
+ *
99
+ * `express.json()` is pre-applied — tune it via the constructor's third
100
+ * argument, e.g. `new McpServer(info, {}, { json: { limit: "10mb" } })`.
101
+ * Register your handlers before `run()`;
102
+ * after `run()`, dev-mode middleware, the `/mcp` route, and the default
103
+ * error handler are appended in that order.
104
+ *
105
+ * Note: Alpic Cloud only routes traffic to `/mcp` — custom routes work
106
+ * locally and on self-hosted deployments.
107
+ */
18
108
  express;
19
- customMiddleware = [];
20
109
  customErrorMiddleware = [];
21
110
  mcpMiddlewareEntries = [];
22
111
  mcpMiddlewareApplied = false;
112
+ claimedViews = new Map();
113
+ viewMetaBuilders = new Map();
114
+ /**
115
+ * Maps a view resource's query-less path to its canonical registered URI
116
+ * (the one carrying the `?v=` cache key). Lets `resources/read` resolve the
117
+ * underlying view no matter which version param the consumer sends, since
118
+ * the param is only a cache key, not part of the resource's identity.
119
+ */
120
+ viewUriByPath = new Map();
121
+ viteManifest = null;
122
+ serverInfo;
123
+ serverOptions;
124
+ constructor(serverInfo, options, skybridgeOptions) {
125
+ super(serverInfo, options);
126
+ this.serverInfo = serverInfo;
127
+ this.serverOptions = options;
128
+ this.express = express();
129
+ this.express.use(express.json(skybridgeOptions?.json));
130
+ // Pick up the manifest if `dist/__entry.js` primed it before importing
131
+ // user code. Consume-once: clear after the first construction so a
132
+ // subsequent test that doesn't prime can't inherit stale state.
133
+ // Explicit `setViteManifest` calls still win because they happen after
134
+ // construction.
135
+ if (pendingBuildManifest) {
136
+ this.setViteManifest(pendingBuildManifest);
137
+ pendingBuildManifest = null;
138
+ }
139
+ }
23
140
  use(pathOrHandler, ...handlers) {
141
+ // Branching is load-bearing: Express's `app.use` overloads can't be
142
+ // resolved against a `string | RequestHandler` union, so we narrow.
24
143
  if (typeof pathOrHandler === "string") {
25
- this.customMiddleware.push({
26
- path: pathOrHandler,
27
- handlers,
28
- });
144
+ this.express.use(pathOrHandler, ...handlers);
29
145
  }
30
146
  else {
31
- this.customMiddleware.push({
32
- handlers: [pathOrHandler, ...handlers],
33
- });
147
+ this.express.use(pathOrHandler, ...handlers);
34
148
  }
35
149
  return this;
36
150
  }
@@ -74,12 +188,73 @@ export class McpServer extends McpServerBase {
74
188
  return;
75
189
  }
76
190
  this.mcpMiddlewareApplied = true;
77
- if (this.mcpMiddlewareEntries.length === 0) {
191
+ // Surface view-resource _meta on `resources/list` (per ext-apps spec:
192
+ // hosts/checkers read CSP & domain at list time before fetching content).
193
+ const viewListMetaEntry = {
194
+ filter: "resources/list",
195
+ handler: async (_req, extra, next) => {
196
+ const result = (await next());
197
+ for (const resource of result.resources) {
198
+ const builder = this.viewMetaBuilders.get(resource.uri);
199
+ if (!builder) {
200
+ continue;
201
+ }
202
+ const meta = builder(extra);
203
+ resource._meta = {
204
+ ...(resource._meta ?? {}),
205
+ ...meta,
206
+ };
207
+ }
208
+ return result;
209
+ },
210
+ };
211
+ // Resolve a view's `resources/read` by its query-less path so the
212
+ // underlying asset is served no matter the `?v=` value (stale cache key,
213
+ // no param, etc.). The version param is a cache-busting hint for external
214
+ // consumers; it must not gate resolution. We rewrite the lookup URI to the
215
+ // canonical registered one, then restore the requested URI on the response
216
+ // so the consumer-facing URI is never rewritten.
217
+ const viewReadResolveEntry = {
218
+ filter: "resources/read",
219
+ handler: async (req, _extra, next) => {
220
+ const requested = req.params.uri;
221
+ if (typeof requested !== "string") {
222
+ return next();
223
+ }
224
+ const path = stripQuery(requested);
225
+ const canonical = this.viewUriByPath.get(path);
226
+ if (!canonical) {
227
+ return next();
228
+ }
229
+ req.params.uri = canonical;
230
+ try {
231
+ const result = (await next());
232
+ for (const content of result.contents ?? []) {
233
+ if (typeof content.uri === "string" &&
234
+ stripQuery(content.uri) === path) {
235
+ content.uri = requested;
236
+ }
237
+ }
238
+ return result;
239
+ }
240
+ finally {
241
+ // Restore the shared request params so middleware outer to us never
242
+ // observes the rewritten lookup URI after next() unwinds.
243
+ req.params.uri = requested;
244
+ }
245
+ },
246
+ };
247
+ const monitoringEntry = createMiddlewareEntry();
248
+ const entries = [
249
+ ...(monitoringEntry ? [monitoringEntry] : []),
250
+ viewListMetaEntry,
251
+ viewReadResolveEntry,
252
+ ...this.mcpMiddlewareEntries,
253
+ ];
254
+ if (entries.length === 0) {
78
255
  return;
79
256
  }
80
257
  const { requestHandlers, notificationHandlers } = getHandlerMaps(this.server);
81
- const entries = this.mcpMiddlewareEntries;
82
- // Wrap existing handlers and proxy future .set() for lazy SDK registration
83
258
  const instrumentMap = (map, isNotification) => {
84
259
  for (const [method, handler] of map) {
85
260
  map.set(method, buildMiddlewareChain(method, isNotification, handler, entries));
@@ -90,199 +265,392 @@ export class McpServer extends McpServerBase {
90
265
  instrumentMap(requestHandlers, false);
91
266
  instrumentMap(notificationHandlers, true);
92
267
  }
268
+ /**
269
+ * Connect to an MCP transport (override of the SDK's `connect`). Use this
270
+ * when you're embedding Skybridge in a host that already manages its own
271
+ * transport (e.g. stdio for desktop apps); for HTTP, prefer {@link McpServer.run}
272
+ * which sets the transport up for you. Locks in any middleware registered
273
+ * via {@link McpServer.mcpMiddleware} — further calls to that method will
274
+ * throw afterwards.
275
+ */
93
276
  async connect(transport) {
94
277
  this.applyMcpMiddleware();
95
- return super.connect(transport);
278
+ return McpServerBase.prototype.connect.call(this, transport);
279
+ }
280
+ /**
281
+ * Per-request stateless connect. The SDK's `Protocol` only allows one
282
+ * transport per instance, so we can't reuse this `McpServer` across
283
+ * concurrent requests. The SDK's idiomatic fix is a `() => McpServer`
284
+ * factory, but that would break Skybridge's singleton API — so instead
285
+ * we build a fresh underlying `Server` per request and share the main
286
+ * server's handler maps by reference. The cast is unavoidable: there's
287
+ * no public API to inject handler maps. `getHandlerMaps` validates the
288
+ * read side and fails fast on SDK field renames.
289
+ */
290
+ async connectStatelessTransport(transport) {
291
+ this.applyMcpMiddleware();
292
+ const { requestHandlers, notificationHandlers } = getHandlerMaps(this.server);
293
+ const fresh = new SdkServer(this.serverInfo, this.serverOptions);
294
+ const target = fresh;
295
+ target._requestHandlers = requestHandlers;
296
+ target._notificationHandlers = notificationHandlers;
297
+ await fresh.connect(transport);
96
298
  }
299
+ /**
300
+ * Start the HTTP server. Listens on `process.env.__PORT` (default `3000`),
301
+ * mounts the `/mcp` route, applies any custom Express middleware registered
302
+ * via {@link McpServer.use} / {@link McpServer.useOnError}, and locks in
303
+ * any MCP middleware registered via {@link McpServer.mcpMiddleware}.
304
+ *
305
+ * On Cloudflare Workers / workerd, returns an object exposing `fetch` so
306
+ * the runtime can bridge incoming requests to the Node HTTP server. On
307
+ * Vercel (`VERCEL === "1"`), returns the Express app directly so the
308
+ * serverless function entry can call it as a `(req, res)` handler. On
309
+ * Node, returns `undefined` once listening.
310
+ */
97
311
  async run() {
98
312
  this.applyMcpMiddleware();
99
- const httpServer = http.createServer();
100
- if (!this.express) {
101
- this.express = await createApp({
313
+ if (process.env.VERCEL === "1") {
314
+ // createApp only reads httpServer inside its dev-only branch
315
+ // (viewsDevServer); under VERCEL=1 + NODE_ENV=production it's a
316
+ // bare object passed to satisfy the required parameter.
317
+ const httpServer = http.createServer();
318
+ await createApp({
102
319
  mcpServer: this,
103
320
  httpServer,
104
- customMiddleware: this.customMiddleware,
105
321
  errorMiddleware: this.customErrorMiddleware,
106
322
  });
323
+ return this.express;
107
324
  }
325
+ const httpServer = http.createServer();
326
+ await createApp({
327
+ mcpServer: this,
328
+ httpServer,
329
+ errorMiddleware: this.customErrorMiddleware,
330
+ });
108
331
  httpServer.on("request", this.express);
109
- return new Promise((resolve, reject) => {
332
+ const port = parseInt(process.env.__PORT ?? "3000", 10);
333
+ await new Promise((resolve, reject) => {
110
334
  httpServer.on("error", (error) => {
111
335
  console.error("Failed to start server:", error);
112
336
  reject(error);
113
337
  });
114
- const port = parseInt(process.env.__PORT ?? "3000", 10);
115
338
  httpServer.listen(port, () => {
116
339
  resolve();
117
340
  });
118
341
  });
342
+ // On workerd, bridge the Node http server to a Workers fetch handler.
343
+ // The specifier is held in a variable to sidestep tsc's module resolution
344
+ // (`cloudflare:node` only exists under wrangler/workerd).
345
+ if (typeof navigator !== "undefined" &&
346
+ navigator.userAgent === "Cloudflare-Workers") {
347
+ const cloudflareNode = "cloudflare:node";
348
+ const { httpServerHandler } = await import(cloudflareNode);
349
+ return httpServerHandler({ port });
350
+ }
351
+ const shutdown = () => {
352
+ // Drop both handlers so a second signal falls through to Node's default
353
+ // (force-quit on a second Ctrl+C while drain is hanging).
354
+ process.off("SIGTERM", shutdown);
355
+ process.off("SIGINT", shutdown);
356
+ httpServer.close(() => process.exit(0));
357
+ // Force exit if connections don't drain in time so the port is still
358
+ // released promptly (e.g. for nodemon restarts).
359
+ setTimeout(() => process.exit(0), 3000).unref();
360
+ };
361
+ process.on("SIGTERM", shutdown);
362
+ process.on("SIGINT", shutdown);
363
+ return undefined;
119
364
  }
120
- registerWidget(name, resourceConfig, toolConfig, toolCallback) {
121
- const userMeta = resourceConfig._meta;
122
- const toolMeta = {
123
- ...toolConfig._meta,
365
+ enforceOneToolPerView(component, toolName) {
366
+ const existingTool = this.claimedViews.get(component);
367
+ if (existingTool) {
368
+ throw new Error(`skybridge: view "${component}" is already used by tool "${existingTool}". Tool "${toolName}" cannot also reference it — each view backs exactly one tool.`);
369
+ }
370
+ this.claimedViews.set(component, toolName);
371
+ }
372
+ resolveViewRequestContext(extra) {
373
+ const isProduction = process.env.NODE_ENV === "production";
374
+ const headers = extra?.requestInfo?.headers || {};
375
+ const header = (key) => {
376
+ const val = headers[key];
377
+ return Array.isArray(val) ? val[0] : val;
124
378
  };
125
- if (!resourceConfig.hosts || resourceConfig.hosts.includes("apps-sdk")) {
126
- const widgetConfig = {
379
+ const isClaude = header("user-agent") === "Claude-User";
380
+ let serverUrl;
381
+ const forwardedHost = header("x-forwarded-host");
382
+ const origin = header("origin");
383
+ const host = header("host");
384
+ if (forwardedHost) {
385
+ const proto = header("x-forwarded-proto") || "https";
386
+ serverUrl = `${proto}://${forwardedHost}`;
387
+ }
388
+ else if (origin) {
389
+ serverUrl = origin;
390
+ }
391
+ else if (host) {
392
+ const proto = ["127.0.0.1:", "localhost:"].some((p) => host.startsWith(p))
393
+ ? "http"
394
+ : "https";
395
+ serverUrl = `${proto}://${host}`;
396
+ }
397
+ else {
398
+ const devPort = process.env.__PORT || "3000";
399
+ serverUrl = `http://localhost:${devPort}`;
400
+ }
401
+ const connectDomains = [serverUrl];
402
+ if (!isProduction) {
403
+ const wsUrl = new URL(serverUrl);
404
+ wsUrl.protocol = wsUrl.protocol === "https:" ? "wss:" : "ws:";
405
+ connectDomains.push(wsUrl.origin);
406
+ }
407
+ let contentMetaOverrides = {};
408
+ if (isClaude) {
409
+ const pathname = extra?.requestInfo?.url?.pathname ?? "";
410
+ const rawUrl = header("x-alpic-forwarded-url") ?? `${serverUrl}${pathname}`;
411
+ // Strip a lone trailing slash so the hash matches the connector URL
412
+ // as registered with Claude (which has no trailing slash on bare origins).
413
+ const url = rawUrl.endsWith("/") ? rawUrl.slice(0, -1) : rawUrl;
414
+ const hash = crypto
415
+ .createHash("sha256")
416
+ .update(url)
417
+ .digest("hex")
418
+ .slice(0, 32);
419
+ contentMetaOverrides = { domain: `${hash}.claudemcpcontent.com` };
420
+ }
421
+ return { serverUrl, connectDomains, contentMetaOverrides };
422
+ }
423
+ registerViewResources(toolName, view, toolMeta) {
424
+ const hosts = view.hosts ?? ["apps-sdk", "mcp-app"];
425
+ // Append a content-derived version param so hosts (e.g. ChatGPT) bust
426
+ // their cache when the bundle changes, but keep the URI stable across
427
+ // `tools/list` calls when the bundle hasn't changed.
428
+ const versionParam = this.computeViewVersionParam(view.component);
429
+ if (hosts.includes("apps-sdk")) {
430
+ const viewResource = {
127
431
  hostType: "apps-sdk",
128
- uri: `ui://widgets/apps-sdk/${name}.html`,
432
+ uri: `ui://views/apps-sdk/${view.component}.html${versionParam}`,
129
433
  mimeType: "text/html+skybridge",
130
434
  buildContentMeta: ({ resourceDomains, connectDomains, domain }, overrides) => {
131
- const userUi = userMeta?.ui;
132
- const userCsp = userUi?.csp;
133
435
  const defaults = {
134
436
  "openai/widgetCSP": {
135
437
  resource_domains: resourceDomains,
136
438
  connect_domains: connectDomains,
137
439
  },
138
440
  "openai/widgetDomain": domain,
139
- "openai/widgetDescription": resourceConfig.description,
441
+ "openai/widgetDescription": view.description,
140
442
  };
141
- const fromUi = {
443
+ const fromView = {
142
444
  "openai/widgetCSP": {
143
- resource_domains: userCsp?.resourceDomains,
144
- connect_domains: userCsp?.connectDomains,
145
- frame_domains: userCsp?.frameDomains,
146
- redirect_domains: userCsp?.redirectDomains,
445
+ resource_domains: view.csp?.resourceDomains,
446
+ connect_domains: view.csp?.connectDomains,
447
+ frame_domains: view.csp?.frameDomains,
448
+ redirect_domains: view.csp?.redirectDomains,
147
449
  },
148
- "openai/widgetDomain": userUi?.domain,
149
- "openai/widgetPrefersBorder": userUi?.prefersBorder,
450
+ "openai/widgetDomain": view.domain,
451
+ "openai/widgetPrefersBorder": view.prefersBorder,
150
452
  };
151
- const directOpenaiKeys = Object.fromEntries(Object.entries(userMeta ?? {}).filter(([key]) => key.startsWith("openai/")));
152
- return mergeWithUnion(mergeWithUnion(mergeWithUnion(defaults, fromUi), directOpenaiKeys), { "openai/widgetDomain": overrides.domain });
453
+ const base = mergeWithUnion(mergeWithUnion(defaults, fromView), {
454
+ "openai/widgetDomain": overrides.domain,
455
+ });
456
+ if (view._meta) {
457
+ return { ...base, ...view._meta };
458
+ }
459
+ return base;
153
460
  },
154
461
  };
155
- this.registerWidgetResource({
156
- name,
157
- widgetConfig,
158
- resourceConfig,
462
+ this.registerViewResource({
463
+ name: toolName,
464
+ viewResource,
465
+ view,
159
466
  });
160
- toolMeta["openai/outputTemplate"] = widgetConfig.uri;
467
+ toolMeta["openai/outputTemplate"] = viewResource.uri;
161
468
  }
162
- if (!resourceConfig.hosts || resourceConfig.hosts.includes("mcp-app")) {
163
- const widgetConfig = {
469
+ if (hosts.includes("mcp-app")) {
470
+ const viewResource = {
164
471
  hostType: "mcp-app",
165
- uri: `ui://widgets/ext-apps/${name}.html`,
472
+ uri: `ui://views/ext-apps/${view.component}.html${versionParam}`,
166
473
  mimeType: "text/html;profile=mcp-app",
167
- buildContentMeta: ({ resourceDomains, connectDomains, domain }, overrides) => {
474
+ buildContentMeta: ({ resourceDomains, connectDomains, domain, baseUriDomains }, overrides) => {
168
475
  const defaults = {
169
476
  ui: {
170
477
  csp: {
171
478
  resourceDomains,
172
479
  connectDomains,
480
+ baseUriDomains,
173
481
  },
174
482
  domain,
175
483
  },
176
484
  };
177
- return mergeWithUnion(defaults, {
178
- ui: { ...userMeta?.ui, ...overrides },
485
+ const fromView = {
486
+ ui: {
487
+ ...(view.description && { description: view.description }),
488
+ ...(view.prefersBorder !== undefined && {
489
+ prefersBorder: view.prefersBorder,
490
+ }),
491
+ ...(view.domain && { domain: view.domain }),
492
+ csp: {
493
+ ...(view.csp?.resourceDomains && {
494
+ resourceDomains: view.csp.resourceDomains,
495
+ }),
496
+ ...(view.csp?.connectDomains && {
497
+ connectDomains: view.csp.connectDomains,
498
+ }),
499
+ ...(view.csp?.frameDomains && {
500
+ frameDomains: view.csp.frameDomains,
501
+ }),
502
+ ...(view.csp?.baseUriDomains && {
503
+ baseUriDomains: view.csp.baseUriDomains,
504
+ }),
505
+ ...(view.csp?.redirectDomains && {
506
+ redirectDomains: view.csp.redirectDomains,
507
+ }),
508
+ },
509
+ },
510
+ };
511
+ const base = mergeWithUnion(mergeWithUnion(defaults, fromView), {
512
+ ui: overrides,
179
513
  });
514
+ if (view._meta) {
515
+ return { ...base, ...view._meta };
516
+ }
517
+ return base;
180
518
  },
181
519
  };
182
- this.registerWidgetResource({
183
- name,
184
- widgetConfig,
185
- resourceConfig,
520
+ this.registerViewResource({
521
+ name: toolName,
522
+ viewResource,
523
+ view,
186
524
  });
187
525
  // @ts-expect-error - For backwards compatibility with Claude current implementation of the specs
188
- toolMeta["ui/resourceUri"] = widgetConfig.uri;
189
- toolMeta.ui = { resourceUri: widgetConfig.uri };
526
+ toolMeta["ui/resourceUri"] = viewResource.uri;
527
+ toolMeta.ui = { ...toolMeta.ui, resourceUri: viewResource.uri };
190
528
  }
191
- this.registerTool(name, {
192
- ...toolConfig,
193
- _meta: toolMeta,
194
- }, toolCallback);
195
- return this;
196
529
  }
197
- registerTool(name, config, cb) {
198
- super.registerTool(name, config, cb);
199
- return this;
200
- }
201
- registerWidgetResource({ name, widgetConfig, resourceConfig, }) {
202
- const { hostType, uri: widgetUri, mimeType, buildContentMeta, } = widgetConfig;
203
- this.registerResource(name, widgetUri, { ...resourceConfig, _meta: resourceConfig._meta }, async (uri, extra) => {
530
+ registerViewResource({ name, viewResource, view, }) {
531
+ const { hostType, uri: viewUri, mimeType, buildContentMeta } = viewResource;
532
+ const buildMeta = (extra) => {
533
+ const { serverUrl, connectDomains, contentMetaOverrides } = this.resolveViewRequestContext(extra);
534
+ return buildContentMeta({
535
+ resourceDomains: [serverUrl],
536
+ connectDomains,
537
+ domain: serverUrl,
538
+ baseUriDomains: [serverUrl],
539
+ }, contentMetaOverrides);
540
+ };
541
+ this.viewMetaBuilders.set(viewUri, buildMeta);
542
+ this.viewUriByPath.set(stripQuery(viewUri), viewUri);
543
+ this.registerResource(name, viewUri, { description: view.description }, async (uri, extra) => {
204
544
  const isProduction = process.env.NODE_ENV === "production";
205
- const isClaude = extra?.requestInfo?.headers?.["user-agent"] === "Claude-User";
206
- const headers = extra?.requestInfo?.headers || {};
207
- const header = (key) => {
208
- const val = headers[key];
209
- return Array.isArray(val) ? val[0] : val;
210
- };
211
- let serverUrl;
212
- const forwardedHost = header("x-forwarded-host");
213
- const origin = header("origin");
214
- const host = header("host");
215
- if (forwardedHost) {
216
- const proto = header("x-forwarded-proto") || "https";
217
- serverUrl = `${proto}://${forwardedHost}`;
218
- }
219
- else if (origin) {
220
- serverUrl = origin;
221
- }
222
- else if (host) {
223
- const proto = ["127.0.0.1:", "localhost:"].some((p) => host.startsWith(p))
224
- ? "http"
225
- : "https";
226
- serverUrl = `${proto}://${host}`;
227
- }
228
- else {
229
- const devPort = process.env.__PORT || "3000";
230
- serverUrl = `http://localhost:${devPort}`;
231
- }
545
+ const { serverUrl } = this.resolveViewRequestContext(extra);
232
546
  const html = isProduction
233
547
  ? templateHelper.renderProduction({
234
548
  hostType,
235
549
  serverUrl,
236
- widgetFile: this.lookupDistFileWithIndexFallback(`src/widgets/${name}`),
237
- styleFile: this.lookupDistFile("style.css"),
550
+ viewFile: this.lookupViewFile(view.component),
551
+ styleFile: this.lookupDistFile("style.css") ?? "",
238
552
  })
239
553
  : templateHelper.renderDevelopment({
240
554
  hostType,
241
555
  serverUrl,
242
- widgetName: name,
556
+ viewName: view.component,
243
557
  });
244
- const connectDomains = [serverUrl];
245
- if (!isProduction) {
246
- const wsUrl = new URL(serverUrl);
247
- wsUrl.protocol = wsUrl.protocol === "https:" ? "wss:" : "ws:";
248
- connectDomains.push(wsUrl.origin);
249
- }
250
- let contentMetaOverrides = {};
251
- if (isClaude) {
252
- const pathname = extra?.requestInfo?.url?.pathname ?? "";
253
- const url = `${serverUrl}${pathname}`;
254
- const hash = crypto
255
- .createHash("sha256")
256
- .update(url)
257
- .digest("hex")
258
- .slice(0, 32);
259
- contentMetaOverrides = { domain: `${hash}.claudemcpcontent.com` };
260
- }
261
- const contentMeta = buildContentMeta({
262
- resourceDomains: [serverUrl],
263
- connectDomains,
264
- domain: serverUrl,
265
- baseUriDomains: [serverUrl],
266
- }, contentMetaOverrides);
267
558
  return {
268
559
  contents: [
269
- { uri: uri.href, mimeType, text: html, _meta: contentMeta },
560
+ { uri: uri.href, mimeType, text: html, _meta: buildMeta(extra) },
270
561
  ],
271
562
  };
272
563
  });
273
564
  }
565
+ wrapHandler(cb, { attachViewUUID }) {
566
+ return async (args, extra) => {
567
+ const result = await cb(args, extra);
568
+ return {
569
+ ...result,
570
+ content: normalizeContent(result.content),
571
+ ...(attachViewUUID && {
572
+ _meta: {
573
+ ...result._meta,
574
+ viewUUID: crypto.randomUUID(),
575
+ },
576
+ }),
577
+ };
578
+ };
579
+ }
580
+ computeViewVersionParam(viewName) {
581
+ if (process.env.NODE_ENV !== "production") {
582
+ return "";
583
+ }
584
+ try {
585
+ const viewFile = this.lookupViewFile(viewName);
586
+ const styleFile = this.lookupDistFile("style.css") ?? "";
587
+ const hash = crypto
588
+ .createHash("sha256")
589
+ .update(viewFile)
590
+ .update("\0")
591
+ .update(styleFile)
592
+ .digest("hex")
593
+ .slice(0, 8);
594
+ return `?v=${hash}`;
595
+ }
596
+ catch {
597
+ return "";
598
+ }
599
+ }
600
+ lookupViewFile(viewName) {
601
+ const manifest = this.readManifest();
602
+ for (const entry of Object.values(manifest)) {
603
+ if (entry?.isEntry && entry.name === viewName && entry.file) {
604
+ return entry.file;
605
+ }
606
+ }
607
+ throw new Error(`View "${viewName}" not found in Vite manifest. Did the build complete successfully? Look for an entry with name "${viewName}" in dist/assets/.vite/manifest.json.`);
608
+ }
274
609
  lookupDistFile(key) {
275
610
  const manifest = this.readManifest();
276
611
  return manifest[key]?.file;
277
612
  }
278
- lookupDistFileWithIndexFallback(basePath) {
279
- const manifest = this.readManifest();
280
- const flatFileKey = `${basePath}.tsx`;
281
- const indexFileKey = `${basePath}/index.tsx`;
282
- return manifest[flatFileKey]?.file ?? manifest[indexFileKey]?.file;
613
+ /**
614
+ * Inject the Vite manifest as a value rather than letting `readManifest()`
615
+ * load it from disk. Required for runtimes without a usable filesystem
616
+ * (Cloudflare Workers, etc.) — the user's `skybridge build` emits the
617
+ * manifest as a JS module which the entry imports and passes here.
618
+ */
619
+ setViteManifest(manifest) {
620
+ this.viteManifest = manifest;
621
+ return this;
283
622
  }
284
623
  readManifest() {
624
+ if (this.viteManifest) {
625
+ return this.viteManifest;
626
+ }
285
627
  return JSON.parse(readFileSync(path.join(process.cwd(), "dist", "assets", ".vite", "manifest.json"), "utf-8"));
286
628
  }
629
+ registerTool(...args) {
630
+ const baseFn = McpServerBase.prototype.registerTool;
631
+ if (typeof args[0] === "string") {
632
+ baseFn.call(this, args[0], args[1], args[2]);
633
+ return this;
634
+ }
635
+ const config = args[0];
636
+ const cb = args[1];
637
+ const { name, view, securitySchemes, _meta: userToolMeta, ...toolFields } = config;
638
+ const toolMeta = { ...userToolMeta };
639
+ if (securitySchemes) {
640
+ // SEP-1488 puts `securitySchemes` at the top level of the tool
641
+ // descriptor, but the SDK's `registerTool` drops unknown top-level
642
+ // fields, so the canonical spot isn't reachable without intercepting
643
+ // `tools/list`. Use the `_meta` back-compat mirror documented in the
644
+ // Apps SDK reference until SEP-1488 lands in the spec.
645
+ toolMeta.securitySchemes = securitySchemes;
646
+ }
647
+ if (view) {
648
+ this.enforceOneToolPerView(view.component, name);
649
+ this.registerViewResources(name, view, toolMeta);
650
+ }
651
+ const wrappedCb = this.wrapHandler(cb, { attachViewUUID: Boolean(view) });
652
+ baseFn.call(this, name, { ...toolFields, _meta: toolMeta }, wrappedCb);
653
+ return this;
654
+ }
287
655
  }
288
656
  //# sourceMappingURL=server.js.map