@herbertgao/pi-extensions 2026.9.17 → 2026.9.18

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 (266) hide show
  1. package/README.md +14 -15
  2. package/node_modules/@herbertgao/pi-bark/package.json +2 -2
  3. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +4 -1
  4. package/node_modules/@herbertgao/pi-cc-extensions/README.md +4 -1
  5. package/node_modules/@herbertgao/pi-cc-extensions/package.json +75 -75
  6. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +6 -0
  7. package/node_modules/@herbertgao/pi-subagents/package.json +7 -7
  8. package/node_modules/@herbertgao/resume-from/package.json +4 -2
  9. package/node_modules/@herbertgao/sol-pi/package.json +6 -6
  10. package/node_modules/@juicesharp/rpiv-ask-user-question/package.json +99 -99
  11. package/node_modules/@pi-plugins/fast-mode/package.json +1 -1
  12. package/node_modules/@tifan/pi-handoff/package.json +1 -1
  13. package/node_modules/@tifan/pi-handoff/src/index.ts +56 -26
  14. package/node_modules/@tifan/pi-mermaid-open/package.json +1 -1
  15. package/node_modules/@tifan/pi-preferred-thinking/package.json +1 -1
  16. package/node_modules/@tifan/pi-recap/package.json +1 -1
  17. package/node_modules/@tifan/pi-rename/package.json +1 -1
  18. package/node_modules/pi-antigravity/package.json +2 -2
  19. package/node_modules/pi-lens/package.json +158 -158
  20. package/node_modules/pi-multi-account/package.json +2 -2
  21. package/node_modules/pi-typesafe/README.md +1 -1
  22. package/node_modules/pi-typesafe/dist/auth.d.ts +9 -5
  23. package/node_modules/pi-typesafe/dist/auth.js +7 -3
  24. package/node_modules/pi-typesafe/dist/backends.d.ts +33 -3
  25. package/node_modules/pi-typesafe/dist/backends.js +95 -1
  26. package/node_modules/pi-typesafe/dist/client.d.ts +5 -5
  27. package/node_modules/pi-typesafe/dist/client.js +12 -9
  28. package/node_modules/pi-typesafe/dist/credentials.d.ts +14 -8
  29. package/node_modules/pi-typesafe/dist/credentials.js +10 -7
  30. package/node_modules/pi-typesafe/dist/errors.d.ts +2 -2
  31. package/node_modules/pi-typesafe/dist/index.d.ts +2 -2
  32. package/node_modules/pi-typesafe/dist/index.js +1 -1
  33. package/node_modules/pi-typesafe/dist/login.d.ts +2 -2
  34. package/node_modules/pi-typesafe/dist/login.js +2 -2
  35. package/node_modules/pi-typesafe/package.json +5 -5
  36. package/node_modules/pi-web-access/package.json +2 -2
  37. package/node_modules/remote-pi/package.json +5 -1
  38. package/package.json +16 -28
  39. package/node_modules/pi-mcp-adapter/CHANGELOG.md +0 -1013
  40. package/node_modules/pi-mcp-adapter/LICENSE +0 -21
  41. package/node_modules/pi-mcp-adapter/OAUTH.md +0 -369
  42. package/node_modules/pi-mcp-adapter/README.md +0 -1021
  43. package/node_modules/pi-mcp-adapter/abort.ts +0 -34
  44. package/node_modules/pi-mcp-adapter/agent-dir.ts +0 -68
  45. package/node_modules/pi-mcp-adapter/agent-plugin-loader.ts +0 -416
  46. package/node_modules/pi-mcp-adapter/agent-plugin-provenance.ts +0 -36
  47. package/node_modules/pi-mcp-adapter/app-bridge.bundle.js +0 -67
  48. package/node_modules/pi-mcp-adapter/banner.png +0 -0
  49. package/node_modules/pi-mcp-adapter/bearer-command-resolver.ts +0 -193
  50. package/node_modules/pi-mcp-adapter/claude-plugin-loader.ts +0 -365
  51. package/node_modules/pi-mcp-adapter/cli.js +0 -454
  52. package/node_modules/pi-mcp-adapter/commands.ts +0 -861
  53. package/node_modules/pi-mcp-adapter/config.ts +0 -1565
  54. package/node_modules/pi-mcp-adapter/consent-manager.ts +0 -95
  55. package/node_modules/pi-mcp-adapter/direct-tool-surface.ts +0 -244
  56. package/node_modules/pi-mcp-adapter/direct-tools.ts +0 -428
  57. package/node_modules/pi-mcp-adapter/dist/abort.d.ts +0 -2
  58. package/node_modules/pi-mcp-adapter/dist/abort.js +0 -36
  59. package/node_modules/pi-mcp-adapter/dist/abort.js.map +0 -1
  60. package/node_modules/pi-mcp-adapter/dist/agent-dir.d.ts +0 -10
  61. package/node_modules/pi-mcp-adapter/dist/agent-dir.js +0 -63
  62. package/node_modules/pi-mcp-adapter/dist/agent-dir.js.map +0 -1
  63. package/node_modules/pi-mcp-adapter/dist/agent-plugin-loader.d.ts +0 -8
  64. package/node_modules/pi-mcp-adapter/dist/agent-plugin-loader.js +0 -398
  65. package/node_modules/pi-mcp-adapter/dist/agent-plugin-loader.js.map +0 -1
  66. package/node_modules/pi-mcp-adapter/dist/agent-plugin-provenance.d.ts +0 -1
  67. package/node_modules/pi-mcp-adapter/dist/agent-plugin-provenance.js +0 -31
  68. package/node_modules/pi-mcp-adapter/dist/agent-plugin-provenance.js.map +0 -1
  69. package/node_modules/pi-mcp-adapter/dist/bearer-command-resolver.d.ts +0 -6
  70. package/node_modules/pi-mcp-adapter/dist/bearer-command-resolver.js +0 -194
  71. package/node_modules/pi-mcp-adapter/dist/bearer-command-resolver.js.map +0 -1
  72. package/node_modules/pi-mcp-adapter/dist/claude-plugin-loader.d.ts +0 -9
  73. package/node_modules/pi-mcp-adapter/dist/claude-plugin-loader.js +0 -362
  74. package/node_modules/pi-mcp-adapter/dist/claude-plugin-loader.js.map +0 -1
  75. package/node_modules/pi-mcp-adapter/dist/config.d.ts +0 -134
  76. package/node_modules/pi-mcp-adapter/dist/config.js +0 -1361
  77. package/node_modules/pi-mcp-adapter/dist/config.js.map +0 -1
  78. package/node_modules/pi-mcp-adapter/dist/consent-manager.d.ts +0 -18
  79. package/node_modules/pi-mcp-adapter/dist/consent-manager.js +0 -88
  80. package/node_modules/pi-mcp-adapter/dist/consent-manager.js.map +0 -1
  81. package/node_modules/pi-mcp-adapter/dist/elicitation-handler.d.ts +0 -17
  82. package/node_modules/pi-mcp-adapter/dist/elicitation-handler.js +0 -316
  83. package/node_modules/pi-mcp-adapter/dist/elicitation-handler.js.map +0 -1
  84. package/node_modules/pi-mcp-adapter/dist/errors.d.ts +0 -131
  85. package/node_modules/pi-mcp-adapter/dist/errors.js +0 -278
  86. package/node_modules/pi-mcp-adapter/dist/errors.js.map +0 -1
  87. package/node_modules/pi-mcp-adapter/dist/http-ca.d.ts +0 -8
  88. package/node_modules/pi-mcp-adapter/dist/http-ca.js +0 -88
  89. package/node_modules/pi-mcp-adapter/dist/http-ca.js.map +0 -1
  90. package/node_modules/pi-mcp-adapter/dist/jev-client.d.ts +0 -14
  91. package/node_modules/pi-mcp-adapter/dist/jev-client.js +0 -367
  92. package/node_modules/pi-mcp-adapter/dist/jev-client.js.map +0 -1
  93. package/node_modules/pi-mcp-adapter/dist/jev-contracts.d.ts +0 -77
  94. package/node_modules/pi-mcp-adapter/dist/jev-contracts.js +0 -2
  95. package/node_modules/pi-mcp-adapter/dist/jev-contracts.js.map +0 -1
  96. package/node_modules/pi-mcp-adapter/dist/jev-key-store.d.ts +0 -51
  97. package/node_modules/pi-mcp-adapter/dist/jev-key-store.js +0 -205
  98. package/node_modules/pi-mcp-adapter/dist/jev-key-store.js.map +0 -1
  99. package/node_modules/pi-mcp-adapter/dist/json-schema-validator.d.ts +0 -2
  100. package/node_modules/pi-mcp-adapter/dist/json-schema-validator.js +0 -68
  101. package/node_modules/pi-mcp-adapter/dist/json-schema-validator.js.map +0 -1
  102. package/node_modules/pi-mcp-adapter/dist/lifecycle.d.ts +0 -56
  103. package/node_modules/pi-mcp-adapter/dist/lifecycle.js +0 -410
  104. package/node_modules/pi-mcp-adapter/dist/lifecycle.js.map +0 -1
  105. package/node_modules/pi-mcp-adapter/dist/logger.d.ts +0 -51
  106. package/node_modules/pi-mcp-adapter/dist/logger.js +0 -131
  107. package/node_modules/pi-mcp-adapter/dist/logger.js.map +0 -1
  108. package/node_modules/pi-mcp-adapter/dist/mcp-auth-fetch.d.ts +0 -26
  109. package/node_modules/pi-mcp-adapter/dist/mcp-auth-fetch.js +0 -103
  110. package/node_modules/pi-mcp-adapter/dist/mcp-auth-fetch.js.map +0 -1
  111. package/node_modules/pi-mcp-adapter/dist/mcp-auth-flow.d.ts +0 -118
  112. package/node_modules/pi-mcp-adapter/dist/mcp-auth-flow.js +0 -1097
  113. package/node_modules/pi-mcp-adapter/dist/mcp-auth-flow.js.map +0 -1
  114. package/node_modules/pi-mcp-adapter/dist/mcp-auth.d.ts +0 -170
  115. package/node_modules/pi-mcp-adapter/dist/mcp-auth.js +0 -1142
  116. package/node_modules/pi-mcp-adapter/dist/mcp-auth.js.map +0 -1
  117. package/node_modules/pi-mcp-adapter/dist/mcp-bearer-store.d.ts +0 -24
  118. package/node_modules/pi-mcp-adapter/dist/mcp-bearer-store.js +0 -203
  119. package/node_modules/pi-mcp-adapter/dist/mcp-bearer-store.js.map +0 -1
  120. package/node_modules/pi-mcp-adapter/dist/mcp-callback-server.d.ts +0 -53
  121. package/node_modules/pi-mcp-adapter/dist/mcp-callback-server.js +0 -441
  122. package/node_modules/pi-mcp-adapter/dist/mcp-callback-server.js.map +0 -1
  123. package/node_modules/pi-mcp-adapter/dist/mcp-oauth-provider.d.ts +0 -148
  124. package/node_modules/pi-mcp-adapter/dist/mcp-oauth-provider.js +0 -689
  125. package/node_modules/pi-mcp-adapter/dist/mcp-oauth-provider.js.map +0 -1
  126. package/node_modules/pi-mcp-adapter/dist/mcp-probe.d.ts +0 -6
  127. package/node_modules/pi-mcp-adapter/dist/mcp-probe.js +0 -166
  128. package/node_modules/pi-mcp-adapter/dist/mcp-probe.js.map +0 -1
  129. package/node_modules/pi-mcp-adapter/dist/mcp-tasks.d.ts +0 -102
  130. package/node_modules/pi-mcp-adapter/dist/mcp-tasks.js +0 -369
  131. package/node_modules/pi-mcp-adapter/dist/mcp-tasks.js.map +0 -1
  132. package/node_modules/pi-mcp-adapter/dist/mcp-trace.d.ts +0 -95
  133. package/node_modules/pi-mcp-adapter/dist/mcp-trace.js +0 -242
  134. package/node_modules/pi-mcp-adapter/dist/mcp-trace.js.map +0 -1
  135. package/node_modules/pi-mcp-adapter/dist/metadata-cache.d.ts +0 -19
  136. package/node_modules/pi-mcp-adapter/dist/metadata-cache.js +0 -301
  137. package/node_modules/pi-mcp-adapter/dist/metadata-cache.js.map +0 -1
  138. package/node_modules/pi-mcp-adapter/dist/npx-resolver.d.ts +0 -6
  139. package/node_modules/pi-mcp-adapter/dist/npx-resolver.js +0 -505
  140. package/node_modules/pi-mcp-adapter/dist/npx-resolver.js.map +0 -1
  141. package/node_modules/pi-mcp-adapter/dist/package-mcp-loader.d.ts +0 -2
  142. package/node_modules/pi-mcp-adapter/dist/package-mcp-loader.js +0 -144
  143. package/node_modules/pi-mcp-adapter/dist/package-mcp-loader.js.map +0 -1
  144. package/node_modules/pi-mcp-adapter/dist/request-headers-command.d.ts +0 -10
  145. package/node_modules/pi-mcp-adapter/dist/request-headers-command.js +0 -312
  146. package/node_modules/pi-mcp-adapter/dist/request-headers-command.js.map +0 -1
  147. package/node_modules/pi-mcp-adapter/dist/resource-tools.d.ts +0 -1
  148. package/node_modules/pi-mcp-adapter/dist/resource-tools.js +0 -15
  149. package/node_modules/pi-mcp-adapter/dist/resource-tools.js.map +0 -1
  150. package/node_modules/pi-mcp-adapter/dist/runtime-owner.d.ts +0 -13
  151. package/node_modules/pi-mcp-adapter/dist/runtime-owner.js +0 -97
  152. package/node_modules/pi-mcp-adapter/dist/runtime-owner.js.map +0 -1
  153. package/node_modules/pi-mcp-adapter/dist/sampling-handler.d.ts +0 -17
  154. package/node_modules/pi-mcp-adapter/dist/sampling-handler.js +0 -203
  155. package/node_modules/pi-mcp-adapter/dist/sampling-handler.js.map +0 -1
  156. package/node_modules/pi-mcp-adapter/dist/secure-keyring.d.ts +0 -11
  157. package/node_modules/pi-mcp-adapter/dist/secure-keyring.js +0 -172
  158. package/node_modules/pi-mcp-adapter/dist/secure-keyring.js.map +0 -1
  159. package/node_modules/pi-mcp-adapter/dist/server-manager.d.ts +0 -157
  160. package/node_modules/pi-mcp-adapter/dist/server-manager.js +0 -1745
  161. package/node_modules/pi-mcp-adapter/dist/server-manager.js.map +0 -1
  162. package/node_modules/pi-mcp-adapter/dist/session-approvals.d.ts +0 -34
  163. package/node_modules/pi-mcp-adapter/dist/session-approvals.js +0 -140
  164. package/node_modules/pi-mcp-adapter/dist/session-approvals.js.map +0 -1
  165. package/node_modules/pi-mcp-adapter/dist/session-recovery.d.ts +0 -26
  166. package/node_modules/pi-mcp-adapter/dist/session-recovery.js +0 -142
  167. package/node_modules/pi-mcp-adapter/dist/session-recovery.js.map +0 -1
  168. package/node_modules/pi-mcp-adapter/dist/state.d.ts +0 -73
  169. package/node_modules/pi-mcp-adapter/dist/state.js +0 -2
  170. package/node_modules/pi-mcp-adapter/dist/state.js.map +0 -1
  171. package/node_modules/pi-mcp-adapter/dist/types.d.ts +0 -642
  172. package/node_modules/pi-mcp-adapter/dist/types.js +0 -331
  173. package/node_modules/pi-mcp-adapter/dist/types.js.map +0 -1
  174. package/node_modules/pi-mcp-adapter/dist/ui-app-bridge-helpers.d.ts +0 -6
  175. package/node_modules/pi-mcp-adapter/dist/ui-app-bridge-helpers.js +0 -37
  176. package/node_modules/pi-mcp-adapter/dist/ui-app-bridge-helpers.js.map +0 -1
  177. package/node_modules/pi-mcp-adapter/dist/ui-resource-handler.d.ts +0 -17
  178. package/node_modules/pi-mcp-adapter/dist/ui-resource-handler.js +0 -219
  179. package/node_modules/pi-mcp-adapter/dist/ui-resource-handler.js.map +0 -1
  180. package/node_modules/pi-mcp-adapter/dist/ui-stream-types.d.ts +0 -104
  181. package/node_modules/pi-mcp-adapter/dist/ui-stream-types.js +0 -59
  182. package/node_modules/pi-mcp-adapter/dist/ui-stream-types.js.map +0 -1
  183. package/node_modules/pi-mcp-adapter/dist/ui-tool-visibility.d.ts +0 -4
  184. package/node_modules/pi-mcp-adapter/dist/ui-tool-visibility.js +0 -27
  185. package/node_modules/pi-mcp-adapter/dist/ui-tool-visibility.js.map +0 -1
  186. package/node_modules/pi-mcp-adapter/dist/unix-socket-transport.d.ts +0 -15
  187. package/node_modules/pi-mcp-adapter/dist/unix-socket-transport.js +0 -85
  188. package/node_modules/pi-mcp-adapter/dist/unix-socket-transport.js.map +0 -1
  189. package/node_modules/pi-mcp-adapter/dist/utils.d.ts +0 -41
  190. package/node_modules/pi-mcp-adapter/dist/utils.js +0 -417
  191. package/node_modules/pi-mcp-adapter/dist/utils.js.map +0 -1
  192. package/node_modules/pi-mcp-adapter/elicitation-handler.ts +0 -358
  193. package/node_modules/pi-mcp-adapter/error-signal.ts +0 -32
  194. package/node_modules/pi-mcp-adapter/errors.ts +0 -364
  195. package/node_modules/pi-mcp-adapter/examples/jev-accessibility-loop.mjs +0 -85
  196. package/node_modules/pi-mcp-adapter/examples/jev-semantic-filter.mjs +0 -34
  197. package/node_modules/pi-mcp-adapter/failure-backoff.ts +0 -23
  198. package/node_modules/pi-mcp-adapter/glimpse-ui.ts +0 -80
  199. package/node_modules/pi-mcp-adapter/host-html-template.ts +0 -515
  200. package/node_modules/pi-mcp-adapter/http-ca.ts +0 -84
  201. package/node_modules/pi-mcp-adapter/index.ts +0 -2106
  202. package/node_modules/pi-mcp-adapter/init.ts +0 -721
  203. package/node_modules/pi-mcp-adapter/jev-client.ts +0 -300
  204. package/node_modules/pi-mcp-adapter/jev-contracts.ts +0 -53
  205. package/node_modules/pi-mcp-adapter/jev-key-store.ts +0 -192
  206. package/node_modules/pi-mcp-adapter/json-schema-validator.ts +0 -83
  207. package/node_modules/pi-mcp-adapter/lazy-loader.ts +0 -7
  208. package/node_modules/pi-mcp-adapter/lifecycle.ts +0 -457
  209. package/node_modules/pi-mcp-adapter/logger.ts +0 -169
  210. package/node_modules/pi-mcp-adapter/mcp-auth-fetch.ts +0 -113
  211. package/node_modules/pi-mcp-adapter/mcp-auth-flow.ts +0 -1296
  212. package/node_modules/pi-mcp-adapter/mcp-auth.ts +0 -1287
  213. package/node_modules/pi-mcp-adapter/mcp-bearer-store.ts +0 -250
  214. package/node_modules/pi-mcp-adapter/mcp-callback-server.ts +0 -534
  215. package/node_modules/pi-mcp-adapter/mcp-code.ts +0 -495
  216. package/node_modules/pi-mcp-adapter/mcp-install.ts +0 -60
  217. package/node_modules/pi-mcp-adapter/mcp-keyring-helper.cjs +0 -89
  218. package/node_modules/pi-mcp-adapter/mcp-oauth-provider.ts +0 -819
  219. package/node_modules/pi-mcp-adapter/mcp-output-guard.ts +0 -511
  220. package/node_modules/pi-mcp-adapter/mcp-panel-theme.ts +0 -104
  221. package/node_modules/pi-mcp-adapter/mcp-panel.ts +0 -1099
  222. package/node_modules/pi-mcp-adapter/mcp-probe.ts +0 -201
  223. package/node_modules/pi-mcp-adapter/mcp-references.ts +0 -373
  224. package/node_modules/pi-mcp-adapter/mcp-script-worker.mjs +0 -137
  225. package/node_modules/pi-mcp-adapter/mcp-setup-panel.ts +0 -747
  226. package/node_modules/pi-mcp-adapter/mcp-status.ts +0 -105
  227. package/node_modules/pi-mcp-adapter/mcp-tasks.ts +0 -467
  228. package/node_modules/pi-mcp-adapter/mcp-trace.ts +0 -306
  229. package/node_modules/pi-mcp-adapter/metadata-cache.ts +0 -362
  230. package/node_modules/pi-mcp-adapter/namespace-tools.ts +0 -334
  231. package/node_modules/pi-mcp-adapter/npx-resolver.ts +0 -543
  232. package/node_modules/pi-mcp-adapter/oauth-handler.ts +0 -30
  233. package/node_modules/pi-mcp-adapter/oauth.ts +0 -52
  234. package/node_modules/pi-mcp-adapter/onboarding-state.ts +0 -76
  235. package/node_modules/pi-mcp-adapter/package-mcp-loader.ts +0 -156
  236. package/node_modules/pi-mcp-adapter/package.json +0 -219
  237. package/node_modules/pi-mcp-adapter/panel-keys.ts +0 -53
  238. package/node_modules/pi-mcp-adapter/prompts.ts +0 -385
  239. package/node_modules/pi-mcp-adapter/proxy-modes.ts +0 -1735
  240. package/node_modules/pi-mcp-adapter/request-headers-command.ts +0 -333
  241. package/node_modules/pi-mcp-adapter/resource-tools.ts +0 -17
  242. package/node_modules/pi-mcp-adapter/runtime-owner.ts +0 -106
  243. package/node_modules/pi-mcp-adapter/sampling-handler.ts +0 -261
  244. package/node_modules/pi-mcp-adapter/sandbox-proxy-template.ts +0 -144
  245. package/node_modules/pi-mcp-adapter/search-ranking.ts +0 -309
  246. package/node_modules/pi-mcp-adapter/secure-keyring.ts +0 -170
  247. package/node_modules/pi-mcp-adapter/semantic-search.ts +0 -186
  248. package/node_modules/pi-mcp-adapter/server-manager.ts +0 -2088
  249. package/node_modules/pi-mcp-adapter/session-approvals.ts +0 -201
  250. package/node_modules/pi-mcp-adapter/session-recovery.ts +0 -158
  251. package/node_modules/pi-mcp-adapter/skills/mcp-scripting/SKILL.md +0 -49
  252. package/node_modules/pi-mcp-adapter/state.ts +0 -71
  253. package/node_modules/pi-mcp-adapter/tool-approval.ts +0 -205
  254. package/node_modules/pi-mcp-adapter/tool-metadata.ts +0 -302
  255. package/node_modules/pi-mcp-adapter/tool-registrar.ts +0 -255
  256. package/node_modules/pi-mcp-adapter/tool-result-renderer.ts +0 -573
  257. package/node_modules/pi-mcp-adapter/ts-shape.ts +0 -149
  258. package/node_modules/pi-mcp-adapter/types.ts +0 -1120
  259. package/node_modules/pi-mcp-adapter/ui-app-bridge-helpers.ts +0 -40
  260. package/node_modules/pi-mcp-adapter/ui-resource-handler.ts +0 -266
  261. package/node_modules/pi-mcp-adapter/ui-server.ts +0 -993
  262. package/node_modules/pi-mcp-adapter/ui-session.ts +0 -624
  263. package/node_modules/pi-mcp-adapter/ui-stream-types.ts +0 -89
  264. package/node_modules/pi-mcp-adapter/ui-tool-visibility.ts +0 -25
  265. package/node_modules/pi-mcp-adapter/unix-socket-transport.ts +0 -85
  266. package/node_modules/pi-mcp-adapter/utils.ts +0 -464
@@ -1,515 +0,0 @@
1
- import type { UiHostContext, UiResourceContent, UiResourceCsp } from "./types.ts";
2
-
3
- // Use locally bundled AppBridge to avoid CDN Zod bundling issues
4
- const DEFAULT_APP_BRIDGE_MODULE_URL = "/app-bridge.bundle.js";
5
- const APP_SANDBOX = "allow-scripts allow-forms allow-modals allow-popups allow-downloads";
6
- const APP_PROXY_SANDBOX = `${APP_SANDBOX} allow-same-origin`;
7
- const APP_INNER_SANDBOX = APP_PROXY_SANDBOX;
8
-
9
- export interface HostHtmlTemplateInput {
10
- sessionToken: string;
11
- serverName: string;
12
- toolName: string;
13
- toolArgs: Record<string, unknown>;
14
- resource: UiResourceContent;
15
- allowAttribute: string;
16
- requireToolConsent: boolean;
17
- cacheToolConsent: boolean;
18
- hostContext?: UiHostContext;
19
- appBridgeModuleUrl?: string;
20
- sandboxProxyUrl: string;
21
- }
22
-
23
- export function buildHostHtmlTemplate(input: HostHtmlTemplateInput): string {
24
- const hostContext = input.hostContext ?? {};
25
-
26
- const sessionToken = safeInlineJSON(input.sessionToken);
27
- const toolArgs = safeInlineJSON(input.toolArgs);
28
- const serverName = safeInlineJSON(input.serverName);
29
- const toolName = safeInlineJSON(input.toolName);
30
- const hostContextJson = safeInlineJSON(hostContext);
31
- const allowAttribute = safeInlineJSON(input.allowAttribute);
32
- const requireToolConsent = safeInlineJSON(input.requireToolConsent);
33
- const cacheToolConsent = safeInlineJSON(input.cacheToolConsent);
34
- const moduleUrl = safeInlineJSON(input.appBridgeModuleUrl ?? DEFAULT_APP_BRIDGE_MODULE_URL);
35
- const sandboxProxyUrl = safeInlineJSON(input.sandboxProxyUrl);
36
- const resourceCsp = safeInlineJSON(input.resource.meta.csp);
37
- const resourcePermissions = safeInlineJSON(input.resource.meta.permissions);
38
-
39
- return `<!doctype html>
40
- <html lang="en">
41
- <head>
42
- <meta charset="utf-8" />
43
- <meta name="viewport" content="width=device-width, initial-scale=1" />
44
- <title>MCP UI - ${escapeHtml(input.serverName)} / ${escapeHtml(input.toolName)}</title>
45
- <style>
46
- :root {
47
- color-scheme: light dark;
48
- --bg: #0f1115;
49
- --surface: #181c22;
50
- --text: #ecf0f5;
51
- --muted: #a9b2bf;
52
- --accent: #43c0ff;
53
- --border: rgba(255, 255, 255, 0.12);
54
- --good: #34d399;
55
- --warn: #fbbf24;
56
- --bad: #f87171;
57
- }
58
- @media (prefers-color-scheme: light) {
59
- :root {
60
- --bg: #f6f7fb;
61
- --surface: #ffffff;
62
- --text: #1d2939;
63
- --muted: #667085;
64
- --accent: #0ea5e9;
65
- --border: rgba(15, 23, 42, 0.14);
66
- --good: #059669;
67
- --warn: #b45309;
68
- --bad: #b91c1c;
69
- }
70
- }
71
- * { box-sizing: border-box; }
72
- html, body { margin: 0; padding: 0; height: 100%; font-family: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: var(--bg); color: var(--text); }
73
- body { display: flex; flex-direction: column; min-height: 100vh; min-height: 100dvh; }
74
- header { background: var(--surface); border-bottom: 1px solid var(--border); padding: calc(10px + env(safe-area-inset-top, 0px)) calc(14px + env(safe-area-inset-right, 0px)) 10px calc(14px + env(safe-area-inset-left, 0px)); display: flex; align-items: center; justify-content: space-between; gap: 10px; }
75
- .title { display: flex; gap: 8px; align-items: baseline; min-width: 0; }
76
- .server { font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.08em; white-space: nowrap; }
77
- .tool { font-size: 14px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
78
- .badge { border: 1px solid var(--border); border-radius: 999px; padding: 2px 8px; font-size: 11px; color: var(--muted); white-space: nowrap; }
79
- .controls { display: flex; gap: 8px; align-items: center; }
80
- .status { font-size: 12px; color: var(--muted); white-space: nowrap; }
81
- button { border: 1px solid var(--border); background: transparent; color: var(--text); border-radius: 8px; padding: 6px 10px; cursor: pointer; font-size: 12px; }
82
- button.primary { border-color: color-mix(in srgb, var(--good) 40%, var(--border) 60%); color: var(--good); }
83
- button.danger { border-color: color-mix(in srgb, var(--bad) 40%, var(--border) 60%); color: var(--bad); }
84
- button:hover { background: color-mix(in srgb, var(--surface) 75%, var(--accent) 25%); }
85
- main { flex: 1; min-height: 0; padding: 10px; padding-inline: calc(10px + env(safe-area-inset-left, 0px)) calc(10px + env(safe-area-inset-right, 0px)); padding-bottom: calc(10px + env(safe-area-inset-bottom, 0px)); display: flex; }
86
- iframe { width: 100%; height: 100%; border: 1px solid var(--border); border-radius: 10px; background: white; }
87
- .overlay { position: fixed; inset: 0; background: color-mix(in srgb, var(--bg) 90%, black 10%); display: none; align-items: center; justify-content: center; z-index: 2; padding: 16px; }
88
- .overlay.visible { display: flex; }
89
- .panel { width: min(680px, calc(100vw - 40px)); background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 18px; }
90
- .panel h2 { margin: 0 0 8px; font-size: 16px; }
91
- .panel p { margin: 0; color: var(--muted); line-height: 1.4; font-size: 14px; white-space: pre-wrap; }
92
- @media (max-width: 640px) {
93
- header { align-items: stretch; flex-direction: column; gap: 8px; }
94
- .title { flex-wrap: wrap; row-gap: 4px; }
95
- .server { flex-basis: 100%; }
96
- .controls { width: 100%; }
97
- .status { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
98
- button { min-height: 44px; padding: 10px 14px; }
99
- main { padding: 6px; padding-inline: calc(6px + env(safe-area-inset-left, 0px)) calc(6px + env(safe-area-inset-right, 0px)); padding-bottom: calc(6px + env(safe-area-inset-bottom, 0px)); }
100
- iframe { border-radius: 6px; }
101
- .panel { width: 100%; }
102
- }
103
- </style>
104
- </head>
105
- <body>
106
- <header>
107
- <div class="title">
108
- <span class="server">MCP · <span id="server-name"></span></span>
109
- <span class="tool" id="tool-name"></span>
110
- <span class="badge">Sandboxed</span>
111
- </div>
112
- <div class="controls">
113
- <span class="status" id="status">Loading UI...</span>
114
- <button class="primary" id="done-btn" title="Cmd/Ctrl+Enter">Done</button>
115
- <button class="danger" id="cancel-btn" title="Escape">Cancel</button>
116
- </div>
117
- </header>
118
- <main>
119
- <iframe id="mcp-app" sandbox="${APP_PROXY_SANDBOX}" referrerpolicy="no-referrer"></iframe>
120
- </main>
121
- <div class="overlay" id="error-overlay">
122
- <div class="panel">
123
- <h2>UI Error</h2>
124
- <p id="error-message"></p>
125
- </div>
126
- </div>
127
- <div class="overlay" id="completion-overlay">
128
- <div class="panel">
129
- <h2>Done</h2>
130
- <p>MCP UI session finished. You can close this page and return to Pi.</p>
131
- </div>
132
- </div>
133
- <script type="module">
134
- import { AppBridge, PostMessageTransport } from ${moduleUrl};
135
-
136
- const SESSION_TOKEN = ${sessionToken};
137
- const SERVER_NAME = ${serverName};
138
- const TOOL_NAME = ${toolName};
139
- const TOOL_ARGS = ${toolArgs};
140
- const HOST_CONTEXT = ${hostContextJson};
141
- const ALLOW_ATTRIBUTE = ${allowAttribute};
142
- const REQUIRE_TOOL_CONSENT = ${requireToolConsent};
143
- const CACHE_TOOL_CONSENT = ${cacheToolConsent};
144
- const SANDBOX_PROXY_URL = ${sandboxProxyUrl};
145
- const RESOURCE_CSP = ${resourceCsp};
146
- const RESOURCE_PERMISSIONS = ${resourcePermissions};
147
- const INNER_SANDBOX = ${safeInlineJSON(APP_INNER_SANDBOX)};
148
- const STREAM_CONTEXT_KEY = "pi-mcp-adapter/stream";
149
- const STREAM_PATCH_METHOD = "notifications/pi-mcp-adapter/ui-result-patch";
150
-
151
- const iframe = document.getElementById("mcp-app");
152
- const statusNode = document.getElementById("status");
153
- const doneBtn = document.getElementById("done-btn");
154
- const cancelBtn = document.getElementById("cancel-btn");
155
- const errorOverlay = document.getElementById("error-overlay");
156
- const completionOverlay = document.getElementById("completion-overlay");
157
- const errorMessage = document.getElementById("error-message");
158
- const sandboxProxyOrigin = new URL(SANDBOX_PROXY_URL).origin;
159
-
160
- document.getElementById("server-name").textContent = SERVER_NAME;
161
- document.getElementById("tool-name").textContent = TOOL_NAME;
162
-
163
- const setStatus = (text, isError = false) => {
164
- statusNode.textContent = text;
165
- statusNode.style.color = isError ? "var(--bad)" : "var(--muted)";
166
- };
167
-
168
- const showError = (message) => {
169
- errorMessage.textContent = message;
170
- errorOverlay.classList.add("visible");
171
- setStatus("Error", true);
172
- };
173
-
174
- let completionPending = false;
175
- const showCompletion = () => {
176
- completionOverlay.classList.add("visible");
177
- setStatus("Complete");
178
- };
179
- const closeOrShowDone = () => {
180
- completionPending = true;
181
- window.close();
182
- setTimeout(() => {
183
- if (!document.hidden) {
184
- showCompletion();
185
- }
186
- }, 1000);
187
- };
188
- document.addEventListener("visibilitychange", () => {
189
- if (completionPending && !document.hidden) {
190
- showCompletion();
191
- }
192
- });
193
-
194
- const post = async (endpoint, params) => {
195
- const response = await fetch(endpoint, {
196
- method: "POST",
197
- headers: { "Content-Type": "application/json" },
198
- body: JSON.stringify({ token: SESSION_TOKEN, params }),
199
- });
200
-
201
- const body = await response.json().catch(() => ({ ok: false, error: "Invalid JSON response" }));
202
- if (!response.ok || !body.ok) {
203
- const message = body.error || ("HTTP " + response.status);
204
- throw new Error(message);
205
- }
206
- return body.result ?? {};
207
- };
208
-
209
- let consentGranted = !REQUIRE_TOOL_CONSENT;
210
- const initialStreamContext = HOST_CONTEXT?.[STREAM_CONTEXT_KEY];
211
- const streamMode = initialStreamContext?.mode === "stream-first" ? "stream-first" : "eager";
212
-
213
- const bridge = new AppBridge(
214
- null,
215
- { name: "pi", version: "1.0.0" },
216
- {
217
- serverTools: {},
218
- openLinks: {},
219
- logging: {},
220
- updateModelContext: {},
221
- message: {},
222
- sandbox: {
223
- ...(RESOURCE_CSP ? { csp: RESOURCE_CSP } : {}),
224
- ...(RESOURCE_PERMISSIONS ? { permissions: RESOURCE_PERMISSIONS } : {}),
225
- },
226
- },
227
- { hostContext: HOST_CONTEXT }
228
- );
229
-
230
- let sandboxResourceSent = false;
231
- bridge.onsandboxready = () => {
232
- if (sandboxResourceSent) return;
233
- sandboxResourceSent = true;
234
- void bridge.sendSandboxResourceReady({
235
- // The proxy performs a normal HTTP navigation to its session-bound
236
- // resource route. Provider HTML never crosses this trusted document.
237
- html: "",
238
- sandbox: INNER_SANDBOX,
239
- ...(RESOURCE_CSP ? { csp: RESOURCE_CSP } : {}),
240
- ...(RESOURCE_PERMISSIONS ? { permissions: RESOURCE_PERMISSIONS } : {}),
241
- }).catch((error) => {
242
- showError("Failed to load MCP App resource: " + String(error));
243
- });
244
- };
245
-
246
- bridge.oncalltool = async (params) => {
247
- if (!consentGranted) {
248
- const accepted = window.confirm("Allow this UI to call server tools for this session?");
249
- if (!accepted) {
250
- await post("/proxy/ui/consent", { approved: false }).catch(() => {});
251
- return {
252
- isError: true,
253
- content: [{ type: "text", text: "Tool call denied by user." }],
254
- };
255
- }
256
- await post("/proxy/ui/consent", { approved: true });
257
- if (CACHE_TOOL_CONSENT) {
258
- consentGranted = true;
259
- }
260
- }
261
- const result = await post("/proxy/tools/call", params);
262
- // Notify agent about the tool call
263
- await post("/proxy/ui/generated-tool-call-intent", {
264
- tool: params.name,
265
- arguments: params.arguments,
266
- isError: result.isError
267
- }).catch(() => {});
268
- return result;
269
- };
270
-
271
- bridge.onmessage = async (params) => post("/proxy/ui/message", params);
272
- bridge.onupdatemodelcontext = async (params) => post("/proxy/ui/context", params);
273
-
274
- // Also listen for raw postMessage events with custom types (notify, prompt, intent, etc.)
275
- // These bypass the AppBridge protocol but are used by some MCP UI implementations
276
- window.addEventListener("message", async (event) => {
277
- if (event.source !== iframe.contentWindow || event.origin !== sandboxProxyOrigin) return;
278
- const data = event.data;
279
- if (!data || typeof data !== "object") return;
280
-
281
- // Skip AppBridge protocol messages (handled by bridge)
282
- if (data.jsonrpc || (typeof data.method === "string" && (data.method.startsWith("app/") || data.method.startsWith("host/")))) return;
283
-
284
- // Handle raw UI action messages
285
- const msgType = data.type;
286
- if (typeof msgType !== "string") return;
287
-
288
- if (msgType === "notify" || msgType === "prompt" || msgType === "intent" || msgType === "message") {
289
- // Standard MCP-UI types - preserve their semantics
290
- // Support both { type, payload: {...} } and { type, field: value } formats
291
- const { type: _, payload, ...directFields } = data;
292
- await post("/proxy/ui/message", { type: msgType, ...directFields, ...(payload || {}) }).catch(() => {});
293
- } else if (!msgType.startsWith("ui-lifecycle-") && !msgType.startsWith("ui-message-")) {
294
- // Any other custom type - forward as intent with type as intent name
295
- // (Skip internal lifecycle/ack messages)
296
- const payload = data.payload || {};
297
- await post("/proxy/ui/message", {
298
- type: "intent",
299
- intent: msgType,
300
- params: payload,
301
- }).catch(() => {});
302
- }
303
- });
304
- bridge.ondownloadfile = async (params) => post("/proxy/ui/download-file", params);
305
- bridge.onrequestdisplaymode = async (params) => post("/proxy/ui/request-display-mode", params);
306
- bridge.onopenlink = async (params) => {
307
- const result = await post("/proxy/ui/open-link", params);
308
- if (!result.isError) {
309
- window.open(params.url, "_blank", "noopener,noreferrer");
310
- // Notify agent about the link open
311
- await post("/proxy/ui/message", {
312
- type: "intent",
313
- intent: "open_link",
314
- params: { url: params.url }
315
- }).catch(() => {});
316
- }
317
- return result;
318
- };
319
-
320
- bridge.oninitialized = () => {
321
- if (streamMode !== "stream-first") {
322
- bridge.sendToolInput({ arguments: TOOL_ARGS });
323
- }
324
- setStatus(streamMode === "stream-first" ? "Streaming…" : "Connected");
325
- };
326
-
327
- bridge.onsizechange = ({ width, height }) => {
328
- if (typeof width === "number" && width > 0) {
329
- iframe.style.minWidth = Math.min(width, window.innerWidth - 24) + "px";
330
- }
331
- if (typeof height === "number" && height > 0) {
332
- iframe.style.height = Math.max(height, 320) + "px";
333
- }
334
- };
335
-
336
- if (ALLOW_ATTRIBUTE) {
337
- iframe.setAttribute("allow", ALLOW_ATTRIBUTE);
338
- }
339
-
340
- // Connect bridge BEFORE loading iframe to ensure we're listening when the app sends ui/initialize
341
- const sandboxMessageGuard = (event) => {
342
- if (event.source === iframe.contentWindow && event.origin !== sandboxProxyOrigin) {
343
- event.stopImmediatePropagation();
344
- }
345
- };
346
- window.addEventListener("message", sandboxMessageGuard, true);
347
- try {
348
- const transport = new PostMessageTransport(iframe.contentWindow, iframe.contentWindow);
349
- await bridge.connect(transport);
350
- } catch (error) {
351
- console.error("[host] Bridge connection failed:", error);
352
- showError("Failed to initialize AppBridge: " + String(error));
353
- }
354
-
355
- const iframeLoaded = new Promise((resolve) => {
356
- iframe.onload = resolve;
357
- });
358
- iframe.src = SANDBOX_PROXY_URL;
359
- await iframeLoaded;
360
-
361
- const eventSource = new EventSource("/events?session=" + encodeURIComponent(SESSION_TOKEN));
362
- eventSource.addEventListener("tool-input", (event) => {
363
- try {
364
- bridge.sendToolInput(JSON.parse(event.data));
365
- } catch (error) {
366
- showError("Failed to forward tool input: " + String(error));
367
- }
368
- });
369
- eventSource.addEventListener("tool-result", (event) => {
370
- try {
371
- bridge.sendToolResult(JSON.parse(event.data));
372
- } catch (error) {
373
- showError("Failed to forward tool result: " + String(error));
374
- }
375
- });
376
- eventSource.addEventListener("tool-cancelled", (event) => {
377
- try {
378
- bridge.sendToolCancelled(JSON.parse(event.data));
379
- } catch (error) {
380
- showError("Failed to forward cancellation: " + String(error));
381
- }
382
- });
383
- eventSource.addEventListener("resource-updated", () => {
384
- setStatus("Resource updated on the server. Reopen this UI to load the latest version.");
385
- });
386
- eventSource.addEventListener("result-patch", async (event) => {
387
- try {
388
- await bridge.notification({
389
- method: STREAM_PATCH_METHOD,
390
- params: JSON.parse(event.data),
391
- });
392
- } catch (error) {
393
- showError("Failed to forward stream patch: " + String(error));
394
- }
395
- });
396
- eventSource.addEventListener("host-context", (event) => {
397
- try {
398
- bridge.setHostContext(JSON.parse(event.data));
399
- } catch {}
400
- });
401
- eventSource.addEventListener("session-complete", async () => {
402
- await bridge.teardownResource({}).catch(() => {});
403
- eventSource.close();
404
- closeOrShowDone();
405
- });
406
- eventSource.onerror = () => {
407
- setStatus("Connection lost", true);
408
- };
409
-
410
- const heartbeat = setInterval(() => {
411
- post("/proxy/ui/heartbeat", {}).catch(() => {});
412
- }, 10000);
413
-
414
- const complete = async (reason) => {
415
- try {
416
- await post("/proxy/ui/complete", { reason });
417
- } catch {}
418
- try {
419
- await bridge.teardownResource({});
420
- } catch {}
421
- clearInterval(heartbeat);
422
- eventSource.close();
423
- closeOrShowDone();
424
- };
425
-
426
- doneBtn.addEventListener("click", () => complete("done"));
427
- cancelBtn.addEventListener("click", () => complete("cancel"));
428
- window.addEventListener("keydown", (event) => {
429
- if (event.key === "Escape") {
430
- event.preventDefault();
431
- complete("cancel");
432
- } else if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
433
- event.preventDefault();
434
- complete("done");
435
- }
436
- });
437
- </script>
438
- </body>
439
- </html>`;
440
- }
441
-
442
- export function buildCspMetaContent(csp: UiResourceCsp | undefined): string {
443
- return buildCspContent(csp, APP_SANDBOX);
444
- }
445
-
446
- /** CSP for provider HTML navigated on the isolated proxy origin. */
447
- export function buildSandboxResourceCsp(csp: UiResourceCsp | undefined): string {
448
- return buildCspContent(csp, APP_INNER_SANDBOX);
449
- }
450
-
451
- function buildCspContent(csp: UiResourceCsp | undefined, sandbox: string): string {
452
- const resourceDomains = sanitizeCspDomains(csp?.resourceDomains);
453
- const connectDomains = sanitizeCspDomains(csp?.connectDomains);
454
- const frameDomains = sanitizeCspDomains(csp?.frameDomains);
455
- const baseUriDomains = sanitizeCspDomains(csp?.baseUriDomains);
456
-
457
- return [
458
- "default-src 'none'",
459
- `sandbox ${sandbox}`,
460
- toDirective("script-src", ["'self'", "'unsafe-inline'"], resourceDomains),
461
- toDirective("style-src", ["'self'", "'unsafe-inline'"], resourceDomains),
462
- toDirective("font-src", ["'self'"], resourceDomains),
463
- toDirective("img-src", ["'self'", "data:"], resourceDomains),
464
- toDirective("media-src", ["'self'", "data:"], resourceDomains),
465
- connectDomains.length > 0
466
- ? `connect-src ${connectDomains.join(" ")}`
467
- : "connect-src 'none'",
468
- frameDomains.length > 0
469
- ? `frame-src ${frameDomains.join(" ")}`
470
- : "frame-src 'none'",
471
- "worker-src 'none'",
472
- "object-src 'none'",
473
- baseUriDomains.length > 0
474
- ? `base-uri ${baseUriDomains.join(" ")}`
475
- : "base-uri 'self'",
476
- ].join("; ");
477
- }
478
-
479
- function toDirective(name: string, trustedSources: string[], domains: string[]): string {
480
- return `${name} ${[...new Set([...trustedSources, ...domains])].join(" ")}`;
481
- }
482
-
483
- function sanitizeCspDomains(domains: unknown): string[] {
484
- if (!Array.isArray(domains)) return [];
485
-
486
- return [...new Set(domains.filter(
487
- (domain): domain is string =>
488
- typeof domain === "string" &&
489
- domain.length > 0 &&
490
- // HTTP headers must be printable ASCII; rejecting all other code points also
491
- // excludes every C0/C1 control character before Node serializes the policy.
492
- /^[\x21-\x7E]+$/.test(domain) &&
493
- !/[;'"]/.test(domain),
494
- ))];
495
- }
496
-
497
- function safeInlineJSON(value: unknown): string {
498
- const json = JSON.stringify(value);
499
- if (json === undefined) return "undefined";
500
- return json
501
- .replace(/</g, "\\u003c")
502
- .replace(/>/g, "\\u003e")
503
- .replace(/&/g, "\\u0026")
504
- .replace(/\u2028/g, "\\u2028")
505
- .replace(/\u2029/g, "\\u2029");
506
- }
507
-
508
- function escapeHtml(value: string): string {
509
- return value
510
- .replace(/&/g, "&amp;")
511
- .replace(/</g, "&lt;")
512
- .replace(/>/g, "&gt;")
513
- .replace(/"/g, "&quot;")
514
- .replace(/'/g, "&#39;");
515
- }
@@ -1,84 +0,0 @@
1
- import { readFileSync } from "node:fs";
2
- import { X509Certificate } from "node:crypto";
3
- import { Agent, Request as UndiciRequest, fetch as undiciFetch } from "undici";
4
- import type { RequestInit as UndiciRequestInit } from "undici";
5
- import type { ServerEntry } from "./types.ts";
6
- import { getMissingEnvVars, resolveConfigPath, resolveServerUrl } from "./utils.ts";
7
-
8
- /** Validate at the connection boundary, including callers that bypass JSON config. */
9
- export function validateCaFile(definition: ServerEntry): void {
10
- if (definition.caFile === undefined) return;
11
- if (typeof definition.caFile !== "string" || !definition.caFile.trim()) {
12
- throw new Error("MCP caFile must be a non-empty path string");
13
- }
14
- if (definition.command !== undefined || definition.socket !== undefined
15
- || !definition.url || new URL(resolveServerUrl(definition)!).protocol !== "https:") {
16
- throw new Error("MCP caFile is only supported for HTTPS HTTP servers");
17
- }
18
- }
19
-
20
- /** One connection owner, shared across transport/auth retries; never process-wide. */
21
- export function createCaFetch(definition: ServerEntry): { fetch: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>; close: () => Promise<void> } | undefined {
22
- validateCaFile(definition);
23
- if (definition.caFile === undefined) return undefined;
24
- const origin = new URL(resolveServerUrl(definition)!).origin;
25
- if (getMissingEnvVars(definition.caFile).length) throw new Error("Missing environment variable in MCP caFile");
26
- let ca: string;
27
- try {
28
- ca = readFileSync(resolveConfigPath(definition.caFile)!, "utf8");
29
- const certificates = ca.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);
30
- if (!certificates?.length || ca.replace(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g, "").trim()) {
31
- throw new Error("expected a PEM certificate bundle");
32
- }
33
- for (const certificate of certificates) new X509Certificate(certificate);
34
- } catch (cause) {
35
- throw new Error("Failed to load MCP caFile PEM certificate bundle", { cause });
36
- }
37
- const dispatcher = new Agent({ connect: { ca } });
38
- let closed: Promise<void> | undefined;
39
- return {
40
- fetch: (input, init) => {
41
- const url = new URL(input instanceof Request ? input.url : input.toString());
42
- if (url.origin !== origin) return globalThis.fetch(input, init);
43
- // The Agent comes from the bundled undici copy, whose internals do not
44
- // match the global fetch dispatcher contract on newer Node releases
45
- // (Node 26 ships undici v8; the dependency pins undici v6). Route
46
- // same-origin requests through the bundled fetch so dispatcher and
47
- // Agent share an implementation. Never follow a redirect with this
48
- // dispatcher, even to the same origin (no trust-bearing redirect hops).
49
- // Attach after header-command Request reconstruction.
50
- try {
51
- const bundledInput = input instanceof Request
52
- ? new UndiciRequest(input.url, {
53
- method: input.method,
54
- headers: [...input.headers],
55
- // Defer acquiring the source stream until bundled Request validation
56
- // succeeds. An overriding body never consumes the original body.
57
- ...(init?.body == null && input.body ? { body: (async function* () {
58
- yield* input.body!;
59
- })(), duplex: "half" as const } : {}),
60
- cache: input.cache,
61
- credentials: input.credentials,
62
- integrity: input.integrity,
63
- keepalive: input.keepalive,
64
- mode: input.mode,
65
- redirect: input.redirect,
66
- referrer: input.referrer,
67
- referrerPolicy: input.referrerPolicy,
68
- signal: input.signal,
69
- } as unknown as UndiciRequestInit)
70
- : input;
71
- const options = {
72
- ...init,
73
- ...(init?.headers !== undefined ? { headers: [...new Headers(init.headers)] } : {}),
74
- dispatcher,
75
- redirect: "error" as const,
76
- } as unknown as UndiciRequestInit;
77
- return undiciFetch(bundledInput, options) as unknown as Promise<Response>;
78
- } catch (error) {
79
- return Promise.reject(error);
80
- }
81
- },
82
- close: () => closed ??= dispatcher.destroy(),
83
- };
84
- }