@ashx-j/lunr-dev 0.2.13-dev.7.1 → 0.2.16-dev.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (384) hide show
  1. package/CHANGELOG.md +29 -1
  2. package/dist/builtin-extensions/ashxj-tui.d.ts +14 -0
  3. package/dist/builtin-extensions/ashxj-tui.d.ts.map +1 -1
  4. package/dist/builtin-extensions/ashxj-tui.js +37 -3
  5. package/dist/builtin-extensions/ashxj-tui.js.map +1 -1
  6. package/dist/builtin-extensions/index.d.ts +1 -15
  7. package/dist/builtin-extensions/index.d.ts.map +1 -1
  8. package/dist/builtin-extensions/index.js +7 -21
  9. package/dist/builtin-extensions/index.js.map +1 -1
  10. package/dist/builtin-extensions/narumiruna-pi-goal/src/goal.d.ts.map +1 -1
  11. package/dist/builtin-extensions/narumiruna-pi-goal/src/goal.js +6 -2
  12. package/dist/builtin-extensions/narumiruna-pi-goal/src/goal.js.map +1 -1
  13. package/dist/builtin-extensions/pi-lsp-extension/src/index.d.ts +4 -0
  14. package/dist/builtin-extensions/pi-lsp-extension/src/index.d.ts.map +1 -1
  15. package/dist/builtin-extensions/pi-lsp-extension/src/index.js +163 -169
  16. package/dist/builtin-extensions/pi-lsp-extension/src/index.js.map +1 -1
  17. package/dist/builtin-extensions/pi-lsp-extension/src/runtime.d.ts +46 -0
  18. package/dist/builtin-extensions/pi-lsp-extension/src/runtime.d.ts.map +1 -0
  19. package/dist/builtin-extensions/pi-lsp-extension/src/runtime.js +109 -0
  20. package/dist/builtin-extensions/pi-lsp-extension/src/runtime.js.map +1 -0
  21. package/dist/builtin-extensions/pi-mcp-adapter/direct-tool-executor.d.ts +7 -0
  22. package/dist/builtin-extensions/pi-mcp-adapter/direct-tool-executor.d.ts.map +1 -0
  23. package/dist/builtin-extensions/pi-mcp-adapter/direct-tool-executor.js +211 -0
  24. package/dist/builtin-extensions/pi-mcp-adapter/direct-tool-executor.js.map +1 -0
  25. package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.d.ts +0 -5
  26. package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.d.ts.map +1 -1
  27. package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.js +0 -202
  28. package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.js.map +1 -1
  29. package/dist/builtin-extensions/pi-mcp-adapter/index.d.ts.map +1 -1
  30. package/dist/builtin-extensions/pi-mcp-adapter/index.js +251 -94
  31. package/dist/builtin-extensions/pi-mcp-adapter/index.js.map +1 -1
  32. package/dist/builtin-extensions/pi-mcp-adapter/init.d.ts +4 -1
  33. package/dist/builtin-extensions/pi-mcp-adapter/init.d.ts.map +1 -1
  34. package/dist/builtin-extensions/pi-mcp-adapter/init.js +10 -3
  35. package/dist/builtin-extensions/pi-mcp-adapter/init.js.map +1 -1
  36. package/dist/builtin-extensions/pi-mcp-adapter/metadata-cache.d.ts.map +1 -1
  37. package/dist/builtin-extensions/pi-mcp-adapter/metadata-cache.js +6 -1
  38. package/dist/builtin-extensions/pi-mcp-adapter/metadata-cache.js.map +1 -1
  39. package/dist/builtin-extensions/pi-prompt-template-model/prompt-loader.d.ts.map +1 -1
  40. package/dist/builtin-extensions/pi-prompt-template-model/prompt-loader.js +2 -1
  41. package/dist/builtin-extensions/pi-prompt-template-model/prompt-loader.js.map +1 -1
  42. package/dist/builtin-extensions/pi-prompt-template-model/tool-manager.d.ts +1 -1
  43. package/dist/builtin-extensions/pi-prompt-template-model/tool-manager.d.ts.map +1 -1
  44. package/dist/builtin-extensions/pi-prompt-template-model/tool-manager.js +1 -1
  45. package/dist/builtin-extensions/pi-prompt-template-model/tool-manager.js.map +1 -1
  46. package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts +1 -1
  47. package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts.map +1 -1
  48. package/dist/builtin-extensions/pi-subagents/src/extension/index.js +38 -14
  49. package/dist/builtin-extensions/pi-subagents/src/extension/index.js.map +1 -1
  50. package/dist/builtin-extensions/pi-subagents/src/shared/fork-context.d.ts.map +1 -1
  51. package/dist/builtin-extensions/pi-subagents/src/shared/fork-context.js +1 -1
  52. package/dist/builtin-extensions/pi-subagents/src/shared/fork-context.js.map +1 -1
  53. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts +1 -1
  54. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts.map +1 -1
  55. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js +1 -1
  56. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js.map +1 -1
  57. package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts +1 -1
  58. package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts.map +1 -1
  59. package/dist/builtin-extensions/pi-subagents/src/tui/render.js +2 -1
  60. package/dist/builtin-extensions/pi-subagents/src/tui/render.js.map +1 -1
  61. package/dist/builtin-extensions/pi-subagents/src/watchdog/review.d.ts +1 -1
  62. package/dist/builtin-extensions/pi-subagents/src/watchdog/review.d.ts.map +1 -1
  63. package/dist/builtin-extensions/pi-subagents/src/watchdog/review.js +2 -1
  64. package/dist/builtin-extensions/pi-subagents/src/watchdog/review.js.map +1 -1
  65. package/dist/builtin-extensions/pi-web-access/extract.d.ts.map +1 -1
  66. package/dist/builtin-extensions/pi-web-access/extract.js +105 -54
  67. package/dist/builtin-extensions/pi-web-access/extract.js.map +1 -1
  68. package/dist/builtin-extensions/pi-web-access/gemini-search.d.ts +1 -1
  69. package/dist/builtin-extensions/pi-web-access/gemini-search.d.ts.map +1 -1
  70. package/dist/builtin-extensions/pi-web-access/gemini-search.js +82 -65
  71. package/dist/builtin-extensions/pi-web-access/gemini-search.js.map +1 -1
  72. package/dist/builtin-extensions/pi-web-access/github-extract.d.ts.map +1 -1
  73. package/dist/builtin-extensions/pi-web-access/github-extract.js +2 -0
  74. package/dist/builtin-extensions/pi-web-access/github-extract.js.map +1 -1
  75. package/dist/builtin-extensions/pi-web-access/index.d.ts.map +1 -1
  76. package/dist/builtin-extensions/pi-web-access/index.js +167 -77
  77. package/dist/builtin-extensions/pi-web-access/index.js.map +1 -1
  78. package/dist/builtin-extensions/pi-web-access/lazy.d.ts +18 -0
  79. package/dist/builtin-extensions/pi-web-access/lazy.d.ts.map +1 -0
  80. package/dist/builtin-extensions/pi-web-access/lazy.js +19 -0
  81. package/dist/builtin-extensions/pi-web-access/lazy.js.map +1 -0
  82. package/dist/builtin-extensions/pi-web-access/session-cleanup.d.ts +6 -0
  83. package/dist/builtin-extensions/pi-web-access/session-cleanup.d.ts.map +1 -0
  84. package/dist/builtin-extensions/pi-web-access/session-cleanup.js +17 -0
  85. package/dist/builtin-extensions/pi-web-access/session-cleanup.js.map +1 -0
  86. package/dist/catalog/models.json +1 -1
  87. package/dist/catalog/providers/amazon-bedrock.json +1 -1
  88. package/dist/catalog/providers/azure-openai-responses.json +1 -1
  89. package/dist/catalog/providers/fireworks.json +1 -1
  90. package/dist/catalog/providers/github-copilot.json +1 -1
  91. package/dist/catalog/providers/openai-codex.json +1 -1
  92. package/dist/catalog/providers/openai.json +1 -1
  93. package/dist/catalog/providers/opencode.json +1 -1
  94. package/dist/catalog/providers/openrouter.json +1 -1
  95. package/dist/catalog/providers/vercel-ai-gateway.json +1 -1
  96. package/dist/catalog/publication.json +131 -3
  97. package/dist/cli/list-models.d.ts.map +1 -1
  98. package/dist/cli/list-models.js +1 -0
  99. package/dist/cli/list-models.js.map +1 -1
  100. package/dist/cli-runtime.d.ts +3 -0
  101. package/dist/cli-runtime.d.ts.map +1 -0
  102. package/dist/cli-runtime.js +73 -0
  103. package/dist/cli-runtime.js.map +1 -0
  104. package/dist/cli.d.ts.map +1 -1
  105. package/dist/cli.js +14 -53
  106. package/dist/cli.js.map +1 -1
  107. package/dist/config.d.ts +1 -0
  108. package/dist/config.d.ts.map +1 -1
  109. package/dist/config.js +1 -0
  110. package/dist/config.js.map +1 -1
  111. package/dist/core/agent-session.d.ts +3 -0
  112. package/dist/core/agent-session.d.ts.map +1 -1
  113. package/dist/core/agent-session.js +56 -12
  114. package/dist/core/agent-session.js.map +1 -1
  115. package/dist/core/catalog-cache-scope.d.ts +3 -0
  116. package/dist/core/catalog-cache-scope.d.ts.map +1 -0
  117. package/dist/core/catalog-cache-scope.js +12 -0
  118. package/dist/core/catalog-cache-scope.js.map +1 -0
  119. package/dist/core/catalog-merge.d.ts +2 -0
  120. package/dist/core/catalog-merge.d.ts.map +1 -1
  121. package/dist/core/catalog-merge.js +29 -2
  122. package/dist/core/catalog-merge.js.map +1 -1
  123. package/dist/core/catalog-refresh-polling.d.ts +8 -0
  124. package/dist/core/catalog-refresh-polling.d.ts.map +1 -0
  125. package/dist/core/catalog-refresh-polling.js +30 -0
  126. package/dist/core/catalog-refresh-polling.js.map +1 -0
  127. package/dist/core/codex-catalog.d.ts +3 -0
  128. package/dist/core/codex-catalog.d.ts.map +1 -0
  129. package/dist/core/codex-catalog.js +15 -0
  130. package/dist/core/codex-catalog.js.map +1 -0
  131. package/dist/core/compaction/compaction.d.ts.map +1 -1
  132. package/dist/core/compaction/compaction.js +10 -5
  133. package/dist/core/compaction/compaction.js.map +1 -1
  134. package/dist/core/extensions/host-static.d.ts.map +1 -1
  135. package/dist/core/extensions/host-static.js +34 -12
  136. package/dist/core/extensions/host-static.js.map +1 -1
  137. package/dist/core/extensions/loader.d.ts +1 -2
  138. package/dist/core/extensions/loader.d.ts.map +1 -1
  139. package/dist/core/extensions/loader.js +10 -64
  140. package/dist/core/extensions/loader.js.map +1 -1
  141. package/dist/core/extensions/types.d.ts +2 -2
  142. package/dist/core/extensions/types.d.ts.map +1 -1
  143. package/dist/core/extensions/types.js.map +1 -1
  144. package/dist/core/footer-data-provider.d.ts.map +1 -1
  145. package/dist/core/footer-data-provider.js +2 -0
  146. package/dist/core/footer-data-provider.js.map +1 -1
  147. package/dist/core/live-catalog.d.ts +5 -2
  148. package/dist/core/live-catalog.d.ts.map +1 -1
  149. package/dist/core/live-catalog.js +108 -27
  150. package/dist/core/live-catalog.js.map +1 -1
  151. package/dist/core/model-runtime.d.ts +8 -0
  152. package/dist/core/model-runtime.d.ts.map +1 -1
  153. package/dist/core/model-runtime.js +64 -12
  154. package/dist/core/model-runtime.js.map +1 -1
  155. package/dist/core/official-catalog.d.ts +4 -0
  156. package/dist/core/official-catalog.d.ts.map +1 -1
  157. package/dist/core/official-catalog.js +86 -21
  158. package/dist/core/official-catalog.js.map +1 -1
  159. package/dist/core/permissions.d.ts +0 -2
  160. package/dist/core/permissions.d.ts.map +1 -1
  161. package/dist/core/permissions.js +10 -18
  162. package/dist/core/permissions.js.map +1 -1
  163. package/dist/core/sdk.d.ts +1 -1
  164. package/dist/core/sdk.d.ts.map +1 -1
  165. package/dist/core/sdk.js +1 -1
  166. package/dist/core/sdk.js.map +1 -1
  167. package/dist/core/slash-commands.d.ts.map +1 -1
  168. package/dist/core/slash-commands.js +0 -1
  169. package/dist/core/slash-commands.js.map +1 -1
  170. package/dist/core/timings.d.ts +2 -1
  171. package/dist/core/timings.d.ts.map +1 -1
  172. package/dist/core/timings.js +17 -2
  173. package/dist/core/timings.js.map +1 -1
  174. package/dist/gateway/commands.d.ts +1 -1
  175. package/dist/gateway/commands.d.ts.map +1 -1
  176. package/dist/gateway/commands.js +1 -18
  177. package/dist/gateway/commands.js.map +1 -1
  178. package/dist/main.d.ts +2 -2
  179. package/dist/main.d.ts.map +1 -1
  180. package/dist/main.js +66 -48
  181. package/dist/main.js.map +1 -1
  182. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  183. package/dist/modes/interactive/components/model-selector.js +4 -1
  184. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  185. package/dist/modes/interactive/interactive-mode.d.ts +13 -22
  186. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  187. package/dist/modes/interactive/interactive-mode.js +141 -207
  188. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  189. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  190. package/dist/modes/interactive/theme/theme.js +95 -84
  191. package/dist/modes/interactive/theme/theme.js.map +1 -1
  192. package/dist/node-runtime/agent-session-services-IFJMSX7Z.js +36 -0
  193. package/dist/node-runtime/benchmark-request-UC7PD3V3.js +57 -0
  194. package/dist/node-runtime/brave-UWDA3I22.js +143 -0
  195. package/dist/node-runtime/builtin-extensions-LYZ3BFWQ.js +28 -0
  196. package/dist/node-runtime/chunk-2QKLKMKC.js +173 -0
  197. package/dist/node-runtime/chunk-3GHXVUAK.js +21 -0
  198. package/dist/node-runtime/chunk-3RCWXWAY.js +466 -0
  199. package/dist/node-runtime/chunk-3WFAEVKS.js +115 -0
  200. package/dist/node-runtime/chunk-3X3KZKMI.js +49 -0
  201. package/dist/node-runtime/chunk-4HXHDDCF.js +16 -0
  202. package/dist/node-runtime/chunk-4TLO4PO2.js +3427 -0
  203. package/dist/node-runtime/chunk-4ZWGEEAS.js +69 -0
  204. package/dist/node-runtime/chunk-53YJI7JU.js +137 -0
  205. package/dist/node-runtime/chunk-5P7PZMRU.js +610 -0
  206. package/dist/node-runtime/chunk-7N3YHTYF.js +26 -0
  207. package/dist/node-runtime/chunk-7NBZ5P7I.js +24 -0
  208. package/dist/node-runtime/chunk-A2KQXUJD.js +105 -0
  209. package/dist/node-runtime/chunk-AD6VXAO7.js +342 -0
  210. package/dist/node-runtime/chunk-AHSTJBIB.js +64 -0
  211. package/dist/node-runtime/chunk-AJX357CL.js +20211 -0
  212. package/dist/node-runtime/chunk-ARC4KOTI.js +11178 -0
  213. package/dist/node-runtime/chunk-AUXVGBO4.js +19 -0
  214. package/dist/node-runtime/chunk-AY6CAJSL.js +30 -0
  215. package/dist/node-runtime/chunk-BHO7O6E5.js +296 -0
  216. package/dist/node-runtime/chunk-BI3DHYCN.js +8845 -0
  217. package/dist/node-runtime/chunk-BR7YDUKA.js +109 -0
  218. package/dist/node-runtime/chunk-BRJX2PRC.js +53 -0
  219. package/dist/node-runtime/chunk-C4O2RSQQ.js +37 -0
  220. package/dist/node-runtime/chunk-CCZJ3PYY.js +17 -0
  221. package/dist/node-runtime/chunk-CDFZEWPU.js +8388 -0
  222. package/dist/node-runtime/chunk-CGBXPL3E.js +1171 -0
  223. package/dist/node-runtime/chunk-CJECDQKP.js +19 -0
  224. package/dist/node-runtime/chunk-DAPBPCBP.js +53 -0
  225. package/dist/node-runtime/chunk-DDGMHUOW.js +305 -0
  226. package/dist/node-runtime/chunk-DMMTJQMQ.js +43 -0
  227. package/dist/node-runtime/chunk-DVGWF6A2.js +1180 -0
  228. package/dist/node-runtime/chunk-ECD5L7YI.js +1369 -0
  229. package/dist/node-runtime/chunk-EDBJNRSM.js +46 -0
  230. package/dist/node-runtime/chunk-F4VQFJI2.js +1269 -0
  231. package/dist/node-runtime/chunk-FVDOXRUD.js +96 -0
  232. package/dist/node-runtime/chunk-GZQHMEWL.js +126 -0
  233. package/dist/node-runtime/chunk-H2EOZYMP.js +57 -0
  234. package/dist/node-runtime/chunk-HQCKFM2O.js +56 -0
  235. package/dist/node-runtime/chunk-HYHJIRDW.js +19 -0
  236. package/dist/node-runtime/chunk-I6R76AG7.js +22 -0
  237. package/dist/node-runtime/chunk-IPA627GP.js +296 -0
  238. package/dist/node-runtime/chunk-JHYKXIMM.js +378 -0
  239. package/dist/node-runtime/chunk-KKSIVROT.js +88 -0
  240. package/dist/node-runtime/chunk-LZAW4ZX3.js +633 -0
  241. package/dist/node-runtime/chunk-M3LZLQW2.js +98 -0
  242. package/dist/node-runtime/chunk-MGWCVY6Y.js +47 -0
  243. package/dist/node-runtime/chunk-MJQDX3BA.js +72 -0
  244. package/dist/node-runtime/chunk-MKKH27PH.js +8956 -0
  245. package/dist/node-runtime/chunk-MX3GJNXJ.js +986 -0
  246. package/dist/node-runtime/chunk-N77MY65L.js +966 -0
  247. package/dist/node-runtime/chunk-NUIFPZWX.js +209 -0
  248. package/dist/node-runtime/chunk-OBMWP3I5.js +68 -0
  249. package/dist/node-runtime/chunk-OR4L3IB2.js +42 -0
  250. package/dist/node-runtime/chunk-PBC2Y6GS.js +903 -0
  251. package/dist/node-runtime/chunk-PCGNAY2O.js +1324 -0
  252. package/dist/node-runtime/chunk-PCIGF2XK.js +250 -0
  253. package/dist/node-runtime/chunk-PGAJ5MO5.js +7558 -0
  254. package/dist/node-runtime/chunk-PL6JKXWI.js +3622 -0
  255. package/dist/node-runtime/chunk-PVCDKGR6.js +55 -0
  256. package/dist/node-runtime/chunk-Q4Q6D4IY.js +364 -0
  257. package/dist/node-runtime/chunk-Q5ZU2VRT.js +83 -0
  258. package/dist/node-runtime/chunk-QFWG2RVL.js +5477 -0
  259. package/dist/node-runtime/chunk-QH42CDX3.js +9451 -0
  260. package/dist/node-runtime/chunk-RQ2Q5IYR.js +72 -0
  261. package/dist/node-runtime/chunk-RQ5DNUNG.js +429 -0
  262. package/dist/node-runtime/chunk-RRIZE6QQ.js +17 -0
  263. package/dist/node-runtime/chunk-SN6G4OU6.js +4753 -0
  264. package/dist/node-runtime/chunk-SWSN6HAB.js +53 -0
  265. package/dist/node-runtime/chunk-TQNSPERU.js +949 -0
  266. package/dist/node-runtime/chunk-VRB2IYGG.js +53 -0
  267. package/dist/node-runtime/chunk-VSELYKWU.js +772 -0
  268. package/dist/node-runtime/chunk-W3CVH5RX.js +62 -0
  269. package/dist/node-runtime/chunk-WJVFOIB5.js +24921 -0
  270. package/dist/node-runtime/chunk-WOVTOV5P.js +5653 -0
  271. package/dist/node-runtime/chunk-XBWPBZBN.js +125 -0
  272. package/dist/node-runtime/chunk-XTHQ7XR7.js +509 -0
  273. package/dist/node-runtime/chunk-YF63P5ZT.js +864 -0
  274. package/dist/node-runtime/chunk-YSKSB3BJ.js +295 -0
  275. package/dist/node-runtime/chunk-ZCHMJ34K.js +130 -0
  276. package/dist/node-runtime/chunk-ZKMFUD3Q.js +2834 -0
  277. package/dist/node-runtime/cli-runtime.js +81 -0
  278. package/dist/node-runtime/clipboard-OZ63BBC6.js +12 -0
  279. package/dist/node-runtime/clipboard-image-7QR6GXVA.js +13 -0
  280. package/dist/node-runtime/command-L3LAHDIH.js +13 -0
  281. package/dist/node-runtime/commands-RL5YBW5I.js +291 -0
  282. package/dist/node-runtime/config-FMEOZSWE.js +77 -0
  283. package/dist/node-runtime/curator-server-XCM43VEF.js +3816 -0
  284. package/dist/node-runtime/customize-XEXL2DGQ.js +12 -0
  285. package/dist/node-runtime/direct-tool-executor-JVDXTO7A.js +188 -0
  286. package/dist/node-runtime/exa-LL64QZR2.js +329 -0
  287. package/dist/node-runtime/export-html-KR26FOUZ.js +150 -0
  288. package/dist/node-runtime/extension-input-RV5N6APL.js +14 -0
  289. package/dist/node-runtime/extension-selector-CPD5LWDD.js +14 -0
  290. package/dist/node-runtime/extract-XLQSJN4V.js +17 -0
  291. package/dist/node-runtime/file-sync-HCOP2QVF.js +117 -0
  292. package/dist/node-runtime/gateway-X2TI5X7F.js +2484 -0
  293. package/dist/node-runtime/gemini-api-QE7ANVDZ.js +29 -0
  294. package/dist/node-runtime/gemini-search-U7SUMPQA.js +330 -0
  295. package/dist/node-runtime/gemini-url-context-PXWCBQHK.js +103 -0
  296. package/dist/node-runtime/gemini-web-MM446SEH.js +14 -0
  297. package/dist/node-runtime/github-extract-F64RZOEA.js +619 -0
  298. package/dist/node-runtime/goal-CZQ7FFQJ.js +1831 -0
  299. package/dist/node-runtime/index.js +859 -0
  300. package/dist/node-runtime/init-NJV2T55N.js +28 -0
  301. package/dist/node-runtime/install-cli-TH7IJJQQ.js +308 -0
  302. package/dist/node-runtime/interactive-mode-KOM35YF2.js +56 -0
  303. package/dist/node-runtime/interactive-view-U6OILKF3.js +249 -0
  304. package/dist/node-runtime/lsp-manager-3ASUSO4T.js +1104 -0
  305. package/dist/node-runtime/lunr-cron-YJ5UHYRD.js +268 -0
  306. package/dist/node-runtime/main.js +54 -0
  307. package/dist/node-runtime/mcp-auth-flow-QIXHW6QN.js +32 -0
  308. package/dist/node-runtime/mcp-panel-IIGMXQGP.js +501 -0
  309. package/dist/node-runtime/mcp-setup-panel-FEK7663I.js +355 -0
  310. package/dist/node-runtime/memory-cap-3S4XRLNP.js +20 -0
  311. package/dist/node-runtime/model-tiers-NJLHUEGK.js +20 -0
  312. package/dist/node-runtime/openai-search-B3MSNCQA.js +288 -0
  313. package/dist/node-runtime/package-manager-cli-TZZHJCVI.js +749 -0
  314. package/dist/node-runtime/parallel-AI2MNSCU.js +265 -0
  315. package/dist/node-runtime/parser-manager-TQHWYDH7.js +152 -0
  316. package/dist/node-runtime/pdf-extract-IPE6H4HP.js +57 -0
  317. package/dist/node-runtime/perplexity-QVJW3I35.js +12 -0
  318. package/dist/node-runtime/pi-intercom-EEMBGQID.js +2215 -0
  319. package/dist/node-runtime/pi-mcp-adapter-QFB37AVN.js +422 -0
  320. package/dist/node-runtime/pi-ollama-cloud-4VZRMULP.js +1440 -0
  321. package/dist/node-runtime/pi-prompt-template-model-4QT4LLXF.js +3946 -0
  322. package/dist/node-runtime/pi-subagents-7XJ4H53P.js +6023 -0
  323. package/dist/node-runtime/pi-web-access-DPGAVKOA.js +1864 -0
  324. package/dist/node-runtime/print-mode-VWIRFDAC.js +12 -0
  325. package/dist/node-runtime/proxy-modes-HEEFK4KC.js +685 -0
  326. package/dist/node-runtime/rpc-entry.js +62 -0
  327. package/dist/node-runtime/rpc-mode-SJNSOA4G.js +13 -0
  328. package/dist/node-runtime/runtime-bridges-PPHNBFWL.js +14 -0
  329. package/dist/node-runtime/session-manager-MQNBYACL.js +35 -0
  330. package/dist/node-runtime/session-selector-5AZLJS6U.js +14 -0
  331. package/dist/node-runtime/settings-manager-5LF2VQWC.js +21 -0
  332. package/dist/node-runtime/src-Y7JSCK64.js +2407 -0
  333. package/dist/node-runtime/subagent-executor-5RNDEPIJ.js +8483 -0
  334. package/dist/node-runtime/summary-review-YSMXKITO.js +228 -0
  335. package/dist/node-runtime/tavily-WEZFVFP7.js +154 -0
  336. package/dist/node-runtime/timings-UAD5BEAS.js +16 -0
  337. package/dist/node-runtime/tool-renderer-MV5O452K.js +204 -0
  338. package/dist/node-runtime/update-cli-A253SZ7P.js +73 -0
  339. package/dist/node-runtime/v4-5MNC3H7G.js +424 -0
  340. package/dist/node-runtime/video-extract-OYT5WKS5.js +304 -0
  341. package/dist/node-runtime/workspace-index-6DBXSTJ6.js +163 -0
  342. package/dist/node-runtime/youtube-extract-TQYKGFGS.js +264 -0
  343. package/dist/startup/benchmark-request.d.ts +3 -0
  344. package/dist/startup/benchmark-request.d.ts.map +1 -0
  345. package/dist/startup/benchmark-request.js +65 -0
  346. package/dist/startup/benchmark-request.js.map +1 -0
  347. package/dist/startup/interactive-view.d.ts +55 -0
  348. package/dist/startup/interactive-view.d.ts.map +1 -0
  349. package/dist/startup/interactive-view.js +332 -0
  350. package/dist/startup/interactive-view.js.map +1 -0
  351. package/dist/startup/launch-routing.d.ts.map +1 -1
  352. package/dist/startup/launch-routing.js +9 -10
  353. package/dist/startup/launch-routing.js.map +1 -1
  354. package/dist/startup/startup-milestones.d.ts +1 -1
  355. package/dist/startup/startup-milestones.d.ts.map +1 -1
  356. package/dist/startup/startup-milestones.js +3 -2
  357. package/dist/startup/startup-milestones.js.map +1 -1
  358. package/dist/utils/await-with-abort.d.ts +2 -0
  359. package/dist/utils/await-with-abort.d.ts.map +1 -0
  360. package/dist/utils/await-with-abort.js +19 -0
  361. package/dist/utils/await-with-abort.js.map +1 -0
  362. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  363. package/dist/utils/syntax-highlight.js +10 -4
  364. package/dist/utils/syntax-highlight.js.map +1 -1
  365. package/docs/compaction.md +5 -3
  366. package/docs/development.md +5 -1
  367. package/docs/features.md +0 -1
  368. package/docs/interactive-startup.md +98 -0
  369. package/docs/model-catalog.md +29 -0
  370. package/docs/usage.md +0 -1
  371. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  372. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  373. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  374. package/examples/extensions/gondolin/package-lock.json +2 -2
  375. package/examples/extensions/gondolin/package.json +1 -1
  376. package/examples/extensions/sandbox/package-lock.json +2 -2
  377. package/examples/extensions/sandbox/package.json +1 -1
  378. package/examples/extensions/with-deps/package-lock.json +2 -2
  379. package/examples/extensions/with-deps/package.json +1 -1
  380. package/package.json +20 -20
  381. package/dist/core/swarm.d.ts +0 -23
  382. package/dist/core/swarm.d.ts.map +0 -1
  383. package/dist/core/swarm.js +0 -45
  384. package/dist/core/swarm.js.map +0 -1
@@ -0,0 +1,3427 @@
1
+ import { createRequire as __lunrRequire } from "node:module"; const require = __lunrRequire(import.meta.url);
2
+ import {
3
+ getAgentPath
4
+ } from "./chunk-4HXHDDCF.js";
5
+ import {
6
+ NEVER,
7
+ ZodIssueCode,
8
+ _enum,
9
+ _null,
10
+ any,
11
+ array,
12
+ boolean,
13
+ coerce_exports,
14
+ custom,
15
+ discriminatedUnion,
16
+ intersection,
17
+ iso_exports,
18
+ literal,
19
+ looseObject,
20
+ number,
21
+ object,
22
+ optional,
23
+ preprocess,
24
+ record,
25
+ string,
26
+ union,
27
+ unknown,
28
+ url
29
+ } from "./chunk-BI3DHYCN.js";
30
+ import {
31
+ __commonJS,
32
+ __toESM
33
+ } from "./chunk-BRJX2PRC.js";
34
+
35
+ // node_modules/content-type/index.js
36
+ var require_content_type = __commonJS({
37
+ "node_modules/content-type/index.js"(exports) {
38
+ "use strict";
39
+ var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g, TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/, TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/, QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g, QUOTE_REGEXP = /([\\"])/g, TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
40
+ exports.format = format;
41
+ exports.parse = parse;
42
+ function format(obj) {
43
+ if (!obj || typeof obj != "object")
44
+ throw new TypeError("argument obj is required");
45
+ var parameters = obj.parameters, type = obj.type;
46
+ if (!type || !TYPE_REGEXP.test(type))
47
+ throw new TypeError("invalid type");
48
+ var string2 = type;
49
+ if (parameters && typeof parameters == "object")
50
+ for (var param, params = Object.keys(parameters).sort(), i = 0; i < params.length; i++) {
51
+ if (param = params[i], !TOKEN_REGEXP.test(param))
52
+ throw new TypeError("invalid parameter name");
53
+ string2 += "; " + param + "=" + qstring(parameters[param]);
54
+ }
55
+ return string2;
56
+ }
57
+ function parse(string2) {
58
+ if (!string2)
59
+ throw new TypeError("argument string is required");
60
+ var header = typeof string2 == "object" ? getcontenttype(string2) : string2;
61
+ if (typeof header != "string")
62
+ throw new TypeError("argument string is required to be a string");
63
+ var index = header.indexOf(";"), type = index !== -1 ? header.slice(0, index).trim() : header.trim();
64
+ if (!TYPE_REGEXP.test(type))
65
+ throw new TypeError("invalid media type");
66
+ var obj = new ContentType(type.toLowerCase());
67
+ if (index !== -1) {
68
+ var key, match, value;
69
+ for (PARAM_REGEXP.lastIndex = index; match = PARAM_REGEXP.exec(header); ) {
70
+ if (match.index !== index)
71
+ throw new TypeError("invalid parameter format");
72
+ index += match[0].length, key = match[1].toLowerCase(), value = match[2], value.charCodeAt(0) === 34 && (value = value.slice(1, -1), value.indexOf("\\") !== -1 && (value = value.replace(QESC_REGEXP, "$1"))), obj.parameters[key] = value;
73
+ }
74
+ if (index !== header.length)
75
+ throw new TypeError("invalid parameter format");
76
+ }
77
+ return obj;
78
+ }
79
+ function getcontenttype(obj) {
80
+ var header;
81
+ if (typeof obj.getHeader == "function" ? header = obj.getHeader("content-type") : typeof obj.headers == "object" && (header = obj.headers && obj.headers["content-type"]), typeof header != "string")
82
+ throw new TypeError("content-type header is missing from object");
83
+ return header;
84
+ }
85
+ function qstring(val) {
86
+ var str = String(val);
87
+ if (TOKEN_REGEXP.test(str))
88
+ return str;
89
+ if (str.length > 0 && !TEXT_REGEXP.test(str))
90
+ throw new TypeError("invalid parameter value");
91
+ return '"' + str.replace(QUOTE_REGEXP, "\\$1") + '"';
92
+ }
93
+ function ContentType(type) {
94
+ this.parameters = /* @__PURE__ */ Object.create(null), this.type = type;
95
+ }
96
+ }
97
+ });
98
+
99
+ // node_modules/pkce-challenge/dist/index.node.js
100
+ var crypto2;
101
+ crypto2 = globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL
102
+ globalThis.crypto ?? // Node.js >18
103
+ import("node:crypto").then((m) => m.webcrypto);
104
+ async function getRandomValues(size) {
105
+ return (await crypto2).getRandomValues(new Uint8Array(size));
106
+ }
107
+ async function random(size) {
108
+ let mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~", evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length, result = "";
109
+ for (; result.length < size; ) {
110
+ let randomBytes = await getRandomValues(size - result.length);
111
+ for (let randomByte of randomBytes)
112
+ randomByte < evenDistCutoff && (result += mask[randomByte % mask.length]);
113
+ }
114
+ return result;
115
+ }
116
+ async function generateVerifier(length) {
117
+ return await random(length);
118
+ }
119
+ async function generateChallenge(code_verifier) {
120
+ let buffer = await (await crypto2).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier));
121
+ return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "");
122
+ }
123
+ async function pkceChallenge(length) {
124
+ if (length || (length = 43), length < 43 || length > 128)
125
+ throw `Expected a length between 43 and 128. Received ${length}.`;
126
+ let verifier = await generateVerifier(length), challenge = await generateChallenge(verifier);
127
+ return {
128
+ code_verifier: verifier,
129
+ code_challenge: challenge
130
+ };
131
+ }
132
+
133
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
134
+ var LATEST_PROTOCOL_VERSION = "2025-11-25";
135
+ var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"], RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task", JSONRPC_VERSION = "2.0", AssertObjectSchema = custom((v) => v !== null && (typeof v == "object" || typeof v == "function")), ProgressTokenSchema = union([string(), number().int()]), CursorSchema = string(), TaskCreationParamsSchema = looseObject({
136
+ /**
137
+ * Requested duration in milliseconds to retain task from creation.
138
+ */
139
+ ttl: number().optional(),
140
+ /**
141
+ * Time in milliseconds to wait between task status requests.
142
+ */
143
+ pollInterval: number().optional()
144
+ }), TaskMetadataSchema = object({
145
+ ttl: number().optional()
146
+ }), RelatedTaskMetadataSchema = object({
147
+ taskId: string()
148
+ }), RequestMetaSchema = looseObject({
149
+ /**
150
+ * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.
151
+ */
152
+ progressToken: ProgressTokenSchema.optional(),
153
+ /**
154
+ * If specified, this request is related to the provided task.
155
+ */
156
+ [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
157
+ }), BaseRequestParamsSchema = object({
158
+ /**
159
+ * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.
160
+ */
161
+ _meta: RequestMetaSchema.optional()
162
+ }), TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({
163
+ /**
164
+ * If specified, the caller is requesting task-augmented execution for this request.
165
+ * The request will return a CreateTaskResult immediately, and the actual result can be
166
+ * retrieved later via tasks/result.
167
+ *
168
+ * Task augmentation is subject to capability negotiation - receivers MUST declare support
169
+ * for task augmentation of specific request types in their capabilities.
170
+ */
171
+ task: TaskMetadataSchema.optional()
172
+ }), isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success, RequestSchema = object({
173
+ method: string(),
174
+ params: BaseRequestParamsSchema.loose().optional()
175
+ }), NotificationsParamsSchema = object({
176
+ /**
177
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
178
+ * for notes on _meta usage.
179
+ */
180
+ _meta: RequestMetaSchema.optional()
181
+ }), NotificationSchema = object({
182
+ method: string(),
183
+ params: NotificationsParamsSchema.loose().optional()
184
+ }), ResultSchema = looseObject({
185
+ /**
186
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
187
+ * for notes on _meta usage.
188
+ */
189
+ _meta: RequestMetaSchema.optional()
190
+ }), RequestIdSchema = union([string(), number().int()]), JSONRPCRequestSchema = object({
191
+ jsonrpc: literal(JSONRPC_VERSION),
192
+ id: RequestIdSchema,
193
+ ...RequestSchema.shape
194
+ }).strict(), isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success, JSONRPCNotificationSchema = object({
195
+ jsonrpc: literal(JSONRPC_VERSION),
196
+ ...NotificationSchema.shape
197
+ }).strict(), isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success, JSONRPCResultResponseSchema = object({
198
+ jsonrpc: literal(JSONRPC_VERSION),
199
+ id: RequestIdSchema,
200
+ result: ResultSchema
201
+ }).strict(), isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;
202
+ var ErrorCode;
203
+ (function(ErrorCode2) {
204
+ ErrorCode2[ErrorCode2.ConnectionClosed = -32e3] = "ConnectionClosed", ErrorCode2[ErrorCode2.RequestTimeout = -32001] = "RequestTimeout", ErrorCode2[ErrorCode2.ParseError = -32700] = "ParseError", ErrorCode2[ErrorCode2.InvalidRequest = -32600] = "InvalidRequest", ErrorCode2[ErrorCode2.MethodNotFound = -32601] = "MethodNotFound", ErrorCode2[ErrorCode2.InvalidParams = -32602] = "InvalidParams", ErrorCode2[ErrorCode2.InternalError = -32603] = "InternalError", ErrorCode2[ErrorCode2.UrlElicitationRequired = -32042] = "UrlElicitationRequired";
205
+ })(ErrorCode || (ErrorCode = {}));
206
+ var JSONRPCErrorResponseSchema = object({
207
+ jsonrpc: literal(JSONRPC_VERSION),
208
+ id: RequestIdSchema.optional(),
209
+ error: object({
210
+ /**
211
+ * The error type that occurred.
212
+ */
213
+ code: number().int(),
214
+ /**
215
+ * A short description of the error. The message SHOULD be limited to a concise single sentence.
216
+ */
217
+ message: string(),
218
+ /**
219
+ * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
220
+ */
221
+ data: unknown().optional()
222
+ })
223
+ }).strict();
224
+ var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;
225
+ var JSONRPCMessageSchema = union([
226
+ JSONRPCRequestSchema,
227
+ JSONRPCNotificationSchema,
228
+ JSONRPCResultResponseSchema,
229
+ JSONRPCErrorResponseSchema
230
+ ]), JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]), EmptyResultSchema = ResultSchema.strict(), CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
231
+ /**
232
+ * The ID of the request to cancel.
233
+ *
234
+ * This MUST correspond to the ID of a request previously issued in the same direction.
235
+ */
236
+ requestId: RequestIdSchema.optional(),
237
+ /**
238
+ * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
239
+ */
240
+ reason: string().optional()
241
+ }), CancelledNotificationSchema = NotificationSchema.extend({
242
+ method: literal("notifications/cancelled"),
243
+ params: CancelledNotificationParamsSchema
244
+ }), IconSchema = object({
245
+ /**
246
+ * URL or data URI for the icon.
247
+ */
248
+ src: string(),
249
+ /**
250
+ * Optional MIME type for the icon.
251
+ */
252
+ mimeType: string().optional(),
253
+ /**
254
+ * Optional array of strings that specify sizes at which the icon can be used.
255
+ * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG.
256
+ *
257
+ * If not provided, the client should assume that the icon can be used at any size.
258
+ */
259
+ sizes: array(string()).optional(),
260
+ /**
261
+ * Optional specifier for the theme this icon is designed for. `light` indicates
262
+ * the icon is designed to be used with a light background, and `dark` indicates
263
+ * the icon is designed to be used with a dark background.
264
+ *
265
+ * If not provided, the client should assume the icon can be used with any theme.
266
+ */
267
+ theme: _enum(["light", "dark"]).optional()
268
+ }), IconsSchema = object({
269
+ /**
270
+ * Optional set of sized icons that the client can display in a user interface.
271
+ *
272
+ * Clients that support rendering icons MUST support at least the following MIME types:
273
+ * - `image/png` - PNG images (safe, universal compatibility)
274
+ * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)
275
+ *
276
+ * Clients that support rendering icons SHOULD also support:
277
+ * - `image/svg+xml` - SVG images (scalable but requires security precautions)
278
+ * - `image/webp` - WebP images (modern, efficient format)
279
+ */
280
+ icons: array(IconSchema).optional()
281
+ }), BaseMetadataSchema = object({
282
+ /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */
283
+ name: string(),
284
+ /**
285
+ * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,
286
+ * even by those unfamiliar with domain-specific terminology.
287
+ *
288
+ * If not provided, the name should be used for display (except for Tool,
289
+ * where `annotations.title` should be given precedence over using `name`,
290
+ * if present).
291
+ */
292
+ title: string().optional()
293
+ }), ImplementationSchema = BaseMetadataSchema.extend({
294
+ ...BaseMetadataSchema.shape,
295
+ ...IconsSchema.shape,
296
+ version: string(),
297
+ /**
298
+ * An optional URL of the website for this implementation.
299
+ */
300
+ websiteUrl: string().optional(),
301
+ /**
302
+ * An optional human-readable description of what this implementation does.
303
+ *
304
+ * This can be used by clients or servers to provide context about their purpose
305
+ * and capabilities. For example, a server might describe the types of resources
306
+ * or tools it provides, while a client might describe its intended use case.
307
+ */
308
+ description: string().optional()
309
+ }), FormElicitationCapabilitySchema = intersection(object({
310
+ applyDefaults: boolean().optional()
311
+ }), record(string(), unknown())), ElicitationCapabilitySchema = preprocess((value) => value && typeof value == "object" && !Array.isArray(value) && Object.keys(value).length === 0 ? { form: {} } : value, intersection(object({
312
+ form: FormElicitationCapabilitySchema.optional(),
313
+ url: AssertObjectSchema.optional()
314
+ }), record(string(), unknown()).optional())), ClientTasksCapabilitySchema = looseObject({
315
+ /**
316
+ * Present if the client supports listing tasks.
317
+ */
318
+ list: AssertObjectSchema.optional(),
319
+ /**
320
+ * Present if the client supports cancelling tasks.
321
+ */
322
+ cancel: AssertObjectSchema.optional(),
323
+ /**
324
+ * Capabilities for task creation on specific request types.
325
+ */
326
+ requests: looseObject({
327
+ /**
328
+ * Task support for sampling requests.
329
+ */
330
+ sampling: looseObject({
331
+ createMessage: AssertObjectSchema.optional()
332
+ }).optional(),
333
+ /**
334
+ * Task support for elicitation requests.
335
+ */
336
+ elicitation: looseObject({
337
+ create: AssertObjectSchema.optional()
338
+ }).optional()
339
+ }).optional()
340
+ }), ServerTasksCapabilitySchema = looseObject({
341
+ /**
342
+ * Present if the server supports listing tasks.
343
+ */
344
+ list: AssertObjectSchema.optional(),
345
+ /**
346
+ * Present if the server supports cancelling tasks.
347
+ */
348
+ cancel: AssertObjectSchema.optional(),
349
+ /**
350
+ * Capabilities for task creation on specific request types.
351
+ */
352
+ requests: looseObject({
353
+ /**
354
+ * Task support for tool requests.
355
+ */
356
+ tools: looseObject({
357
+ call: AssertObjectSchema.optional()
358
+ }).optional()
359
+ }).optional()
360
+ }), ClientCapabilitiesSchema = object({
361
+ /**
362
+ * Experimental, non-standard capabilities that the client supports.
363
+ */
364
+ experimental: record(string(), AssertObjectSchema).optional(),
365
+ /**
366
+ * Present if the client supports sampling from an LLM.
367
+ */
368
+ sampling: object({
369
+ /**
370
+ * Present if the client supports context inclusion via includeContext parameter.
371
+ * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it).
372
+ */
373
+ context: AssertObjectSchema.optional(),
374
+ /**
375
+ * Present if the client supports tool use via tools and toolChoice parameters.
376
+ */
377
+ tools: AssertObjectSchema.optional()
378
+ }).optional(),
379
+ /**
380
+ * Present if the client supports eliciting user input.
381
+ */
382
+ elicitation: ElicitationCapabilitySchema.optional(),
383
+ /**
384
+ * Present if the client supports listing roots.
385
+ */
386
+ roots: object({
387
+ /**
388
+ * Whether the client supports issuing notifications for changes to the roots list.
389
+ */
390
+ listChanged: boolean().optional()
391
+ }).optional(),
392
+ /**
393
+ * Present if the client supports task creation.
394
+ */
395
+ tasks: ClientTasksCapabilitySchema.optional(),
396
+ /**
397
+ * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).
398
+ */
399
+ extensions: record(string(), AssertObjectSchema).optional()
400
+ }), InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
401
+ /**
402
+ * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
403
+ */
404
+ protocolVersion: string(),
405
+ capabilities: ClientCapabilitiesSchema,
406
+ clientInfo: ImplementationSchema
407
+ }), InitializeRequestSchema = RequestSchema.extend({
408
+ method: literal("initialize"),
409
+ params: InitializeRequestParamsSchema
410
+ });
411
+ var ServerCapabilitiesSchema = object({
412
+ /**
413
+ * Experimental, non-standard capabilities that the server supports.
414
+ */
415
+ experimental: record(string(), AssertObjectSchema).optional(),
416
+ /**
417
+ * Present if the server supports sending log messages to the client.
418
+ */
419
+ logging: AssertObjectSchema.optional(),
420
+ /**
421
+ * Present if the server supports sending completions to the client.
422
+ */
423
+ completions: AssertObjectSchema.optional(),
424
+ /**
425
+ * Present if the server offers any prompt templates.
426
+ */
427
+ prompts: object({
428
+ /**
429
+ * Whether this server supports issuing notifications for changes to the prompt list.
430
+ */
431
+ listChanged: boolean().optional()
432
+ }).optional(),
433
+ /**
434
+ * Present if the server offers any resources to read.
435
+ */
436
+ resources: object({
437
+ /**
438
+ * Whether this server supports clients subscribing to resource updates.
439
+ */
440
+ subscribe: boolean().optional(),
441
+ /**
442
+ * Whether this server supports issuing notifications for changes to the resource list.
443
+ */
444
+ listChanged: boolean().optional()
445
+ }).optional(),
446
+ /**
447
+ * Present if the server offers any tools to call.
448
+ */
449
+ tools: object({
450
+ /**
451
+ * Whether this server supports issuing notifications for changes to the tool list.
452
+ */
453
+ listChanged: boolean().optional()
454
+ }).optional(),
455
+ /**
456
+ * Present if the server supports task creation.
457
+ */
458
+ tasks: ServerTasksCapabilitySchema.optional(),
459
+ /**
460
+ * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).
461
+ */
462
+ extensions: record(string(), AssertObjectSchema).optional()
463
+ }), InitializeResultSchema = ResultSchema.extend({
464
+ /**
465
+ * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.
466
+ */
467
+ protocolVersion: string(),
468
+ capabilities: ServerCapabilitiesSchema,
469
+ serverInfo: ImplementationSchema,
470
+ /**
471
+ * Instructions describing how to use the server and its features.
472
+ *
473
+ * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.
474
+ */
475
+ instructions: string().optional()
476
+ }), InitializedNotificationSchema = NotificationSchema.extend({
477
+ method: literal("notifications/initialized"),
478
+ params: NotificationsParamsSchema.optional()
479
+ }), isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success, PingRequestSchema = RequestSchema.extend({
480
+ method: literal("ping"),
481
+ params: BaseRequestParamsSchema.optional()
482
+ }), ProgressSchema = object({
483
+ /**
484
+ * The progress thus far. This should increase every time progress is made, even if the total is unknown.
485
+ */
486
+ progress: number(),
487
+ /**
488
+ * Total number of items to process (or total progress required), if known.
489
+ */
490
+ total: optional(number()),
491
+ /**
492
+ * An optional message describing the current progress.
493
+ */
494
+ message: optional(string())
495
+ }), ProgressNotificationParamsSchema = object({
496
+ ...NotificationsParamsSchema.shape,
497
+ ...ProgressSchema.shape,
498
+ /**
499
+ * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
500
+ */
501
+ progressToken: ProgressTokenSchema
502
+ }), ProgressNotificationSchema = NotificationSchema.extend({
503
+ method: literal("notifications/progress"),
504
+ params: ProgressNotificationParamsSchema
505
+ }), PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({
506
+ /**
507
+ * An opaque token representing the current pagination position.
508
+ * If provided, the server should return results starting after this cursor.
509
+ */
510
+ cursor: CursorSchema.optional()
511
+ }), PaginatedRequestSchema = RequestSchema.extend({
512
+ params: PaginatedRequestParamsSchema.optional()
513
+ }), PaginatedResultSchema = ResultSchema.extend({
514
+ /**
515
+ * An opaque token representing the pagination position after the last returned result.
516
+ * If present, there may be more results available.
517
+ */
518
+ nextCursor: CursorSchema.optional()
519
+ }), TaskStatusSchema = _enum(["working", "input_required", "completed", "failed", "cancelled"]), TaskSchema = object({
520
+ taskId: string(),
521
+ status: TaskStatusSchema,
522
+ /**
523
+ * Time in milliseconds to keep task results available after completion.
524
+ * If null, the task has unlimited lifetime until manually cleaned up.
525
+ */
526
+ ttl: union([number(), _null()]),
527
+ /**
528
+ * ISO 8601 timestamp when the task was created.
529
+ */
530
+ createdAt: string(),
531
+ /**
532
+ * ISO 8601 timestamp when the task was last updated.
533
+ */
534
+ lastUpdatedAt: string(),
535
+ pollInterval: optional(number()),
536
+ /**
537
+ * Optional diagnostic message for failed tasks or other status information.
538
+ */
539
+ statusMessage: optional(string())
540
+ }), CreateTaskResultSchema = ResultSchema.extend({
541
+ task: TaskSchema
542
+ }), TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema), TaskStatusNotificationSchema = NotificationSchema.extend({
543
+ method: literal("notifications/tasks/status"),
544
+ params: TaskStatusNotificationParamsSchema
545
+ }), GetTaskRequestSchema = RequestSchema.extend({
546
+ method: literal("tasks/get"),
547
+ params: BaseRequestParamsSchema.extend({
548
+ taskId: string()
549
+ })
550
+ }), GetTaskResultSchema = ResultSchema.merge(TaskSchema), GetTaskPayloadRequestSchema = RequestSchema.extend({
551
+ method: literal("tasks/result"),
552
+ params: BaseRequestParamsSchema.extend({
553
+ taskId: string()
554
+ })
555
+ }), GetTaskPayloadResultSchema = ResultSchema.loose(), ListTasksRequestSchema = PaginatedRequestSchema.extend({
556
+ method: literal("tasks/list")
557
+ }), ListTasksResultSchema = PaginatedResultSchema.extend({
558
+ tasks: array(TaskSchema)
559
+ }), CancelTaskRequestSchema = RequestSchema.extend({
560
+ method: literal("tasks/cancel"),
561
+ params: BaseRequestParamsSchema.extend({
562
+ taskId: string()
563
+ })
564
+ }), CancelTaskResultSchema = ResultSchema.merge(TaskSchema), ResourceContentsSchema = object({
565
+ /**
566
+ * The URI of this resource.
567
+ */
568
+ uri: string(),
569
+ /**
570
+ * The MIME type of this resource, if known.
571
+ */
572
+ mimeType: optional(string()),
573
+ /**
574
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
575
+ * for notes on _meta usage.
576
+ */
577
+ _meta: record(string(), unknown()).optional()
578
+ }), TextResourceContentsSchema = ResourceContentsSchema.extend({
579
+ /**
580
+ * The text of the item. This must only be set if the item can actually be represented as text (not binary data).
581
+ */
582
+ text: string()
583
+ }), Base64Schema = string().refine((val) => {
584
+ try {
585
+ return atob(val), !0;
586
+ } catch {
587
+ return !1;
588
+ }
589
+ }, { message: "Invalid Base64 string" }), BlobResourceContentsSchema = ResourceContentsSchema.extend({
590
+ /**
591
+ * A base64-encoded string representing the binary data of the item.
592
+ */
593
+ blob: Base64Schema
594
+ }), RoleSchema = _enum(["user", "assistant"]), AnnotationsSchema = object({
595
+ /**
596
+ * Intended audience(s) for the resource.
597
+ */
598
+ audience: array(RoleSchema).optional(),
599
+ /**
600
+ * Importance hint for the resource, from 0 (least) to 1 (most).
601
+ */
602
+ priority: number().min(0).max(1).optional(),
603
+ /**
604
+ * ISO 8601 timestamp for the most recent modification.
605
+ */
606
+ lastModified: iso_exports.datetime({ offset: !0 }).optional()
607
+ }), ResourceSchema = object({
608
+ ...BaseMetadataSchema.shape,
609
+ ...IconsSchema.shape,
610
+ /**
611
+ * The URI of this resource.
612
+ */
613
+ uri: string(),
614
+ /**
615
+ * A description of what this resource represents.
616
+ *
617
+ * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
618
+ */
619
+ description: optional(string()),
620
+ /**
621
+ * The MIME type of this resource, if known.
622
+ */
623
+ mimeType: optional(string()),
624
+ /**
625
+ * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.
626
+ *
627
+ * This can be used by Hosts to display file sizes and estimate context window usage.
628
+ */
629
+ size: optional(number()),
630
+ /**
631
+ * Optional annotations for the client.
632
+ */
633
+ annotations: AnnotationsSchema.optional(),
634
+ /**
635
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
636
+ * for notes on _meta usage.
637
+ */
638
+ _meta: optional(looseObject({}))
639
+ }), ResourceTemplateSchema = object({
640
+ ...BaseMetadataSchema.shape,
641
+ ...IconsSchema.shape,
642
+ /**
643
+ * A URI template (according to RFC 6570) that can be used to construct resource URIs.
644
+ */
645
+ uriTemplate: string(),
646
+ /**
647
+ * A description of what this template is for.
648
+ *
649
+ * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
650
+ */
651
+ description: optional(string()),
652
+ /**
653
+ * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.
654
+ */
655
+ mimeType: optional(string()),
656
+ /**
657
+ * Optional annotations for the client.
658
+ */
659
+ annotations: AnnotationsSchema.optional(),
660
+ /**
661
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
662
+ * for notes on _meta usage.
663
+ */
664
+ _meta: optional(looseObject({}))
665
+ }), ListResourcesRequestSchema = PaginatedRequestSchema.extend({
666
+ method: literal("resources/list")
667
+ }), ListResourcesResultSchema = PaginatedResultSchema.extend({
668
+ resources: array(ResourceSchema)
669
+ }), ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
670
+ method: literal("resources/templates/list")
671
+ }), ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
672
+ resourceTemplates: array(ResourceTemplateSchema)
673
+ }), ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({
674
+ /**
675
+ * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.
676
+ *
677
+ * @format uri
678
+ */
679
+ uri: string()
680
+ }), ReadResourceRequestParamsSchema = ResourceRequestParamsSchema, ReadResourceRequestSchema = RequestSchema.extend({
681
+ method: literal("resources/read"),
682
+ params: ReadResourceRequestParamsSchema
683
+ }), ReadResourceResultSchema = ResultSchema.extend({
684
+ contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema]))
685
+ }), ResourceListChangedNotificationSchema = NotificationSchema.extend({
686
+ method: literal("notifications/resources/list_changed"),
687
+ params: NotificationsParamsSchema.optional()
688
+ }), SubscribeRequestParamsSchema = ResourceRequestParamsSchema, SubscribeRequestSchema = RequestSchema.extend({
689
+ method: literal("resources/subscribe"),
690
+ params: SubscribeRequestParamsSchema
691
+ }), UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema, UnsubscribeRequestSchema = RequestSchema.extend({
692
+ method: literal("resources/unsubscribe"),
693
+ params: UnsubscribeRequestParamsSchema
694
+ }), ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({
695
+ /**
696
+ * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
697
+ */
698
+ uri: string()
699
+ }), ResourceUpdatedNotificationSchema = NotificationSchema.extend({
700
+ method: literal("notifications/resources/updated"),
701
+ params: ResourceUpdatedNotificationParamsSchema
702
+ }), PromptArgumentSchema = object({
703
+ /**
704
+ * The name of the argument.
705
+ */
706
+ name: string(),
707
+ /**
708
+ * A human-readable description of the argument.
709
+ */
710
+ description: optional(string()),
711
+ /**
712
+ * Whether this argument must be provided.
713
+ */
714
+ required: optional(boolean())
715
+ }), PromptSchema = object({
716
+ ...BaseMetadataSchema.shape,
717
+ ...IconsSchema.shape,
718
+ /**
719
+ * An optional description of what this prompt provides
720
+ */
721
+ description: optional(string()),
722
+ /**
723
+ * A list of arguments to use for templating the prompt.
724
+ */
725
+ arguments: optional(array(PromptArgumentSchema)),
726
+ /**
727
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
728
+ * for notes on _meta usage.
729
+ */
730
+ _meta: optional(looseObject({}))
731
+ }), ListPromptsRequestSchema = PaginatedRequestSchema.extend({
732
+ method: literal("prompts/list")
733
+ }), ListPromptsResultSchema = PaginatedResultSchema.extend({
734
+ prompts: array(PromptSchema)
735
+ }), GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
736
+ /**
737
+ * The name of the prompt or prompt template.
738
+ */
739
+ name: string(),
740
+ /**
741
+ * Arguments to use for templating the prompt.
742
+ */
743
+ arguments: record(string(), string()).optional()
744
+ }), GetPromptRequestSchema = RequestSchema.extend({
745
+ method: literal("prompts/get"),
746
+ params: GetPromptRequestParamsSchema
747
+ }), TextContentSchema = object({
748
+ type: literal("text"),
749
+ /**
750
+ * The text content of the message.
751
+ */
752
+ text: string(),
753
+ /**
754
+ * Optional annotations for the client.
755
+ */
756
+ annotations: AnnotationsSchema.optional(),
757
+ /**
758
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
759
+ * for notes on _meta usage.
760
+ */
761
+ _meta: record(string(), unknown()).optional()
762
+ }), ImageContentSchema = object({
763
+ type: literal("image"),
764
+ /**
765
+ * The base64-encoded image data.
766
+ */
767
+ data: Base64Schema,
768
+ /**
769
+ * The MIME type of the image. Different providers may support different image types.
770
+ */
771
+ mimeType: string(),
772
+ /**
773
+ * Optional annotations for the client.
774
+ */
775
+ annotations: AnnotationsSchema.optional(),
776
+ /**
777
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
778
+ * for notes on _meta usage.
779
+ */
780
+ _meta: record(string(), unknown()).optional()
781
+ }), AudioContentSchema = object({
782
+ type: literal("audio"),
783
+ /**
784
+ * The base64-encoded audio data.
785
+ */
786
+ data: Base64Schema,
787
+ /**
788
+ * The MIME type of the audio. Different providers may support different audio types.
789
+ */
790
+ mimeType: string(),
791
+ /**
792
+ * Optional annotations for the client.
793
+ */
794
+ annotations: AnnotationsSchema.optional(),
795
+ /**
796
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
797
+ * for notes on _meta usage.
798
+ */
799
+ _meta: record(string(), unknown()).optional()
800
+ }), ToolUseContentSchema = object({
801
+ type: literal("tool_use"),
802
+ /**
803
+ * The name of the tool to invoke.
804
+ * Must match a tool name from the request's tools array.
805
+ */
806
+ name: string(),
807
+ /**
808
+ * Unique identifier for this tool call.
809
+ * Used to correlate with ToolResultContent in subsequent messages.
810
+ */
811
+ id: string(),
812
+ /**
813
+ * Arguments to pass to the tool.
814
+ * Must conform to the tool's inputSchema.
815
+ */
816
+ input: record(string(), unknown()),
817
+ /**
818
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
819
+ * for notes on _meta usage.
820
+ */
821
+ _meta: record(string(), unknown()).optional()
822
+ }), EmbeddedResourceSchema = object({
823
+ type: literal("resource"),
824
+ resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
825
+ /**
826
+ * Optional annotations for the client.
827
+ */
828
+ annotations: AnnotationsSchema.optional(),
829
+ /**
830
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
831
+ * for notes on _meta usage.
832
+ */
833
+ _meta: record(string(), unknown()).optional()
834
+ }), ResourceLinkSchema = ResourceSchema.extend({
835
+ type: literal("resource_link")
836
+ }), ContentBlockSchema = union([
837
+ TextContentSchema,
838
+ ImageContentSchema,
839
+ AudioContentSchema,
840
+ ResourceLinkSchema,
841
+ EmbeddedResourceSchema
842
+ ]), PromptMessageSchema = object({
843
+ role: RoleSchema,
844
+ content: ContentBlockSchema
845
+ }), GetPromptResultSchema = ResultSchema.extend({
846
+ /**
847
+ * An optional description for the prompt.
848
+ */
849
+ description: string().optional(),
850
+ messages: array(PromptMessageSchema)
851
+ }), PromptListChangedNotificationSchema = NotificationSchema.extend({
852
+ method: literal("notifications/prompts/list_changed"),
853
+ params: NotificationsParamsSchema.optional()
854
+ }), ToolAnnotationsSchema = object({
855
+ /**
856
+ * A human-readable title for the tool.
857
+ */
858
+ title: string().optional(),
859
+ /**
860
+ * If true, the tool does not modify its environment.
861
+ *
862
+ * Default: false
863
+ */
864
+ readOnlyHint: boolean().optional(),
865
+ /**
866
+ * If true, the tool may perform destructive updates to its environment.
867
+ * If false, the tool performs only additive updates.
868
+ *
869
+ * (This property is meaningful only when `readOnlyHint == false`)
870
+ *
871
+ * Default: true
872
+ */
873
+ destructiveHint: boolean().optional(),
874
+ /**
875
+ * If true, calling the tool repeatedly with the same arguments
876
+ * will have no additional effect on the its environment.
877
+ *
878
+ * (This property is meaningful only when `readOnlyHint == false`)
879
+ *
880
+ * Default: false
881
+ */
882
+ idempotentHint: boolean().optional(),
883
+ /**
884
+ * If true, this tool may interact with an "open world" of external
885
+ * entities. If false, the tool's domain of interaction is closed.
886
+ * For example, the world of a web search tool is open, whereas that
887
+ * of a memory tool is not.
888
+ *
889
+ * Default: true
890
+ */
891
+ openWorldHint: boolean().optional()
892
+ }), ToolExecutionSchema = object({
893
+ /**
894
+ * Indicates the tool's preference for task-augmented execution.
895
+ * - "required": Clients MUST invoke the tool as a task
896
+ * - "optional": Clients MAY invoke the tool as a task or normal request
897
+ * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task
898
+ *
899
+ * If not present, defaults to "forbidden".
900
+ */
901
+ taskSupport: _enum(["required", "optional", "forbidden"]).optional()
902
+ }), ToolSchema = object({
903
+ ...BaseMetadataSchema.shape,
904
+ ...IconsSchema.shape,
905
+ /**
906
+ * A human-readable description of the tool.
907
+ */
908
+ description: string().optional(),
909
+ /**
910
+ * A JSON Schema 2020-12 object defining the expected parameters for the tool.
911
+ * Must have type: 'object' at the root level per MCP spec.
912
+ */
913
+ inputSchema: object({
914
+ type: literal("object"),
915
+ properties: record(string(), AssertObjectSchema).optional(),
916
+ required: array(string()).optional()
917
+ }).catchall(unknown()),
918
+ /**
919
+ * An optional JSON Schema 2020-12 object defining the structure of the tool's output
920
+ * returned in the structuredContent field of a CallToolResult.
921
+ * Must have type: 'object' at the root level per MCP spec.
922
+ */
923
+ outputSchema: object({
924
+ type: literal("object"),
925
+ properties: record(string(), AssertObjectSchema).optional(),
926
+ required: array(string()).optional()
927
+ }).catchall(unknown()).optional(),
928
+ /**
929
+ * Optional additional tool information.
930
+ */
931
+ annotations: ToolAnnotationsSchema.optional(),
932
+ /**
933
+ * Execution-related properties for this tool.
934
+ */
935
+ execution: ToolExecutionSchema.optional(),
936
+ /**
937
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
938
+ * for notes on _meta usage.
939
+ */
940
+ _meta: record(string(), unknown()).optional()
941
+ }), ListToolsRequestSchema = PaginatedRequestSchema.extend({
942
+ method: literal("tools/list")
943
+ }), ListToolsResultSchema = PaginatedResultSchema.extend({
944
+ tools: array(ToolSchema)
945
+ }), CallToolResultSchema = ResultSchema.extend({
946
+ /**
947
+ * A list of content objects that represent the result of the tool call.
948
+ *
949
+ * If the Tool does not define an outputSchema, this field MUST be present in the result.
950
+ * For backwards compatibility, this field is always present, but it may be empty.
951
+ */
952
+ content: array(ContentBlockSchema).default([]),
953
+ /**
954
+ * An object containing structured tool output.
955
+ *
956
+ * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.
957
+ */
958
+ structuredContent: record(string(), unknown()).optional(),
959
+ /**
960
+ * Whether the tool call ended in an error.
961
+ *
962
+ * If not set, this is assumed to be false (the call was successful).
963
+ *
964
+ * Any errors that originate from the tool SHOULD be reported inside the result
965
+ * object, with `isError` set to true, _not_ as an MCP protocol-level error
966
+ * response. Otherwise, the LLM would not be able to see that an error occurred
967
+ * and self-correct.
968
+ *
969
+ * However, any errors in _finding_ the tool, an error indicating that the
970
+ * server does not support tool calls, or any other exceptional conditions,
971
+ * should be reported as an MCP error response.
972
+ */
973
+ isError: boolean().optional()
974
+ }), CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({
975
+ toolResult: unknown()
976
+ })), CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
977
+ /**
978
+ * The name of the tool to call.
979
+ */
980
+ name: string(),
981
+ /**
982
+ * Arguments to pass to the tool.
983
+ */
984
+ arguments: record(string(), unknown()).optional()
985
+ }), CallToolRequestSchema = RequestSchema.extend({
986
+ method: literal("tools/call"),
987
+ params: CallToolRequestParamsSchema
988
+ }), ToolListChangedNotificationSchema = NotificationSchema.extend({
989
+ method: literal("notifications/tools/list_changed"),
990
+ params: NotificationsParamsSchema.optional()
991
+ }), ListChangedOptionsBaseSchema = object({
992
+ /**
993
+ * If true, the list will be refreshed automatically when a list changed notification is received.
994
+ * The callback will be called with the updated list.
995
+ *
996
+ * If false, the callback will be called with null items, allowing manual refresh.
997
+ *
998
+ * @default true
999
+ */
1000
+ autoRefresh: boolean().default(!0),
1001
+ /**
1002
+ * Debounce time in milliseconds for list changed notification processing.
1003
+ *
1004
+ * Multiple notifications received within this timeframe will only trigger one refresh.
1005
+ * Set to 0 to disable debouncing.
1006
+ *
1007
+ * @default 300
1008
+ */
1009
+ debounceMs: number().int().nonnegative().default(300)
1010
+ }), LoggingLevelSchema = _enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]), SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({
1011
+ /**
1012
+ * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.
1013
+ */
1014
+ level: LoggingLevelSchema
1015
+ }), SetLevelRequestSchema = RequestSchema.extend({
1016
+ method: literal("logging/setLevel"),
1017
+ params: SetLevelRequestParamsSchema
1018
+ }), LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({
1019
+ /**
1020
+ * The severity of this log message.
1021
+ */
1022
+ level: LoggingLevelSchema,
1023
+ /**
1024
+ * An optional name of the logger issuing this message.
1025
+ */
1026
+ logger: string().optional(),
1027
+ /**
1028
+ * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
1029
+ */
1030
+ data: unknown()
1031
+ }), LoggingMessageNotificationSchema = NotificationSchema.extend({
1032
+ method: literal("notifications/message"),
1033
+ params: LoggingMessageNotificationParamsSchema
1034
+ }), ModelHintSchema = object({
1035
+ /**
1036
+ * A hint for a model name.
1037
+ */
1038
+ name: string().optional()
1039
+ }), ModelPreferencesSchema = object({
1040
+ /**
1041
+ * Optional hints to use for model selection.
1042
+ */
1043
+ hints: array(ModelHintSchema).optional(),
1044
+ /**
1045
+ * How much to prioritize cost when selecting a model.
1046
+ */
1047
+ costPriority: number().min(0).max(1).optional(),
1048
+ /**
1049
+ * How much to prioritize sampling speed (latency) when selecting a model.
1050
+ */
1051
+ speedPriority: number().min(0).max(1).optional(),
1052
+ /**
1053
+ * How much to prioritize intelligence and capabilities when selecting a model.
1054
+ */
1055
+ intelligencePriority: number().min(0).max(1).optional()
1056
+ }), ToolChoiceSchema = object({
1057
+ /**
1058
+ * Controls when tools are used:
1059
+ * - "auto": Model decides whether to use tools (default)
1060
+ * - "required": Model MUST use at least one tool before completing
1061
+ * - "none": Model MUST NOT use any tools
1062
+ */
1063
+ mode: _enum(["auto", "required", "none"]).optional()
1064
+ }), ToolResultContentSchema = object({
1065
+ type: literal("tool_result"),
1066
+ toolUseId: string().describe("The unique identifier for the corresponding tool call."),
1067
+ content: array(ContentBlockSchema).default([]),
1068
+ structuredContent: object({}).loose().optional(),
1069
+ isError: boolean().optional(),
1070
+ /**
1071
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
1072
+ * for notes on _meta usage.
1073
+ */
1074
+ _meta: record(string(), unknown()).optional()
1075
+ }), SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]), SamplingMessageContentBlockSchema = discriminatedUnion("type", [
1076
+ TextContentSchema,
1077
+ ImageContentSchema,
1078
+ AudioContentSchema,
1079
+ ToolUseContentSchema,
1080
+ ToolResultContentSchema
1081
+ ]), SamplingMessageSchema = object({
1082
+ role: RoleSchema,
1083
+ content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),
1084
+ /**
1085
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
1086
+ * for notes on _meta usage.
1087
+ */
1088
+ _meta: record(string(), unknown()).optional()
1089
+ }), CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
1090
+ messages: array(SamplingMessageSchema),
1091
+ /**
1092
+ * The server's preferences for which model to select. The client MAY modify or omit this request.
1093
+ */
1094
+ modelPreferences: ModelPreferencesSchema.optional(),
1095
+ /**
1096
+ * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
1097
+ */
1098
+ systemPrompt: string().optional(),
1099
+ /**
1100
+ * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.
1101
+ * The client MAY ignore this request.
1102
+ *
1103
+ * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client
1104
+ * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.
1105
+ */
1106
+ includeContext: _enum(["none", "thisServer", "allServers"]).optional(),
1107
+ temperature: number().optional(),
1108
+ /**
1109
+ * The requested maximum number of tokens to sample (to prevent runaway completions).
1110
+ *
1111
+ * The client MAY choose to sample fewer tokens than the requested maximum.
1112
+ */
1113
+ maxTokens: number().int(),
1114
+ stopSequences: array(string()).optional(),
1115
+ /**
1116
+ * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
1117
+ */
1118
+ metadata: AssertObjectSchema.optional(),
1119
+ /**
1120
+ * Tools that the model may use during generation.
1121
+ * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
1122
+ */
1123
+ tools: array(ToolSchema).optional(),
1124
+ /**
1125
+ * Controls how the model uses tools.
1126
+ * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
1127
+ * Default is `{ mode: "auto" }`.
1128
+ */
1129
+ toolChoice: ToolChoiceSchema.optional()
1130
+ }), CreateMessageRequestSchema = RequestSchema.extend({
1131
+ method: literal("sampling/createMessage"),
1132
+ params: CreateMessageRequestParamsSchema
1133
+ }), CreateMessageResultSchema = ResultSchema.extend({
1134
+ /**
1135
+ * The name of the model that generated the message.
1136
+ */
1137
+ model: string(),
1138
+ /**
1139
+ * The reason why sampling stopped, if known.
1140
+ *
1141
+ * Standard values:
1142
+ * - "endTurn": Natural end of the assistant's turn
1143
+ * - "stopSequence": A stop sequence was encountered
1144
+ * - "maxTokens": Maximum token limit was reached
1145
+ *
1146
+ * This field is an open string to allow for provider-specific stop reasons.
1147
+ */
1148
+ stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens"]).or(string())),
1149
+ role: RoleSchema,
1150
+ /**
1151
+ * Response content. Single content block (text, image, or audio).
1152
+ */
1153
+ content: SamplingContentSchema
1154
+ }), CreateMessageResultWithToolsSchema = ResultSchema.extend({
1155
+ /**
1156
+ * The name of the model that generated the message.
1157
+ */
1158
+ model: string(),
1159
+ /**
1160
+ * The reason why sampling stopped, if known.
1161
+ *
1162
+ * Standard values:
1163
+ * - "endTurn": Natural end of the assistant's turn
1164
+ * - "stopSequence": A stop sequence was encountered
1165
+ * - "maxTokens": Maximum token limit was reached
1166
+ * - "toolUse": The model wants to use one or more tools
1167
+ *
1168
+ * This field is an open string to allow for provider-specific stop reasons.
1169
+ */
1170
+ stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string())),
1171
+ role: RoleSchema,
1172
+ /**
1173
+ * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse".
1174
+ */
1175
+ content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])
1176
+ }), BooleanSchemaSchema = object({
1177
+ type: literal("boolean"),
1178
+ title: string().optional(),
1179
+ description: string().optional(),
1180
+ default: boolean().optional()
1181
+ }), StringSchemaSchema = object({
1182
+ type: literal("string"),
1183
+ title: string().optional(),
1184
+ description: string().optional(),
1185
+ minLength: number().optional(),
1186
+ maxLength: number().optional(),
1187
+ format: _enum(["email", "uri", "date", "date-time"]).optional(),
1188
+ default: string().optional()
1189
+ }), NumberSchemaSchema = object({
1190
+ type: _enum(["number", "integer"]),
1191
+ title: string().optional(),
1192
+ description: string().optional(),
1193
+ minimum: number().optional(),
1194
+ maximum: number().optional(),
1195
+ default: number().optional()
1196
+ }), UntitledSingleSelectEnumSchemaSchema = object({
1197
+ type: literal("string"),
1198
+ title: string().optional(),
1199
+ description: string().optional(),
1200
+ enum: array(string()),
1201
+ default: string().optional()
1202
+ }), TitledSingleSelectEnumSchemaSchema = object({
1203
+ type: literal("string"),
1204
+ title: string().optional(),
1205
+ description: string().optional(),
1206
+ oneOf: array(object({
1207
+ const: string(),
1208
+ title: string()
1209
+ })),
1210
+ default: string().optional()
1211
+ }), LegacyTitledEnumSchemaSchema = object({
1212
+ type: literal("string"),
1213
+ title: string().optional(),
1214
+ description: string().optional(),
1215
+ enum: array(string()),
1216
+ enumNames: array(string()).optional(),
1217
+ default: string().optional()
1218
+ }), SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]), UntitledMultiSelectEnumSchemaSchema = object({
1219
+ type: literal("array"),
1220
+ title: string().optional(),
1221
+ description: string().optional(),
1222
+ minItems: number().optional(),
1223
+ maxItems: number().optional(),
1224
+ items: object({
1225
+ type: literal("string"),
1226
+ enum: array(string())
1227
+ }),
1228
+ default: array(string()).optional()
1229
+ }), TitledMultiSelectEnumSchemaSchema = object({
1230
+ type: literal("array"),
1231
+ title: string().optional(),
1232
+ description: string().optional(),
1233
+ minItems: number().optional(),
1234
+ maxItems: number().optional(),
1235
+ items: object({
1236
+ anyOf: array(object({
1237
+ const: string(),
1238
+ title: string()
1239
+ }))
1240
+ }),
1241
+ default: array(string()).optional()
1242
+ }), MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]), EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]), PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]), ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
1243
+ /**
1244
+ * The elicitation mode.
1245
+ *
1246
+ * Optional for backward compatibility. Clients MUST treat missing mode as "form".
1247
+ */
1248
+ mode: literal("form").optional(),
1249
+ /**
1250
+ * The message to present to the user describing what information is being requested.
1251
+ */
1252
+ message: string(),
1253
+ /**
1254
+ * A restricted subset of JSON Schema.
1255
+ * Only top-level properties are allowed, without nesting.
1256
+ */
1257
+ requestedSchema: object({
1258
+ type: literal("object"),
1259
+ properties: record(string(), PrimitiveSchemaDefinitionSchema),
1260
+ required: array(string()).optional()
1261
+ })
1262
+ }), ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({
1263
+ /**
1264
+ * The elicitation mode.
1265
+ */
1266
+ mode: literal("url"),
1267
+ /**
1268
+ * The message to present to the user explaining why the interaction is needed.
1269
+ */
1270
+ message: string(),
1271
+ /**
1272
+ * The ID of the elicitation, which must be unique within the context of the server.
1273
+ * The client MUST treat this ID as an opaque value.
1274
+ */
1275
+ elicitationId: string(),
1276
+ /**
1277
+ * The URL that the user should navigate to.
1278
+ */
1279
+ url: string().url()
1280
+ }), ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]), ElicitRequestSchema = RequestSchema.extend({
1281
+ method: literal("elicitation/create"),
1282
+ params: ElicitRequestParamsSchema
1283
+ }), ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({
1284
+ /**
1285
+ * The ID of the elicitation that completed.
1286
+ */
1287
+ elicitationId: string()
1288
+ }), ElicitationCompleteNotificationSchema = NotificationSchema.extend({
1289
+ method: literal("notifications/elicitation/complete"),
1290
+ params: ElicitationCompleteNotificationParamsSchema
1291
+ }), ElicitResultSchema = ResultSchema.extend({
1292
+ /**
1293
+ * The user action in response to the elicitation.
1294
+ * - "accept": User submitted the form/confirmed the action
1295
+ * - "decline": User explicitly decline the action
1296
+ * - "cancel": User dismissed without making an explicit choice
1297
+ */
1298
+ action: _enum(["accept", "decline", "cancel"]),
1299
+ /**
1300
+ * The submitted form data, only present when action is "accept".
1301
+ * Contains values matching the requested schema.
1302
+ * Per MCP spec, content is "typically omitted" for decline/cancel actions.
1303
+ * We normalize null to undefined for leniency while maintaining type compatibility.
1304
+ */
1305
+ content: preprocess((val) => val === null ? void 0 : val, record(string(), union([string(), number(), boolean(), array(string())])).optional())
1306
+ }), ResourceTemplateReferenceSchema = object({
1307
+ type: literal("ref/resource"),
1308
+ /**
1309
+ * The URI or URI template of the resource.
1310
+ */
1311
+ uri: string()
1312
+ });
1313
+ var PromptReferenceSchema = object({
1314
+ type: literal("ref/prompt"),
1315
+ /**
1316
+ * The name of the prompt or prompt template
1317
+ */
1318
+ name: string()
1319
+ }), CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
1320
+ ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
1321
+ /**
1322
+ * The argument's information
1323
+ */
1324
+ argument: object({
1325
+ /**
1326
+ * The name of the argument
1327
+ */
1328
+ name: string(),
1329
+ /**
1330
+ * The value of the argument to use for completion matching.
1331
+ */
1332
+ value: string()
1333
+ }),
1334
+ context: object({
1335
+ /**
1336
+ * Previously-resolved variables in a URI template or prompt.
1337
+ */
1338
+ arguments: record(string(), string()).optional()
1339
+ }).optional()
1340
+ }), CompleteRequestSchema = RequestSchema.extend({
1341
+ method: literal("completion/complete"),
1342
+ params: CompleteRequestParamsSchema
1343
+ });
1344
+ var CompleteResultSchema = ResultSchema.extend({
1345
+ completion: looseObject({
1346
+ /**
1347
+ * An array of completion values. Must not exceed 100 items.
1348
+ */
1349
+ values: array(string()).max(100),
1350
+ /**
1351
+ * The total number of completion options available. This can exceed the number of values actually sent in the response.
1352
+ */
1353
+ total: optional(number().int()),
1354
+ /**
1355
+ * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
1356
+ */
1357
+ hasMore: optional(boolean())
1358
+ })
1359
+ }), RootSchema = object({
1360
+ /**
1361
+ * The URI identifying the root. This *must* start with file:// for now.
1362
+ */
1363
+ uri: string().startsWith("file://"),
1364
+ /**
1365
+ * An optional name for the root.
1366
+ */
1367
+ name: string().optional(),
1368
+ /**
1369
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
1370
+ * for notes on _meta usage.
1371
+ */
1372
+ _meta: record(string(), unknown()).optional()
1373
+ }), ListRootsRequestSchema = RequestSchema.extend({
1374
+ method: literal("roots/list"),
1375
+ params: BaseRequestParamsSchema.optional()
1376
+ }), ListRootsResultSchema = ResultSchema.extend({
1377
+ roots: array(RootSchema)
1378
+ }), RootsListChangedNotificationSchema = NotificationSchema.extend({
1379
+ method: literal("notifications/roots/list_changed"),
1380
+ params: NotificationsParamsSchema.optional()
1381
+ }), ClientRequestSchema = union([
1382
+ PingRequestSchema,
1383
+ InitializeRequestSchema,
1384
+ CompleteRequestSchema,
1385
+ SetLevelRequestSchema,
1386
+ GetPromptRequestSchema,
1387
+ ListPromptsRequestSchema,
1388
+ ListResourcesRequestSchema,
1389
+ ListResourceTemplatesRequestSchema,
1390
+ ReadResourceRequestSchema,
1391
+ SubscribeRequestSchema,
1392
+ UnsubscribeRequestSchema,
1393
+ CallToolRequestSchema,
1394
+ ListToolsRequestSchema,
1395
+ GetTaskRequestSchema,
1396
+ GetTaskPayloadRequestSchema,
1397
+ ListTasksRequestSchema,
1398
+ CancelTaskRequestSchema
1399
+ ]), ClientNotificationSchema = union([
1400
+ CancelledNotificationSchema,
1401
+ ProgressNotificationSchema,
1402
+ InitializedNotificationSchema,
1403
+ RootsListChangedNotificationSchema,
1404
+ TaskStatusNotificationSchema
1405
+ ]), ClientResultSchema = union([
1406
+ EmptyResultSchema,
1407
+ CreateMessageResultSchema,
1408
+ CreateMessageResultWithToolsSchema,
1409
+ ElicitResultSchema,
1410
+ ListRootsResultSchema,
1411
+ GetTaskResultSchema,
1412
+ ListTasksResultSchema,
1413
+ CreateTaskResultSchema
1414
+ ]), ServerRequestSchema = union([
1415
+ PingRequestSchema,
1416
+ CreateMessageRequestSchema,
1417
+ ElicitRequestSchema,
1418
+ ListRootsRequestSchema,
1419
+ GetTaskRequestSchema,
1420
+ GetTaskPayloadRequestSchema,
1421
+ ListTasksRequestSchema,
1422
+ CancelTaskRequestSchema
1423
+ ]), ServerNotificationSchema = union([
1424
+ CancelledNotificationSchema,
1425
+ ProgressNotificationSchema,
1426
+ LoggingMessageNotificationSchema,
1427
+ ResourceUpdatedNotificationSchema,
1428
+ ResourceListChangedNotificationSchema,
1429
+ ToolListChangedNotificationSchema,
1430
+ PromptListChangedNotificationSchema,
1431
+ TaskStatusNotificationSchema,
1432
+ ElicitationCompleteNotificationSchema
1433
+ ]), ServerResultSchema = union([
1434
+ EmptyResultSchema,
1435
+ InitializeResultSchema,
1436
+ CompleteResultSchema,
1437
+ GetPromptResultSchema,
1438
+ ListPromptsResultSchema,
1439
+ ListResourcesResultSchema,
1440
+ ListResourceTemplatesResultSchema,
1441
+ ReadResourceResultSchema,
1442
+ CallToolResultSchema,
1443
+ ListToolsResultSchema,
1444
+ GetTaskResultSchema,
1445
+ ListTasksResultSchema,
1446
+ CreateTaskResultSchema
1447
+ ]), McpError = class _McpError extends Error {
1448
+ constructor(code, message, data) {
1449
+ super(`MCP error ${code}: ${message}`), this.code = code, this.data = data, this.name = "McpError";
1450
+ }
1451
+ /**
1452
+ * Factory method to create the appropriate error type based on the error code and data
1453
+ */
1454
+ static fromError(code, message, data) {
1455
+ if (code === ErrorCode.UrlElicitationRequired && data) {
1456
+ let errorData = data;
1457
+ if (errorData.elicitations)
1458
+ return new UrlElicitationRequiredError(errorData.elicitations, message);
1459
+ }
1460
+ return new _McpError(code, message, data);
1461
+ }
1462
+ }, UrlElicitationRequiredError = class extends McpError {
1463
+ constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {
1464
+ super(ErrorCode.UrlElicitationRequired, message, {
1465
+ elicitations
1466
+ });
1467
+ }
1468
+ get elicitations() {
1469
+ return this.data?.elicitations ?? [];
1470
+ }
1471
+ };
1472
+
1473
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
1474
+ var SafeUrlSchema = url().superRefine((val, ctx) => {
1475
+ if (!URL.canParse(val))
1476
+ return ctx.addIssue({
1477
+ code: ZodIssueCode.custom,
1478
+ message: "URL must be parseable",
1479
+ fatal: !0
1480
+ }), NEVER;
1481
+ }).refine((url2) => {
1482
+ let u = new URL(url2);
1483
+ return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:";
1484
+ }, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }), OAuthProtectedResourceMetadataSchema = looseObject({
1485
+ resource: string().url(),
1486
+ authorization_servers: array(SafeUrlSchema).optional(),
1487
+ jwks_uri: string().url().optional(),
1488
+ scopes_supported: array(string()).optional(),
1489
+ bearer_methods_supported: array(string()).optional(),
1490
+ resource_signing_alg_values_supported: array(string()).optional(),
1491
+ resource_name: string().optional(),
1492
+ resource_documentation: string().optional(),
1493
+ resource_policy_uri: string().url().optional(),
1494
+ resource_tos_uri: string().url().optional(),
1495
+ tls_client_certificate_bound_access_tokens: boolean().optional(),
1496
+ authorization_details_types_supported: array(string()).optional(),
1497
+ dpop_signing_alg_values_supported: array(string()).optional(),
1498
+ dpop_bound_access_tokens_required: boolean().optional()
1499
+ }), OAuthMetadataSchema = looseObject({
1500
+ issuer: string(),
1501
+ authorization_endpoint: SafeUrlSchema,
1502
+ token_endpoint: SafeUrlSchema,
1503
+ registration_endpoint: SafeUrlSchema.optional(),
1504
+ scopes_supported: array(string()).optional(),
1505
+ response_types_supported: array(string()),
1506
+ response_modes_supported: array(string()).optional(),
1507
+ grant_types_supported: array(string()).optional(),
1508
+ token_endpoint_auth_methods_supported: array(string()).optional(),
1509
+ token_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
1510
+ service_documentation: SafeUrlSchema.optional(),
1511
+ revocation_endpoint: SafeUrlSchema.optional(),
1512
+ revocation_endpoint_auth_methods_supported: array(string()).optional(),
1513
+ revocation_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
1514
+ introspection_endpoint: string().optional(),
1515
+ introspection_endpoint_auth_methods_supported: array(string()).optional(),
1516
+ introspection_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
1517
+ code_challenge_methods_supported: array(string()).optional(),
1518
+ client_id_metadata_document_supported: boolean().optional()
1519
+ }), OpenIdProviderMetadataSchema = looseObject({
1520
+ issuer: string(),
1521
+ authorization_endpoint: SafeUrlSchema,
1522
+ token_endpoint: SafeUrlSchema,
1523
+ userinfo_endpoint: SafeUrlSchema.optional(),
1524
+ jwks_uri: SafeUrlSchema,
1525
+ registration_endpoint: SafeUrlSchema.optional(),
1526
+ scopes_supported: array(string()).optional(),
1527
+ response_types_supported: array(string()),
1528
+ response_modes_supported: array(string()).optional(),
1529
+ grant_types_supported: array(string()).optional(),
1530
+ acr_values_supported: array(string()).optional(),
1531
+ subject_types_supported: array(string()),
1532
+ id_token_signing_alg_values_supported: array(string()),
1533
+ id_token_encryption_alg_values_supported: array(string()).optional(),
1534
+ id_token_encryption_enc_values_supported: array(string()).optional(),
1535
+ userinfo_signing_alg_values_supported: array(string()).optional(),
1536
+ userinfo_encryption_alg_values_supported: array(string()).optional(),
1537
+ userinfo_encryption_enc_values_supported: array(string()).optional(),
1538
+ request_object_signing_alg_values_supported: array(string()).optional(),
1539
+ request_object_encryption_alg_values_supported: array(string()).optional(),
1540
+ request_object_encryption_enc_values_supported: array(string()).optional(),
1541
+ token_endpoint_auth_methods_supported: array(string()).optional(),
1542
+ token_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
1543
+ display_values_supported: array(string()).optional(),
1544
+ claim_types_supported: array(string()).optional(),
1545
+ claims_supported: array(string()).optional(),
1546
+ service_documentation: string().optional(),
1547
+ claims_locales_supported: array(string()).optional(),
1548
+ ui_locales_supported: array(string()).optional(),
1549
+ claims_parameter_supported: boolean().optional(),
1550
+ request_parameter_supported: boolean().optional(),
1551
+ request_uri_parameter_supported: boolean().optional(),
1552
+ require_request_uri_registration: boolean().optional(),
1553
+ op_policy_uri: SafeUrlSchema.optional(),
1554
+ op_tos_uri: SafeUrlSchema.optional(),
1555
+ client_id_metadata_document_supported: boolean().optional()
1556
+ }), OpenIdProviderDiscoveryMetadataSchema = object({
1557
+ ...OpenIdProviderMetadataSchema.shape,
1558
+ ...OAuthMetadataSchema.pick({
1559
+ code_challenge_methods_supported: !0
1560
+ }).shape
1561
+ }), OAuthTokensSchema = object({
1562
+ access_token: string(),
1563
+ id_token: string().optional(),
1564
+ // Optional for OAuth 2.1, but necessary in OpenID Connect
1565
+ token_type: string(),
1566
+ expires_in: coerce_exports.number().optional(),
1567
+ scope: string().optional(),
1568
+ refresh_token: string().optional()
1569
+ }).strip(), OAuthErrorResponseSchema = object({
1570
+ error: string(),
1571
+ error_description: string().optional(),
1572
+ error_uri: string().optional()
1573
+ }), OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => {
1574
+ })), OAuthClientMetadataSchema = object({
1575
+ redirect_uris: array(SafeUrlSchema),
1576
+ token_endpoint_auth_method: string().optional(),
1577
+ grant_types: array(string()).optional(),
1578
+ response_types: array(string()).optional(),
1579
+ client_name: string().optional(),
1580
+ client_uri: SafeUrlSchema.optional(),
1581
+ logo_uri: OptionalSafeUrlSchema,
1582
+ scope: string().optional(),
1583
+ contacts: array(string()).optional(),
1584
+ tos_uri: OptionalSafeUrlSchema,
1585
+ policy_uri: string().optional(),
1586
+ jwks_uri: SafeUrlSchema.optional(),
1587
+ jwks: any().optional(),
1588
+ software_id: string().optional(),
1589
+ software_version: string().optional(),
1590
+ software_statement: string().optional()
1591
+ }).strip(), OAuthClientInformationSchema = object({
1592
+ client_id: string(),
1593
+ client_secret: string().optional(),
1594
+ client_id_issued_at: number().optional(),
1595
+ client_secret_expires_at: number().optional()
1596
+ }).strip(), OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema), OAuthClientRegistrationErrorSchema = object({
1597
+ error: string(),
1598
+ error_description: string().optional()
1599
+ }).strip(), OAuthTokenRevocationRequestSchema = object({
1600
+ token: string(),
1601
+ token_type_hint: string().optional()
1602
+ }).strip();
1603
+
1604
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js
1605
+ function resourceUrlFromServerUrl(url2) {
1606
+ let resourceURL = typeof url2 == "string" ? new URL(url2) : new URL(url2.href);
1607
+ return resourceURL.hash = "", resourceURL;
1608
+ }
1609
+ function checkResourceAllowed({ requestedResource, configuredResource }) {
1610
+ let requested = typeof requestedResource == "string" ? new URL(requestedResource) : new URL(requestedResource.href), configured = typeof configuredResource == "string" ? new URL(configuredResource) : new URL(configuredResource.href);
1611
+ if (requested.origin !== configured.origin || requested.pathname.length < configured.pathname.length)
1612
+ return !1;
1613
+ let requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/", configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/";
1614
+ return requestedPath.startsWith(configuredPath);
1615
+ }
1616
+
1617
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js
1618
+ var OAuthError = class extends Error {
1619
+ constructor(message, errorUri) {
1620
+ super(message), this.errorUri = errorUri, this.name = this.constructor.name;
1621
+ }
1622
+ /**
1623
+ * Converts the error to a standard OAuth error response object
1624
+ */
1625
+ toResponseObject() {
1626
+ let response = {
1627
+ error: this.errorCode,
1628
+ error_description: this.message
1629
+ };
1630
+ return this.errorUri && (response.error_uri = this.errorUri), response;
1631
+ }
1632
+ get errorCode() {
1633
+ return this.constructor.errorCode;
1634
+ }
1635
+ }, InvalidRequestError = class extends OAuthError {
1636
+ };
1637
+ InvalidRequestError.errorCode = "invalid_request";
1638
+ var InvalidClientError = class extends OAuthError {
1639
+ };
1640
+ InvalidClientError.errorCode = "invalid_client";
1641
+ var InvalidGrantError = class extends OAuthError {
1642
+ };
1643
+ InvalidGrantError.errorCode = "invalid_grant";
1644
+ var UnauthorizedClientError = class extends OAuthError {
1645
+ };
1646
+ UnauthorizedClientError.errorCode = "unauthorized_client";
1647
+ var UnsupportedGrantTypeError = class extends OAuthError {
1648
+ };
1649
+ UnsupportedGrantTypeError.errorCode = "unsupported_grant_type";
1650
+ var InvalidScopeError = class extends OAuthError {
1651
+ };
1652
+ InvalidScopeError.errorCode = "invalid_scope";
1653
+ var AccessDeniedError = class extends OAuthError {
1654
+ };
1655
+ AccessDeniedError.errorCode = "access_denied";
1656
+ var ServerError = class extends OAuthError {
1657
+ };
1658
+ ServerError.errorCode = "server_error";
1659
+ var TemporarilyUnavailableError = class extends OAuthError {
1660
+ };
1661
+ TemporarilyUnavailableError.errorCode = "temporarily_unavailable";
1662
+ var UnsupportedResponseTypeError = class extends OAuthError {
1663
+ };
1664
+ UnsupportedResponseTypeError.errorCode = "unsupported_response_type";
1665
+ var UnsupportedTokenTypeError = class extends OAuthError {
1666
+ };
1667
+ UnsupportedTokenTypeError.errorCode = "unsupported_token_type";
1668
+ var InvalidTokenError = class extends OAuthError {
1669
+ };
1670
+ InvalidTokenError.errorCode = "invalid_token";
1671
+ var MethodNotAllowedError = class extends OAuthError {
1672
+ };
1673
+ MethodNotAllowedError.errorCode = "method_not_allowed";
1674
+ var TooManyRequestsError = class extends OAuthError {
1675
+ };
1676
+ TooManyRequestsError.errorCode = "too_many_requests";
1677
+ var InvalidClientMetadataError = class extends OAuthError {
1678
+ };
1679
+ InvalidClientMetadataError.errorCode = "invalid_client_metadata";
1680
+ var InsufficientScopeError = class extends OAuthError {
1681
+ };
1682
+ InsufficientScopeError.errorCode = "insufficient_scope";
1683
+ var InvalidTargetError = class extends OAuthError {
1684
+ };
1685
+ InvalidTargetError.errorCode = "invalid_target";
1686
+ var OAUTH_ERRORS = {
1687
+ [InvalidRequestError.errorCode]: InvalidRequestError,
1688
+ [InvalidClientError.errorCode]: InvalidClientError,
1689
+ [InvalidGrantError.errorCode]: InvalidGrantError,
1690
+ [UnauthorizedClientError.errorCode]: UnauthorizedClientError,
1691
+ [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError,
1692
+ [InvalidScopeError.errorCode]: InvalidScopeError,
1693
+ [AccessDeniedError.errorCode]: AccessDeniedError,
1694
+ [ServerError.errorCode]: ServerError,
1695
+ [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError,
1696
+ [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError,
1697
+ [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError,
1698
+ [InvalidTokenError.errorCode]: InvalidTokenError,
1699
+ [MethodNotAllowedError.errorCode]: MethodNotAllowedError,
1700
+ [TooManyRequestsError.errorCode]: TooManyRequestsError,
1701
+ [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,
1702
+ [InsufficientScopeError.errorCode]: InsufficientScopeError,
1703
+ [InvalidTargetError.errorCode]: InvalidTargetError
1704
+ };
1705
+
1706
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
1707
+ var UnauthorizedError = class extends Error {
1708
+ constructor(message) {
1709
+ super(message ?? "Unauthorized");
1710
+ }
1711
+ };
1712
+ function isClientAuthMethod(method) {
1713
+ return ["client_secret_basic", "client_secret_post", "none"].includes(method);
1714
+ }
1715
+ var AUTHORIZATION_CODE_RESPONSE_TYPE = "code", AUTHORIZATION_CODE_CHALLENGE_METHOD = "S256";
1716
+ function selectClientAuthMethod(clientInformation, supportedMethods) {
1717
+ let hasClientSecret = clientInformation.client_secret !== void 0;
1718
+ return "token_endpoint_auth_method" in clientInformation && clientInformation.token_endpoint_auth_method && isClientAuthMethod(clientInformation.token_endpoint_auth_method) && (supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method)) ? clientInformation.token_endpoint_auth_method : supportedMethods.length === 0 ? hasClientSecret ? "client_secret_basic" : "none" : hasClientSecret && supportedMethods.includes("client_secret_basic") ? "client_secret_basic" : hasClientSecret && supportedMethods.includes("client_secret_post") ? "client_secret_post" : supportedMethods.includes("none") ? "none" : hasClientSecret ? "client_secret_post" : "none";
1719
+ }
1720
+ function applyClientAuthentication(method, clientInformation, headers, params) {
1721
+ let { client_id, client_secret } = clientInformation;
1722
+ switch (method) {
1723
+ case "client_secret_basic":
1724
+ applyBasicAuth(client_id, client_secret, headers);
1725
+ return;
1726
+ case "client_secret_post":
1727
+ applyPostAuth(client_id, client_secret, params);
1728
+ return;
1729
+ case "none":
1730
+ applyPublicAuth(client_id, params);
1731
+ return;
1732
+ default:
1733
+ throw new Error(`Unsupported client authentication method: ${method}`);
1734
+ }
1735
+ }
1736
+ function applyBasicAuth(clientId, clientSecret, headers) {
1737
+ if (!clientSecret)
1738
+ throw new Error("client_secret_basic authentication requires a client_secret");
1739
+ let credentials = btoa(`${clientId}:${clientSecret}`);
1740
+ headers.set("Authorization", `Basic ${credentials}`);
1741
+ }
1742
+ function applyPostAuth(clientId, clientSecret, params) {
1743
+ params.set("client_id", clientId), clientSecret && params.set("client_secret", clientSecret);
1744
+ }
1745
+ function applyPublicAuth(clientId, params) {
1746
+ params.set("client_id", clientId);
1747
+ }
1748
+ async function parseErrorResponse(input) {
1749
+ let statusCode = input instanceof Response ? input.status : void 0, body = input instanceof Response ? await input.text() : input;
1750
+ try {
1751
+ let result = OAuthErrorResponseSchema.parse(JSON.parse(body)), { error, error_description, error_uri } = result, errorClass = OAUTH_ERRORS[error] || ServerError;
1752
+ return new errorClass(error_description || "", error_uri);
1753
+ } catch (error) {
1754
+ let errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`;
1755
+ return new ServerError(errorMessage);
1756
+ }
1757
+ }
1758
+ async function auth(provider, options) {
1759
+ try {
1760
+ return await authInternal(provider, options);
1761
+ } catch (error) {
1762
+ if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError)
1763
+ return await provider.invalidateCredentials?.("all"), await authInternal(provider, options);
1764
+ if (error instanceof InvalidGrantError)
1765
+ return await provider.invalidateCredentials?.("tokens"), await authInternal(provider, options);
1766
+ throw error;
1767
+ }
1768
+ }
1769
+ async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {
1770
+ let cachedState = await provider.discoveryState?.(), resourceMetadata, authorizationServerUrl, metadata, effectiveResourceMetadataUrl = resourceMetadataUrl;
1771
+ if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl && (effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl)), cachedState?.authorizationServerUrl) {
1772
+ if (authorizationServerUrl = cachedState.authorizationServerUrl, resourceMetadata = cachedState.resourceMetadata, metadata = cachedState.authorizationServerMetadata ?? await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn }), !resourceMetadata)
1773
+ try {
1774
+ resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn);
1775
+ } catch {
1776
+ }
1777
+ (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) && await provider.saveDiscoveryState?.({
1778
+ authorizationServerUrl: String(authorizationServerUrl),
1779
+ resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
1780
+ resourceMetadata,
1781
+ authorizationServerMetadata: metadata
1782
+ });
1783
+ } else {
1784
+ let serverInfo = await discoverOAuthServerInfo(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl, fetchFn });
1785
+ authorizationServerUrl = serverInfo.authorizationServerUrl, metadata = serverInfo.authorizationServerMetadata, resourceMetadata = serverInfo.resourceMetadata, await provider.saveDiscoveryState?.({
1786
+ authorizationServerUrl: String(authorizationServerUrl),
1787
+ resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
1788
+ resourceMetadata,
1789
+ authorizationServerMetadata: metadata
1790
+ });
1791
+ }
1792
+ let resource = await selectResourceURL(serverUrl, provider, resourceMetadata), resolvedScope = scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope, clientInformation = await Promise.resolve(provider.clientInformation());
1793
+ if (!clientInformation) {
1794
+ if (authorizationCode !== void 0)
1795
+ throw new Error("Existing OAuth client information is required when exchanging an authorization code");
1796
+ let supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === !0, clientMetadataUrl = provider.clientMetadataUrl;
1797
+ if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl))
1798
+ throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);
1799
+ if (supportsUrlBasedClientId && clientMetadataUrl)
1800
+ clientInformation = {
1801
+ client_id: clientMetadataUrl
1802
+ }, await provider.saveClientInformation?.(clientInformation);
1803
+ else {
1804
+ if (!provider.saveClientInformation)
1805
+ throw new Error("OAuth client information must be saveable for dynamic registration");
1806
+ let fullInformation = await registerClient(authorizationServerUrl, {
1807
+ metadata,
1808
+ clientMetadata: provider.clientMetadata,
1809
+ scope: resolvedScope,
1810
+ fetchFn
1811
+ });
1812
+ await provider.saveClientInformation(fullInformation), clientInformation = fullInformation;
1813
+ }
1814
+ }
1815
+ let nonInteractiveFlow = !provider.redirectUrl;
1816
+ if (authorizationCode !== void 0 || nonInteractiveFlow) {
1817
+ let tokens2 = await fetchToken(provider, authorizationServerUrl, {
1818
+ metadata,
1819
+ resource,
1820
+ authorizationCode,
1821
+ fetchFn
1822
+ });
1823
+ return await provider.saveTokens(tokens2), "AUTHORIZED";
1824
+ }
1825
+ let tokens = await provider.tokens();
1826
+ if (tokens?.refresh_token)
1827
+ try {
1828
+ let newTokens = await refreshAuthorization(authorizationServerUrl, {
1829
+ metadata,
1830
+ clientInformation,
1831
+ refreshToken: tokens.refresh_token,
1832
+ resource,
1833
+ addClientAuthentication: provider.addClientAuthentication,
1834
+ fetchFn
1835
+ });
1836
+ return await provider.saveTokens(newTokens), "AUTHORIZED";
1837
+ } catch (error) {
1838
+ if (!(!(error instanceof OAuthError) || error instanceof ServerError))
1839
+ throw error;
1840
+ }
1841
+ let state = provider.state ? await provider.state() : void 0, { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {
1842
+ metadata,
1843
+ clientInformation,
1844
+ state,
1845
+ redirectUrl: provider.redirectUrl,
1846
+ scope: resolvedScope,
1847
+ resource
1848
+ });
1849
+ return await provider.saveCodeVerifier(codeVerifier), await provider.redirectToAuthorization(authorizationUrl), "REDIRECT";
1850
+ }
1851
+ function isHttpsUrl(value) {
1852
+ if (!value)
1853
+ return !1;
1854
+ try {
1855
+ let url2 = new URL(value);
1856
+ return url2.protocol === "https:" && url2.pathname !== "/";
1857
+ } catch {
1858
+ return !1;
1859
+ }
1860
+ }
1861
+ async function selectResourceURL(serverUrl, provider, resourceMetadata) {
1862
+ let defaultResource = resourceUrlFromServerUrl(serverUrl);
1863
+ if (provider.validateResourceURL)
1864
+ return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource);
1865
+ if (resourceMetadata) {
1866
+ if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource }))
1867
+ throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);
1868
+ return new URL(resourceMetadata.resource);
1869
+ }
1870
+ }
1871
+ function extractWWWAuthenticateParams(res) {
1872
+ let authenticateHeader = res.headers.get("WWW-Authenticate");
1873
+ if (!authenticateHeader)
1874
+ return {};
1875
+ let [type, scheme] = authenticateHeader.split(" ");
1876
+ if (type.toLowerCase() !== "bearer" || !scheme)
1877
+ return {};
1878
+ let resourceMetadataMatch = extractFieldFromWwwAuth(res, "resource_metadata") || void 0, resourceMetadataUrl;
1879
+ if (resourceMetadataMatch)
1880
+ try {
1881
+ resourceMetadataUrl = new URL(resourceMetadataMatch);
1882
+ } catch {
1883
+ }
1884
+ let scope = extractFieldFromWwwAuth(res, "scope") || void 0, error = extractFieldFromWwwAuth(res, "error") || void 0;
1885
+ return {
1886
+ resourceMetadataUrl,
1887
+ scope,
1888
+ error
1889
+ };
1890
+ }
1891
+ function extractFieldFromWwwAuth(response, fieldName) {
1892
+ let wwwAuthHeader = response.headers.get("WWW-Authenticate");
1893
+ if (!wwwAuthHeader)
1894
+ return null;
1895
+ let pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`), match = wwwAuthHeader.match(pattern);
1896
+ return match ? match[1] || match[2] : null;
1897
+ }
1898
+ async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
1899
+ let response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, {
1900
+ protocolVersion: opts?.protocolVersion,
1901
+ metadataUrl: opts?.resourceMetadataUrl
1902
+ });
1903
+ if (!response || response.status === 404)
1904
+ throw await response?.body?.cancel(), new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");
1905
+ if (!response.ok)
1906
+ throw await response.body?.cancel(), new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);
1907
+ return OAuthProtectedResourceMetadataSchema.parse(await response.json());
1908
+ }
1909
+ async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) {
1910
+ try {
1911
+ return await fetchFn(url2, { headers });
1912
+ } catch (error) {
1913
+ if (error instanceof TypeError)
1914
+ return headers ? fetchWithCorsRetry(url2, void 0, fetchFn) : void 0;
1915
+ throw error;
1916
+ }
1917
+ }
1918
+ function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) {
1919
+ return pathname.endsWith("/") && (pathname = pathname.slice(0, -1)), options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;
1920
+ }
1921
+ async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) {
1922
+ return await fetchWithCorsRetry(url2, {
1923
+ "MCP-Protocol-Version": protocolVersion
1924
+ }, fetchFn);
1925
+ }
1926
+ function shouldAttemptFallback(response, pathname) {
1927
+ return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
1928
+ }
1929
+ async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
1930
+ let issuer = new URL(serverUrl), protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION, url2;
1931
+ if (opts?.metadataUrl)
1932
+ url2 = new URL(opts.metadataUrl);
1933
+ else {
1934
+ let wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
1935
+ url2 = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer), url2.search = issuer.search;
1936
+ }
1937
+ let response = await tryMetadataDiscovery(url2, protocolVersion, fetchFn);
1938
+ if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) {
1939
+ let rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);
1940
+ response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);
1941
+ }
1942
+ return response;
1943
+ }
1944
+ function buildDiscoveryUrls(authorizationServerUrl) {
1945
+ let url2 = typeof authorizationServerUrl == "string" ? new URL(authorizationServerUrl) : authorizationServerUrl, hasPath = url2.pathname !== "/", urlsToTry = [];
1946
+ if (!hasPath)
1947
+ return urlsToTry.push({
1948
+ url: new URL("/.well-known/oauth-authorization-server", url2.origin),
1949
+ type: "oauth"
1950
+ }), urlsToTry.push({
1951
+ url: new URL("/.well-known/openid-configuration", url2.origin),
1952
+ type: "oidc"
1953
+ }), urlsToTry;
1954
+ let pathname = url2.pathname;
1955
+ return pathname.endsWith("/") && (pathname = pathname.slice(0, -1)), urlsToTry.push({
1956
+ url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url2.origin),
1957
+ type: "oauth"
1958
+ }), urlsToTry.push({
1959
+ url: new URL(`/.well-known/openid-configuration${pathname}`, url2.origin),
1960
+ type: "oidc"
1961
+ }), urlsToTry.push({
1962
+ url: new URL(`${pathname}/.well-known/openid-configuration`, url2.origin),
1963
+ type: "oidc"
1964
+ }), urlsToTry;
1965
+ }
1966
+ async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) {
1967
+ let headers = {
1968
+ "MCP-Protocol-Version": protocolVersion,
1969
+ Accept: "application/json"
1970
+ }, urlsToTry = buildDiscoveryUrls(authorizationServerUrl);
1971
+ for (let { url: endpointUrl, type } of urlsToTry) {
1972
+ let response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);
1973
+ if (response) {
1974
+ if (!response.ok) {
1975
+ if (await response.body?.cancel(), response.status >= 400 && response.status < 500)
1976
+ continue;
1977
+ throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
1978
+ }
1979
+ return type === "oauth" ? OAuthMetadataSchema.parse(await response.json()) : OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());
1980
+ }
1981
+ }
1982
+ }
1983
+ async function discoverOAuthServerInfo(serverUrl, opts) {
1984
+ let resourceMetadata, authorizationServerUrl;
1985
+ try {
1986
+ resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn), resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0 && (authorizationServerUrl = resourceMetadata.authorization_servers[0]);
1987
+ } catch {
1988
+ }
1989
+ authorizationServerUrl || (authorizationServerUrl = String(new URL("/", serverUrl)));
1990
+ let authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts?.fetchFn });
1991
+ return {
1992
+ authorizationServerUrl,
1993
+ authorizationServerMetadata,
1994
+ resourceMetadata
1995
+ };
1996
+ }
1997
+ async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {
1998
+ let authorizationUrl;
1999
+ if (metadata) {
2000
+ if (authorizationUrl = new URL(metadata.authorization_endpoint), !metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE))
2001
+ throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);
2002
+ if (metadata.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD))
2003
+ throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`);
2004
+ } else
2005
+ authorizationUrl = new URL("/authorize", authorizationServerUrl);
2006
+ let challenge = await pkceChallenge(), codeVerifier = challenge.code_verifier, codeChallenge = challenge.code_challenge;
2007
+ return authorizationUrl.searchParams.set("response_type", AUTHORIZATION_CODE_RESPONSE_TYPE), authorizationUrl.searchParams.set("client_id", clientInformation.client_id), authorizationUrl.searchParams.set("code_challenge", codeChallenge), authorizationUrl.searchParams.set("code_challenge_method", AUTHORIZATION_CODE_CHALLENGE_METHOD), authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl)), state && authorizationUrl.searchParams.set("state", state), scope && authorizationUrl.searchParams.set("scope", scope), scope?.includes("offline_access") && authorizationUrl.searchParams.append("prompt", "consent"), resource && authorizationUrl.searchParams.set("resource", resource.href), { authorizationUrl, codeVerifier };
2008
+ }
2009
+ function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {
2010
+ return new URLSearchParams({
2011
+ grant_type: "authorization_code",
2012
+ code: authorizationCode,
2013
+ code_verifier: codeVerifier,
2014
+ redirect_uri: String(redirectUri)
2015
+ });
2016
+ }
2017
+ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {
2018
+ let tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl), headers = new Headers({
2019
+ "Content-Type": "application/x-www-form-urlencoded",
2020
+ Accept: "application/json"
2021
+ });
2022
+ if (resource && tokenRequestParams.set("resource", resource.href), addClientAuthentication)
2023
+ await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
2024
+ else if (clientInformation) {
2025
+ let supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? [], authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
2026
+ applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);
2027
+ }
2028
+ let response = await (fetchFn ?? fetch)(tokenUrl, {
2029
+ method: "POST",
2030
+ headers,
2031
+ body: tokenRequestParams
2032
+ });
2033
+ if (!response.ok)
2034
+ throw await parseErrorResponse(response);
2035
+ return OAuthTokensSchema.parse(await response.json());
2036
+ }
2037
+ async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
2038
+ let tokenRequestParams = new URLSearchParams({
2039
+ grant_type: "refresh_token",
2040
+ refresh_token: refreshToken
2041
+ }), tokens = await executeTokenRequest(authorizationServerUrl, {
2042
+ metadata,
2043
+ tokenRequestParams,
2044
+ clientInformation,
2045
+ addClientAuthentication,
2046
+ resource,
2047
+ fetchFn
2048
+ });
2049
+ return { refresh_token: refreshToken, ...tokens };
2050
+ }
2051
+ async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
2052
+ let scope = provider.clientMetadata.scope, tokenRequestParams;
2053
+ if (provider.prepareTokenRequest && (tokenRequestParams = await provider.prepareTokenRequest(scope)), !tokenRequestParams) {
2054
+ if (!authorizationCode)
2055
+ throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");
2056
+ if (!provider.redirectUrl)
2057
+ throw new Error("redirectUrl is required for authorization_code flow");
2058
+ let codeVerifier = await provider.codeVerifier();
2059
+ tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);
2060
+ }
2061
+ let clientInformation = await provider.clientInformation();
2062
+ return executeTokenRequest(authorizationServerUrl, {
2063
+ metadata,
2064
+ tokenRequestParams,
2065
+ clientInformation: clientInformation ?? void 0,
2066
+ addClientAuthentication: provider.addClientAuthentication,
2067
+ resource,
2068
+ fetchFn
2069
+ });
2070
+ }
2071
+ async function registerClient(authorizationServerUrl, { metadata, clientMetadata, scope, fetchFn }) {
2072
+ let registrationUrl;
2073
+ if (metadata) {
2074
+ if (!metadata.registration_endpoint)
2075
+ throw new Error("Incompatible auth server: does not support dynamic client registration");
2076
+ registrationUrl = new URL(metadata.registration_endpoint);
2077
+ } else
2078
+ registrationUrl = new URL("/register", authorizationServerUrl);
2079
+ let response = await (fetchFn ?? fetch)(registrationUrl, {
2080
+ method: "POST",
2081
+ headers: {
2082
+ "Content-Type": "application/json"
2083
+ },
2084
+ body: JSON.stringify({
2085
+ ...clientMetadata,
2086
+ ...scope !== void 0 ? { scope } : {}
2087
+ })
2088
+ });
2089
+ if (!response.ok)
2090
+ throw await parseErrorResponse(response);
2091
+ return OAuthClientInformationFullSchema.parse(await response.json());
2092
+ }
2093
+
2094
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js
2095
+ var import_content_type = __toESM(require_content_type(), 1);
2096
+ function mediaTypeEssence(header) {
2097
+ if (header)
2098
+ try {
2099
+ return import_content_type.default.parse(header).type;
2100
+ } catch {
2101
+ let essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase();
2102
+ return essence === "" || header.slice(essence.length).includes(",") ? void 0 : essence;
2103
+ }
2104
+ }
2105
+
2106
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js
2107
+ function normalizeHeaders(headers) {
2108
+ return headers ? headers instanceof Headers ? Object.fromEntries(headers.entries()) : Array.isArray(headers) ? Object.fromEntries(headers) : { ...headers } : {};
2109
+ }
2110
+ function createFetchWithInit(baseFetch = fetch, baseInit) {
2111
+ return baseInit ? async (url2, init) => {
2112
+ let mergedInit = {
2113
+ ...baseInit,
2114
+ ...init,
2115
+ // Headers need special handling - merge instead of replace
2116
+ headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers
2117
+ };
2118
+ return baseFetch(url2, mergedInit);
2119
+ } : baseFetch;
2120
+ }
2121
+
2122
+ // node_modules/eventsource-parser/dist/index.js
2123
+ var ParseError = class extends Error {
2124
+ constructor(message, options) {
2125
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
2126
+ }
2127
+ }, LF = 10, CR = 13, SPACE = 32;
2128
+ function noop(_arg) {
2129
+ }
2130
+ function createParser(config) {
2131
+ if (typeof config == "function")
2132
+ throw new TypeError(
2133
+ "`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?"
2134
+ );
2135
+ let { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config, pendingFragments = [], pendingFragmentsLength = 0, isFirstChunk = !0, id, data = "", dataLines = 0, eventType, terminated = !1;
2136
+ function feed(chunk) {
2137
+ if (terminated)
2138
+ throw new Error(
2139
+ "Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing."
2140
+ );
2141
+ if (isFirstChunk && (isFirstChunk = !1, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
2142
+ let trailing2 = processLines(chunk);
2143
+ trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
2144
+ return;
2145
+ }
2146
+ if (chunk.indexOf(`
2147
+ `) === -1 && chunk.indexOf("\r") === -1) {
2148
+ pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
2149
+ return;
2150
+ }
2151
+ pendingFragments.push(chunk);
2152
+ let input = pendingFragments.join("");
2153
+ pendingFragments.length = 0, pendingFragmentsLength = 0;
2154
+ let trailing = processLines(input);
2155
+ trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
2156
+ }
2157
+ function checkBufferSize() {
2158
+ maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = !0, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError(
2159
+ new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
2160
+ type: "max-buffer-size-exceeded"
2161
+ })
2162
+ )));
2163
+ }
2164
+ function processLines(chunk) {
2165
+ let searchIndex = 0;
2166
+ if (chunk.indexOf("\r") === -1) {
2167
+ let lfIndex = chunk.indexOf(`
2168
+ `, searchIndex);
2169
+ for (; lfIndex !== -1; ) {
2170
+ if (searchIndex === lfIndex) {
2171
+ dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
2172
+ `, searchIndex);
2173
+ continue;
2174
+ }
2175
+ let firstCharCode = chunk.charCodeAt(searchIndex);
2176
+ if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
2177
+ let valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
2178
+ if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
2179
+ onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
2180
+ `, searchIndex);
2181
+ continue;
2182
+ }
2183
+ data = dataLines === 0 ? value : `${data}
2184
+ ${value}`, dataLines++;
2185
+ } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
2186
+ chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
2187
+ lfIndex
2188
+ ) || void 0 : parseLine(chunk, searchIndex, lfIndex);
2189
+ searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
2190
+ `, searchIndex);
2191
+ }
2192
+ return chunk.slice(searchIndex);
2193
+ }
2194
+ for (; searchIndex < chunk.length; ) {
2195
+ let crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
2196
+ `, searchIndex), lineEnd = -1;
2197
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)
2198
+ break;
2199
+ parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
2200
+ }
2201
+ return chunk.slice(searchIndex);
2202
+ }
2203
+ function parseLine(chunk, start, end) {
2204
+ if (start === end) {
2205
+ dispatchEvent();
2206
+ return;
2207
+ }
2208
+ let firstCharCode = chunk.charCodeAt(start);
2209
+ if (isDataPrefix(chunk, start, firstCharCode)) {
2210
+ let valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
2211
+ data = dataLines === 0 ? value2 : `${data}
2212
+ ${value2}`, dataLines++;
2213
+ return;
2214
+ }
2215
+ if (isEventPrefix(chunk, start, firstCharCode)) {
2216
+ eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
2217
+ return;
2218
+ }
2219
+ if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
2220
+ let value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
2221
+ id = value2.includes("\0") ? void 0 : value2;
2222
+ return;
2223
+ }
2224
+ if (firstCharCode === 58) {
2225
+ if (onComment) {
2226
+ let line2 = chunk.slice(start, end);
2227
+ onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
2228
+ }
2229
+ return;
2230
+ }
2231
+ let line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
2232
+ if (fieldSeparatorIndex === -1) {
2233
+ processField(line, "", line);
2234
+ return;
2235
+ }
2236
+ let field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
2237
+ processField(field, value, line);
2238
+ }
2239
+ function processField(field, value, line) {
2240
+ switch (field) {
2241
+ case "event":
2242
+ eventType = value || void 0;
2243
+ break;
2244
+ case "data":
2245
+ data = dataLines === 0 ? value : `${data}
2246
+ ${value}`, dataLines++;
2247
+ break;
2248
+ case "id":
2249
+ id = value.includes("\0") ? void 0 : value;
2250
+ break;
2251
+ case "retry":
2252
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
2253
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
2254
+ type: "invalid-retry",
2255
+ value,
2256
+ line
2257
+ })
2258
+ );
2259
+ break;
2260
+ default:
2261
+ onError(
2262
+ new ParseError(
2263
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
2264
+ { type: "unknown-field", field, value, line }
2265
+ )
2266
+ );
2267
+ break;
2268
+ }
2269
+ }
2270
+ function dispatchEvent() {
2271
+ dataLines > 0 && onEvent({
2272
+ id,
2273
+ event: eventType,
2274
+ data
2275
+ }), id = void 0, data = "", dataLines = 0, eventType = void 0;
2276
+ }
2277
+ function reset(options = {}) {
2278
+ if (options.consume && pendingFragments.length > 0) {
2279
+ let incompleteLine = pendingFragments.join("");
2280
+ parseLine(incompleteLine, 0, incompleteLine.length);
2281
+ }
2282
+ isFirstChunk = !0, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = !1;
2283
+ }
2284
+ return { feed, reset };
2285
+ }
2286
+ function isDataPrefix(chunk, i, firstCharCode) {
2287
+ return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
2288
+ }
2289
+ function isEventPrefix(chunk, i, firstCharCode) {
2290
+ return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
2291
+ }
2292
+
2293
+ // node_modules/eventsource-parser/dist/stream.js
2294
+ var EventSourceParserStream = class extends TransformStream {
2295
+ constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {
2296
+ let parser;
2297
+ super({
2298
+ start(controller) {
2299
+ parser = createParser({
2300
+ onEvent: (event) => {
2301
+ controller.enqueue(event);
2302
+ },
2303
+ onError(error) {
2304
+ typeof onError == "function" && onError(error), (onError === "terminate" || error.type === "max-buffer-size-exceeded") && controller.error(error);
2305
+ },
2306
+ onRetry,
2307
+ onComment,
2308
+ maxBufferSize
2309
+ });
2310
+ },
2311
+ transform(chunk) {
2312
+ parser.feed(chunk);
2313
+ }
2314
+ });
2315
+ }
2316
+ };
2317
+
2318
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
2319
+ var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
2320
+ initialReconnectionDelay: 1e3,
2321
+ maxReconnectionDelay: 3e4,
2322
+ reconnectionDelayGrowFactor: 1.5,
2323
+ maxRetries: 2
2324
+ }, StreamableHTTPError = class extends Error {
2325
+ constructor(code, message) {
2326
+ super(`Streamable HTTP error: ${message}`), this.code = code;
2327
+ }
2328
+ }, StreamableHTTPClientTransport = class {
2329
+ constructor(url2, opts) {
2330
+ this._hasCompletedAuthFlow = !1, this._url = url2, this._resourceMetadataUrl = void 0, this._scope = void 0, this._requestInit = opts?.requestInit, this._authProvider = opts?.authProvider, this._fetch = opts?.fetch, this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit), this._sessionId = opts?.sessionId, this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
2331
+ }
2332
+ async _authThenStart() {
2333
+ if (!this._authProvider)
2334
+ throw new UnauthorizedError("No auth provider");
2335
+ let result;
2336
+ try {
2337
+ result = await auth(this._authProvider, {
2338
+ serverUrl: this._url,
2339
+ resourceMetadataUrl: this._resourceMetadataUrl,
2340
+ scope: this._scope,
2341
+ fetchFn: this._fetchWithInit
2342
+ });
2343
+ } catch (error) {
2344
+ throw this.onerror?.(error), error;
2345
+ }
2346
+ if (result !== "AUTHORIZED")
2347
+ throw new UnauthorizedError();
2348
+ return await this._startOrAuthSse({ resumptionToken: void 0 });
2349
+ }
2350
+ async _commonHeaders() {
2351
+ let headers = {};
2352
+ if (this._authProvider) {
2353
+ let tokens = await this._authProvider.tokens();
2354
+ tokens && (headers.Authorization = `Bearer ${tokens.access_token}`);
2355
+ }
2356
+ this._sessionId && (headers["mcp-session-id"] = this._sessionId), this._protocolVersion && (headers["mcp-protocol-version"] = this._protocolVersion);
2357
+ let extraHeaders = normalizeHeaders(this._requestInit?.headers);
2358
+ return new Headers({
2359
+ ...headers,
2360
+ ...extraHeaders
2361
+ });
2362
+ }
2363
+ async _startOrAuthSse(options) {
2364
+ let { resumptionToken } = options;
2365
+ try {
2366
+ let headers = await this._commonHeaders();
2367
+ headers.set("Accept", "text/event-stream"), resumptionToken && headers.set("last-event-id", resumptionToken);
2368
+ let response = await (this._fetch ?? fetch)(this._url, {
2369
+ method: "GET",
2370
+ headers,
2371
+ signal: this._abortController?.signal
2372
+ });
2373
+ if (!response.ok) {
2374
+ if (await response.body?.cancel(), response.status === 401 && this._authProvider)
2375
+ return await this._authThenStart();
2376
+ if (response.status === 405)
2377
+ return;
2378
+ throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`);
2379
+ }
2380
+ this._handleSseStream(response.body, options, !0);
2381
+ } catch (error) {
2382
+ throw this.onerror?.(error), error;
2383
+ }
2384
+ }
2385
+ /**
2386
+ * Calculates the next reconnection delay using backoff algorithm
2387
+ *
2388
+ * @param attempt Current reconnection attempt count for the specific stream
2389
+ * @returns Time to wait in milliseconds before next reconnection attempt
2390
+ */
2391
+ _getNextReconnectionDelay(attempt) {
2392
+ if (this._serverRetryMs !== void 0)
2393
+ return this._serverRetryMs;
2394
+ let initialDelay = this._reconnectionOptions.initialReconnectionDelay, growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor, maxDelay = this._reconnectionOptions.maxReconnectionDelay;
2395
+ return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
2396
+ }
2397
+ /**
2398
+ * Schedule a reconnection attempt using server-provided retry interval or backoff
2399
+ *
2400
+ * @param lastEventId The ID of the last received event for resumability
2401
+ * @param attemptCount Current reconnection attempt count for this specific stream
2402
+ */
2403
+ _scheduleReconnection(options, attemptCount = 0) {
2404
+ let maxRetries = this._reconnectionOptions.maxRetries;
2405
+ if (attemptCount >= maxRetries) {
2406
+ this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
2407
+ return;
2408
+ }
2409
+ let delay = this._getNextReconnectionDelay(attemptCount);
2410
+ this._reconnectionTimeout = setTimeout(() => {
2411
+ this._startOrAuthSse(options).catch((error) => {
2412
+ this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`)), this._scheduleReconnection(options, attemptCount + 1);
2413
+ });
2414
+ }, delay);
2415
+ }
2416
+ _handleSseStream(stream, options, isReconnectable) {
2417
+ if (!stream)
2418
+ return;
2419
+ let { onresumptiontoken, replayMessageId } = options, lastEventId, hasPrimingEvent = !1, receivedResponse = !1;
2420
+ (async () => {
2421
+ try {
2422
+ let reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({
2423
+ onRetry: (retryMs) => {
2424
+ this._serverRetryMs = retryMs;
2425
+ }
2426
+ })).getReader();
2427
+ for (; ; ) {
2428
+ let { value: event, done } = await reader.read();
2429
+ if (done)
2430
+ break;
2431
+ if (event.id && (lastEventId = event.id, hasPrimingEvent = !0, onresumptiontoken?.(event.id)), !!event.data && (!event.event || event.event === "message"))
2432
+ try {
2433
+ let message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
2434
+ isJSONRPCResultResponse(message) && (receivedResponse = !0, replayMessageId !== void 0 && (message.id = replayMessageId)), this.onmessage?.(message);
2435
+ } catch (error) {
2436
+ this.onerror?.(error);
2437
+ }
2438
+ }
2439
+ (isReconnectable || hasPrimingEvent) && !receivedResponse && this._abortController && !this._abortController.signal.aborted && this._scheduleReconnection({
2440
+ resumptionToken: lastEventId,
2441
+ onresumptiontoken,
2442
+ replayMessageId
2443
+ }, 0);
2444
+ } catch (error) {
2445
+ if (this.onerror?.(new Error(`SSE stream disconnected: ${error}`)), (isReconnectable || hasPrimingEvent) && !receivedResponse && this._abortController && !this._abortController.signal.aborted)
2446
+ try {
2447
+ this._scheduleReconnection({
2448
+ resumptionToken: lastEventId,
2449
+ onresumptiontoken,
2450
+ replayMessageId
2451
+ }, 0);
2452
+ } catch (error2) {
2453
+ this.onerror?.(new Error(`Failed to reconnect: ${error2 instanceof Error ? error2.message : String(error2)}`));
2454
+ }
2455
+ }
2456
+ })();
2457
+ }
2458
+ async start() {
2459
+ if (this._abortController)
2460
+ throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");
2461
+ this._abortController = new AbortController();
2462
+ }
2463
+ /**
2464
+ * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
2465
+ */
2466
+ async finishAuth(authorizationCode) {
2467
+ if (!this._authProvider)
2468
+ throw new UnauthorizedError("No auth provider");
2469
+ if (await auth(this._authProvider, {
2470
+ serverUrl: this._url,
2471
+ authorizationCode,
2472
+ resourceMetadataUrl: this._resourceMetadataUrl,
2473
+ scope: this._scope,
2474
+ fetchFn: this._fetchWithInit
2475
+ }) !== "AUTHORIZED")
2476
+ throw new UnauthorizedError("Failed to authorize");
2477
+ }
2478
+ async close() {
2479
+ this._reconnectionTimeout && (clearTimeout(this._reconnectionTimeout), this._reconnectionTimeout = void 0), this._abortController?.abort(), this.onclose?.();
2480
+ }
2481
+ async send(message, options) {
2482
+ try {
2483
+ let { resumptionToken, onresumptiontoken } = options || {};
2484
+ if (resumptionToken) {
2485
+ this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : void 0 }).catch((err) => this.onerror?.(err));
2486
+ return;
2487
+ }
2488
+ let headers = await this._commonHeaders();
2489
+ headers.set("content-type", "application/json"), headers.set("accept", "application/json, text/event-stream");
2490
+ let init = {
2491
+ ...this._requestInit,
2492
+ method: "POST",
2493
+ headers,
2494
+ body: JSON.stringify(message),
2495
+ signal: this._abortController?.signal
2496
+ }, response = await (this._fetch ?? fetch)(this._url, init), sessionId = response.headers.get("mcp-session-id");
2497
+ if (sessionId && (this._sessionId = sessionId), !response.ok) {
2498
+ let text = await response.text().catch(() => null);
2499
+ if (response.status === 401 && this._authProvider) {
2500
+ if (this._hasCompletedAuthFlow)
2501
+ throw new StreamableHTTPError(401, "Server returned 401 after successful authentication");
2502
+ let { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
2503
+ if (this._resourceMetadataUrl = resourceMetadataUrl, this._scope = scope, await auth(this._authProvider, {
2504
+ serverUrl: this._url,
2505
+ resourceMetadataUrl: this._resourceMetadataUrl,
2506
+ scope: this._scope,
2507
+ fetchFn: this._fetchWithInit
2508
+ }) !== "AUTHORIZED")
2509
+ throw new UnauthorizedError();
2510
+ return this._hasCompletedAuthFlow = !0, this.send(message);
2511
+ }
2512
+ if (response.status === 403 && this._authProvider) {
2513
+ let { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response);
2514
+ if (error === "insufficient_scope") {
2515
+ let wwwAuthHeader = response.headers.get("WWW-Authenticate");
2516
+ if (this._lastUpscopingHeader === wwwAuthHeader)
2517
+ throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping");
2518
+ if (scope && (this._scope = scope), resourceMetadataUrl && (this._resourceMetadataUrl = resourceMetadataUrl), this._lastUpscopingHeader = wwwAuthHeader ?? void 0, await auth(this._authProvider, {
2519
+ serverUrl: this._url,
2520
+ resourceMetadataUrl: this._resourceMetadataUrl,
2521
+ scope: this._scope,
2522
+ fetchFn: this._fetch
2523
+ }) !== "AUTHORIZED")
2524
+ throw new UnauthorizedError();
2525
+ return this.send(message);
2526
+ }
2527
+ }
2528
+ throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);
2529
+ }
2530
+ if (this._hasCompletedAuthFlow = !1, this._lastUpscopingHeader = void 0, response.status === 202) {
2531
+ await response.body?.cancel(), isInitializedNotification(message) && this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => this.onerror?.(err));
2532
+ return;
2533
+ }
2534
+ let hasRequests = (Array.isArray(message) ? message : [message]).filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0, contentType2 = response.headers.get("content-type"), responseMediaType = mediaTypeEssence(contentType2);
2535
+ if (hasRequests)
2536
+ if (responseMediaType === "text/event-stream")
2537
+ this._handleSseStream(response.body, { onresumptiontoken }, !1);
2538
+ else if (responseMediaType === "application/json") {
2539
+ let data = await response.json(), responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)];
2540
+ for (let msg of responseMessages)
2541
+ this.onmessage?.(msg);
2542
+ } else
2543
+ throw await response.body?.cancel(), new StreamableHTTPError(-1, `Unexpected content type: ${contentType2}`);
2544
+ else
2545
+ await response.body?.cancel();
2546
+ } catch (error) {
2547
+ throw this.onerror?.(error), error;
2548
+ }
2549
+ }
2550
+ get sessionId() {
2551
+ return this._sessionId;
2552
+ }
2553
+ /**
2554
+ * Terminates the current session by sending a DELETE request to the server.
2555
+ *
2556
+ * Clients that no longer need a particular session
2557
+ * (e.g., because the user is leaving the client application) SHOULD send an
2558
+ * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
2559
+ * terminate the session.
2560
+ *
2561
+ * The server MAY respond with HTTP 405 Method Not Allowed, indicating that
2562
+ * the server does not allow clients to terminate sessions.
2563
+ */
2564
+ async terminateSession() {
2565
+ if (this._sessionId)
2566
+ try {
2567
+ let headers = await this._commonHeaders(), init = {
2568
+ ...this._requestInit,
2569
+ method: "DELETE",
2570
+ headers,
2571
+ signal: this._abortController?.signal
2572
+ }, response = await (this._fetch ?? fetch)(this._url, init);
2573
+ if (await response.body?.cancel(), !response.ok && response.status !== 405)
2574
+ throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);
2575
+ this._sessionId = void 0;
2576
+ } catch (error) {
2577
+ throw this.onerror?.(error), error;
2578
+ }
2579
+ }
2580
+ setProtocolVersion(version) {
2581
+ this._protocolVersion = version;
2582
+ }
2583
+ get protocolVersion() {
2584
+ return this._protocolVersion;
2585
+ }
2586
+ /**
2587
+ * Resume an SSE stream from a previous event ID.
2588
+ * Opens a GET SSE connection with Last-Event-ID header to replay missed events.
2589
+ *
2590
+ * @param lastEventId The event ID to resume from
2591
+ * @param options Optional callback to receive new resumption tokens
2592
+ */
2593
+ async resumeStream(lastEventId, options) {
2594
+ await this._startOrAuthSse({
2595
+ resumptionToken: lastEventId,
2596
+ onresumptiontoken: options?.onresumptiontoken
2597
+ });
2598
+ }
2599
+ };
2600
+
2601
+ // packages/coding-agent/dist/builtin-extensions/pi-mcp-adapter/mcp-auth-flow.js
2602
+ import open from "open";
2603
+
2604
+ // packages/coding-agent/dist/builtin-extensions/pi-mcp-adapter/mcp-auth.js
2605
+ import { createHash } from "crypto";
2606
+ import { mkdirSync, readFileSync, writeFileSync, existsSync, rmSync } from "fs";
2607
+ import { join } from "path";
2608
+ function getAuthBaseDir() {
2609
+ let override = process.env.MCP_OAUTH_DIR?.trim();
2610
+ return override || getAgentPath("mcp-oauth");
2611
+ }
2612
+ function getServerDir(serverName) {
2613
+ if (typeof serverName != "string")
2614
+ throw new Error(`Invalid MCP server name: ${JSON.stringify(serverName)}`);
2615
+ let storageKey = createHash("sha256").update(serverName, "utf8").digest("hex");
2616
+ return join(getAuthBaseDir(), `sha256-${storageKey}`);
2617
+ }
2618
+ function getAuthEntryFilePath(serverName) {
2619
+ return join(getServerDir(serverName), "tokens.json");
2620
+ }
2621
+ function ensureServerDir(serverName) {
2622
+ let dir = getServerDir(serverName);
2623
+ existsSync(dir) || mkdirSync(dir, { recursive: !0, mode: 448 });
2624
+ }
2625
+ function readAuthEntry(serverName) {
2626
+ let filePath = getAuthEntryFilePath(serverName);
2627
+ try {
2628
+ if (!existsSync(filePath))
2629
+ return;
2630
+ let data = readFileSync(filePath, "utf-8");
2631
+ return JSON.parse(data);
2632
+ } catch (error) {
2633
+ console.error(`Failed to read auth entry for ${serverName}:`, error);
2634
+ return;
2635
+ }
2636
+ }
2637
+ function writeAuthEntry(serverName, entry) {
2638
+ ensureServerDir(serverName);
2639
+ let filePath = getAuthEntryFilePath(serverName);
2640
+ writeFileSync(filePath, JSON.stringify(entry, null, 2), { mode: 384 });
2641
+ }
2642
+ function getAuthEntry(serverName) {
2643
+ return readAuthEntry(serverName);
2644
+ }
2645
+ function getAuthForUrl(serverName, serverUrl) {
2646
+ let entry = getAuthEntry(serverName);
2647
+ if (entry && entry.serverUrl && entry.serverUrl === serverUrl)
2648
+ return entry;
2649
+ }
2650
+ function saveAuthEntry(serverName, entry, serverUrl) {
2651
+ serverUrl && (entry.serverUrl = serverUrl), writeAuthEntry(serverName, entry);
2652
+ }
2653
+ function removeAuthEntry(serverName) {
2654
+ try {
2655
+ let filePath = getAuthEntryFilePath(serverName);
2656
+ existsSync(filePath) && writeFileSync(filePath, "{}", { mode: 384 });
2657
+ let dir = getServerDir(serverName);
2658
+ if (existsSync(dir))
2659
+ try {
2660
+ rmSync(dir, { recursive: !0 });
2661
+ } catch {
2662
+ }
2663
+ } catch (error) {
2664
+ console.error(`Failed to remove auth entry for ${serverName}:`, error);
2665
+ }
2666
+ }
2667
+ function updateTokens(serverName, tokens, serverUrl) {
2668
+ let entry = getAuthEntry(serverName) ?? {};
2669
+ serverUrl && entry.serverUrl !== serverUrl && (delete entry.clientInfo, delete entry.codeVerifier, delete entry.oauthState), entry.tokens = tokens, saveAuthEntry(serverName, entry, serverUrl);
2670
+ }
2671
+ function updateClientInfo(serverName, clientInfo, serverUrl) {
2672
+ let entry = getAuthEntry(serverName) ?? {};
2673
+ serverUrl && entry.serverUrl !== serverUrl && (delete entry.tokens, delete entry.codeVerifier, delete entry.oauthState), entry.clientInfo = clientInfo, saveAuthEntry(serverName, entry, serverUrl);
2674
+ }
2675
+ function updateCodeVerifier(serverName, codeVerifier, serverUrl) {
2676
+ let entry = getAuthEntry(serverName) ?? {};
2677
+ serverUrl && entry.serverUrl !== serverUrl && (delete entry.tokens, delete entry.clientInfo, delete entry.oauthState), entry.codeVerifier = codeVerifier, saveAuthEntry(serverName, entry, serverUrl);
2678
+ }
2679
+ function clearCodeVerifier(serverName) {
2680
+ let entry = getAuthEntry(serverName);
2681
+ entry && (delete entry.codeVerifier, saveAuthEntry(serverName, entry));
2682
+ }
2683
+ function updateOAuthState(serverName, state, serverUrl) {
2684
+ let entry = getAuthEntry(serverName) ?? {};
2685
+ serverUrl && entry.serverUrl !== serverUrl && (delete entry.tokens, delete entry.clientInfo, delete entry.codeVerifier), entry.oauthState = state, saveAuthEntry(serverName, entry, serverUrl);
2686
+ }
2687
+ function getOAuthState(serverName) {
2688
+ return getAuthEntry(serverName)?.oauthState;
2689
+ }
2690
+ function clearOAuthState(serverName) {
2691
+ let entry = getAuthEntry(serverName);
2692
+ entry && (delete entry.oauthState, saveAuthEntry(serverName, entry));
2693
+ }
2694
+ function isTokenExpired(serverName) {
2695
+ let entry = getAuthEntry(serverName);
2696
+ return entry?.tokens ? entry.tokens.expiresAt ? entry.tokens.expiresAt < Date.now() / 1e3 : !1 : null;
2697
+ }
2698
+ function hasStoredTokens(serverName) {
2699
+ return !!getAuthEntry(serverName)?.tokens;
2700
+ }
2701
+ function clearAllCredentials(serverName) {
2702
+ removeAuthEntry(serverName);
2703
+ }
2704
+ function clearClientInfo(serverName) {
2705
+ let entry = getAuthEntry(serverName);
2706
+ entry && (delete entry.clientInfo, saveAuthEntry(serverName, entry));
2707
+ }
2708
+ function clearTokens(serverName) {
2709
+ let entry = getAuthEntry(serverName);
2710
+ entry && (delete entry.tokens, saveAuthEntry(serverName, entry));
2711
+ }
2712
+
2713
+ // packages/coding-agent/dist/builtin-extensions/pi-mcp-adapter/mcp-oauth-provider.js
2714
+ var DEFAULT_OAUTH_CALLBACK_PORT = 19876, DEFAULT_OAUTH_CALLBACK_PATH = "/callback", configuredOAuthCallbackPort = DEFAULT_OAUTH_CALLBACK_PORT;
2715
+ if (process.env.MCP_OAUTH_CALLBACK_PORT) {
2716
+ let parsedPort = Number.parseInt(process.env.MCP_OAUTH_CALLBACK_PORT, 10);
2717
+ Number.isInteger(parsedPort) && parsedPort > 0 && parsedPort <= 65535 && (configuredOAuthCallbackPort = parsedPort);
2718
+ }
2719
+ var oauthCallbackPort = configuredOAuthCallbackPort, oauthCallbackPath = DEFAULT_OAUTH_CALLBACK_PATH;
2720
+ function getConfiguredOAuthCallbackPort() {
2721
+ return configuredOAuthCallbackPort;
2722
+ }
2723
+ function getOAuthCallbackPort() {
2724
+ return oauthCallbackPort;
2725
+ }
2726
+ function setOAuthCallbackPort(port) {
2727
+ oauthCallbackPort = port;
2728
+ }
2729
+ function getOAuthCallbackPath() {
2730
+ return oauthCallbackPath;
2731
+ }
2732
+ function setOAuthCallbackPath(path) {
2733
+ oauthCallbackPath = path.startsWith("/") ? path : `/${path}`;
2734
+ }
2735
+ var McpOAuthProvider = class {
2736
+ serverName;
2737
+ serverUrl;
2738
+ config;
2739
+ callbacks;
2740
+ redirectUrlSnapshot;
2741
+ constructor(serverName, serverUrl, config, callbacks) {
2742
+ this.serverName = serverName, this.serverUrl = serverUrl, this.config = config, this.callbacks = callbacks, this.redirectUrlSnapshot = config.grantType === "client_credentials" ? void 0 : config.redirectUri ?? `http://localhost:${getOAuthCallbackPort()}${getOAuthCallbackPath()}`;
2743
+ }
2744
+ get usesClientCredentials() {
2745
+ return this.config.grantType === "client_credentials";
2746
+ }
2747
+ /**
2748
+ * The redirect URL for OAuth callbacks.
2749
+ * This must match the redirect_uri in client metadata.
2750
+ */
2751
+ get redirectUrl() {
2752
+ return this.redirectUrlSnapshot;
2753
+ }
2754
+ /**
2755
+ * Client metadata for dynamic registration.
2756
+ * Describes this client to the OAuth authorization server.
2757
+ */
2758
+ get clientMetadata() {
2759
+ if (this.usesClientCredentials)
2760
+ return {
2761
+ client_name: this.config.clientName ?? "Pi Coding Agent",
2762
+ client_uri: this.config.clientUri ?? "https://github.com/nicobailon/pi-mcp-adapter",
2763
+ redirect_uris: [],
2764
+ grant_types: ["client_credentials"],
2765
+ token_endpoint_auth_method: this.config.clientSecret ? "client_secret_post" : "none"
2766
+ };
2767
+ let redirectUrl = this.redirectUrl;
2768
+ if (!redirectUrl)
2769
+ throw new Error("redirectUrl is required for authorization_code flow");
2770
+ return {
2771
+ redirect_uris: [redirectUrl],
2772
+ client_name: this.config.clientName ?? "Pi Coding Agent",
2773
+ client_uri: this.config.clientUri ?? "https://github.com/nicobailon/pi-mcp-adapter",
2774
+ grant_types: ["authorization_code", "refresh_token"],
2775
+ response_types: ["code"],
2776
+ token_endpoint_auth_method: this.config.clientSecret ? "client_secret_post" : "none",
2777
+ ...this.config.scope !== void 0 ? { scope: this.config.scope } : {}
2778
+ };
2779
+ }
2780
+ /**
2781
+ * Get client information (for pre-registered or dynamically registered clients).
2782
+ * Returns undefined if no client info exists or if the server URL has changed.
2783
+ */
2784
+ async clientInformation() {
2785
+ if (this.config.clientId)
2786
+ return {
2787
+ client_id: this.config.clientId,
2788
+ client_secret: this.config.clientSecret
2789
+ };
2790
+ let entry = await getAuthForUrl(this.serverName, this.serverUrl);
2791
+ if (entry?.clientInfo)
2792
+ return entry.clientInfo.clientSecretExpiresAt && entry.clientInfo.clientSecretExpiresAt < Date.now() / 1e3 ? void 0 : {
2793
+ client_id: entry.clientInfo.clientId,
2794
+ client_secret: entry.clientInfo.clientSecret
2795
+ };
2796
+ }
2797
+ /**
2798
+ * Save client information from dynamic registration.
2799
+ */
2800
+ async saveClientInformation(info) {
2801
+ let redirectUris = info.redirect_uris ?? (this.redirectUrl ? [this.redirectUrl] : void 0), clientInfo = {
2802
+ clientId: info.client_id,
2803
+ clientSecret: info.client_secret,
2804
+ clientIdIssuedAt: info.client_id_issued_at,
2805
+ clientSecretExpiresAt: info.client_secret_expires_at,
2806
+ redirectUris
2807
+ };
2808
+ updateClientInfo(this.serverName, clientInfo, this.serverUrl);
2809
+ }
2810
+ /**
2811
+ * Get stored OAuth tokens.
2812
+ * Returns undefined if no tokens exist or if the server URL has changed.
2813
+ */
2814
+ async tokens() {
2815
+ let entry = await getAuthForUrl(this.serverName, this.serverUrl);
2816
+ if (entry?.tokens)
2817
+ return {
2818
+ access_token: entry.tokens.accessToken,
2819
+ token_type: "Bearer",
2820
+ refresh_token: entry.tokens.refreshToken,
2821
+ expires_in: entry.tokens.expiresAt ? Math.max(0, Math.floor(entry.tokens.expiresAt - Date.now() / 1e3)) : void 0,
2822
+ scope: entry.tokens.scope
2823
+ };
2824
+ }
2825
+ /**
2826
+ * Save OAuth tokens.
2827
+ */
2828
+ async saveTokens(tokens) {
2829
+ let storedTokens = {
2830
+ accessToken: tokens.access_token,
2831
+ refreshToken: tokens.refresh_token,
2832
+ expiresAt: tokens.expires_in ? Date.now() / 1e3 + tokens.expires_in : void 0,
2833
+ scope: tokens.scope
2834
+ };
2835
+ updateTokens(this.serverName, storedTokens, this.serverUrl);
2836
+ }
2837
+ /**
2838
+ * Redirect the user to the authorization URL.
2839
+ * This opens the browser for the user to authenticate.
2840
+ *
2841
+ * Throws UnauthorizedError when called outside of a user-initiated flow
2842
+ * (no oauthState saved by startAuth). That path is reached when the SDK
2843
+ * falls through from a failed refresh into a fresh authorization_code
2844
+ * flow, which library hosts cannot complete in-process.
2845
+ */
2846
+ async redirectToAuthorization(authorizationUrl) {
2847
+ if (this.usesClientCredentials)
2848
+ throw new Error("redirectToAuthorization is not used for client_credentials flow");
2849
+ if (!(await getAuthForUrl(this.serverName, this.serverUrl))?.oauthState)
2850
+ throw new UnauthorizedError(`Re-authentication required for MCP server: ${this.serverName}`);
2851
+ await this.callbacks.onRedirect(authorizationUrl);
2852
+ }
2853
+ /**
2854
+ * Save the PKCE code verifier.
2855
+ */
2856
+ async saveCodeVerifier(codeVerifier) {
2857
+ updateCodeVerifier(this.serverName, codeVerifier, this.serverUrl);
2858
+ }
2859
+ /**
2860
+ * Get the stored PKCE code verifier.
2861
+ * @throws Error if no code verifier is stored
2862
+ */
2863
+ async codeVerifier() {
2864
+ if (this.usesClientCredentials)
2865
+ throw new Error("codeVerifier is not used for client_credentials flow");
2866
+ let entry = await getAuthForUrl(this.serverName, this.serverUrl);
2867
+ if (!entry?.codeVerifier)
2868
+ throw new Error(`No code verifier saved for MCP server: ${this.serverName}`);
2869
+ return entry.codeVerifier;
2870
+ }
2871
+ /**
2872
+ * Save the OAuth state parameter for CSRF protection.
2873
+ */
2874
+ async saveState(state) {
2875
+ updateOAuthState(this.serverName, state, this.serverUrl);
2876
+ }
2877
+ /**
2878
+ * Get the stored OAuth state parameter.
2879
+ * @throws UnauthorizedError if no flow is in progress (see redirectToAuthorization)
2880
+ */
2881
+ async state() {
2882
+ if (this.usesClientCredentials)
2883
+ throw new Error("state is not used for client_credentials flow");
2884
+ let entry = await getAuthForUrl(this.serverName, this.serverUrl);
2885
+ if (!entry?.oauthState)
2886
+ throw new UnauthorizedError(`Re-authentication required for MCP server: ${this.serverName}`);
2887
+ return entry.oauthState;
2888
+ }
2889
+ /**
2890
+ * Invalidate credentials when authentication fails.
2891
+ * Clears tokens, client info, or all credentials based on the type.
2892
+ */
2893
+ async invalidateCredentials(type) {
2894
+ switch (type) {
2895
+ case "all":
2896
+ clearAllCredentials(this.serverName);
2897
+ break;
2898
+ case "client":
2899
+ clearClientInfo(this.serverName);
2900
+ break;
2901
+ case "tokens":
2902
+ clearTokens(this.serverName);
2903
+ break;
2904
+ }
2905
+ }
2906
+ /**
2907
+ * Adds configured authorization-code scope without replacing the SDK's
2908
+ * default token endpoint authentication behavior.
2909
+ */
2910
+ addClientAuthentication = async (headers, params, _url, metadata) => {
2911
+ params.get("grant_type") === "authorization_code" && !params.has("scope") && this.config.scope && params.set("scope", this.config.scope);
2912
+ let clientInfo = await this.clientInformation();
2913
+ if (!clientInfo)
2914
+ return;
2915
+ let supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? [], hasClientSecret = clientInfo.client_secret !== void 0, authMethod;
2916
+ if (supportedMethods.length === 0 ? authMethod = hasClientSecret ? "client_secret_post" : "none" : hasClientSecret && supportedMethods.includes("client_secret_basic") ? authMethod = "client_secret_basic" : hasClientSecret && supportedMethods.includes("client_secret_post") ? authMethod = "client_secret_post" : supportedMethods.includes("none") ? authMethod = "none" : authMethod = hasClientSecret ? "client_secret_post" : "none", authMethod === "client_secret_basic") {
2917
+ if (!clientInfo.client_secret)
2918
+ throw new Error("client_secret_basic authentication requires a client_secret");
2919
+ headers.set("Authorization", `Basic ${Buffer.from(`${clientInfo.client_id}:${clientInfo.client_secret}`).toString("base64")}`);
2920
+ return;
2921
+ }
2922
+ params.has("client_id") || params.set("client_id", clientInfo.client_id), authMethod === "client_secret_post" && clientInfo.client_secret && !params.has("client_secret") && params.set("client_secret", clientInfo.client_secret);
2923
+ };
2924
+ prepareTokenRequest(scope) {
2925
+ if (!this.usesClientCredentials)
2926
+ return;
2927
+ let params = new URLSearchParams({ grant_type: "client_credentials" }), requestedScope = scope ?? this.config.scope;
2928
+ return requestedScope && params.set("scope", requestedScope), params;
2929
+ }
2930
+ };
2931
+
2932
+ // packages/coding-agent/dist/builtin-extensions/pi-mcp-adapter/mcp-callback-server.js
2933
+ import { createServer } from "http";
2934
+ var HTML_SUCCESS = `<!DOCTYPE html>
2935
+ <html>
2936
+ <head>
2937
+ <title>Pi - Authorization Successful</title>
2938
+ <style>
2939
+ body { font-family: system-ui, -apple-system, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #1a1a2e; color: #eee; }
2940
+ .container { text-align: center; padding: 2rem; }
2941
+ h1 { color: #4ade80; margin-bottom: 1rem; }
2942
+ p { color: #aaa; }
2943
+ </style>
2944
+ </head>
2945
+ <body>
2946
+ <div class="container">
2947
+ <h1>Authorization Successful</h1>
2948
+ <p>You can close this window and return to Pi.</p>
2949
+ </div>
2950
+ <script>setTimeout(() => window.close(), 2000);</script>
2951
+ </body>
2952
+ </html>`;
2953
+ function escapeHtml(value) {
2954
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2955
+ }
2956
+ var HTML_ERROR = (error) => `<!DOCTYPE html>
2957
+ <html>
2958
+ <head>
2959
+ <title>Pi - Authorization Failed</title>
2960
+ <style>
2961
+ body { font-family: system-ui, -apple-system, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #1a1a2e; color: #eee; }
2962
+ .container { text-align: center; padding: 2rem; }
2963
+ h1 { color: #f87171; margin-bottom: 1rem; }
2964
+ p { color: #aaa; }
2965
+ .error { color: #fca5a5; font-family: monospace; margin-top: 1rem; padding: 1rem; background: rgba(248,113,113,0.1); border-radius: 0.5rem; }
2966
+ </style>
2967
+ </head>
2968
+ <body>
2969
+ <div class="container">
2970
+ <h1>Authorization Failed</h1>
2971
+ <p>An error occurred during authorization.</p>
2972
+ <div class="error">${escapeHtml(error)}</div>
2973
+ </div>
2974
+ </body>
2975
+ </html>`, server, bindingPromise, pendingAuths = /* @__PURE__ */ new Map(), reservedAuthStates = /* @__PURE__ */ new Set(), CALLBACK_TIMEOUT_MS = 300 * 1e3, DEFAULT_OAUTH_CALLBACK_HOST = "localhost", callbackServerHost = DEFAULT_OAUTH_CALLBACK_HOST;
2976
+ function handleRequest(req, res) {
2977
+ let url2 = new URL(req.url || "/", `http://${req.headers.host}`);
2978
+ if (url2.pathname !== getOAuthCallbackPath()) {
2979
+ res.writeHead(404, { "Content-Type": "text/plain" }), res.end("Not found");
2980
+ return;
2981
+ }
2982
+ let code = url2.searchParams.get("code"), state = url2.searchParams.get("state"), error = url2.searchParams.get("error"), errorDescription = url2.searchParams.get("error_description");
2983
+ if (!state) {
2984
+ let errorMsg = "Missing required state parameter - potential CSRF attack";
2985
+ res.writeHead(400, { "Content-Type": "text/html" }), res.end(HTML_ERROR(errorMsg));
2986
+ return;
2987
+ }
2988
+ let pending = pendingAuths.get(state), isReserved = reservedAuthStates.has(state);
2989
+ if (error) {
2990
+ if (!pending && !isReserved) {
2991
+ let errorMsg2 = "Invalid or expired state parameter - potential CSRF attack";
2992
+ res.writeHead(400, { "Content-Type": "text/html" }), res.end(HTML_ERROR(errorMsg2));
2993
+ return;
2994
+ }
2995
+ let errorMsg = errorDescription || error;
2996
+ res.writeHead(200, { "Content-Type": "text/html" }), res.end(HTML_ERROR(errorMsg)), reservedAuthStates.delete(state), pending && (clearTimeout(pending.timeout), pendingAuths.delete(state), setTimeout(() => pending.reject(new Error(errorMsg)), 0));
2997
+ return;
2998
+ }
2999
+ if (!pending) {
3000
+ let errorMsg = "Invalid or expired state parameter - potential CSRF attack";
3001
+ res.writeHead(400, { "Content-Type": "text/html" }), res.end(HTML_ERROR(errorMsg));
3002
+ return;
3003
+ }
3004
+ if (!code) {
3005
+ res.writeHead(400, { "Content-Type": "text/html" }), res.end(HTML_ERROR("No authorization code provided"));
3006
+ return;
3007
+ }
3008
+ clearTimeout(pending.timeout), pendingAuths.delete(state), pending.resolve(code), res.writeHead(200, { "Content-Type": "text/html" }), res.end(HTML_SUCCESS);
3009
+ }
3010
+ async function ensureCallbackServer(options = {}) {
3011
+ for (; bindingPromise; )
3012
+ await bindingPromise;
3013
+ let operation = ensureCallbackServerLocked(options);
3014
+ bindingPromise = operation;
3015
+ try {
3016
+ await operation;
3017
+ } finally {
3018
+ bindingPromise === operation && (bindingPromise = void 0);
3019
+ }
3020
+ }
3021
+ async function ensureCallbackServerLocked(options = {}) {
3022
+ let requiredPort = options.port ?? getConfiguredOAuthCallbackPort(), strictPort = options.strictPort === !0, requestedHost = options.callbackHost ?? DEFAULT_OAUTH_CALLBACK_HOST, rawRequestedPath = options.callbackPath ?? DEFAULT_OAUTH_CALLBACK_PATH, requestedPath = rawRequestedPath.startsWith("/") ? rawRequestedPath : `/${rawRequestedPath}`;
3023
+ if (options.reserveState && !options.oauthState)
3024
+ throw new Error("OAuth callback reservation requires an oauthState");
3025
+ let reservedState, previousServer = server, needsStrictRebind = !!(previousServer && strictPort && getOAuthCallbackPort() !== requiredPort), needsHostSwitch = !!(previousServer && callbackServerHost !== requestedHost), needsPathSwitch = !!(previousServer && getOAuthCallbackPath() !== requestedPath);
3026
+ if (previousServer) {
3027
+ if (!needsStrictRebind && !needsHostSwitch) {
3028
+ if (needsPathSwitch) {
3029
+ if (pendingAuths.size > 0 || reservedAuthStates.size > 0)
3030
+ throw new Error(`OAuth callback server is using path ${getOAuthCallbackPath()}, but callback path ${requestedPath} is required and cannot be switched while authorizations are pending`);
3031
+ setOAuthCallbackPath(requestedPath);
3032
+ }
3033
+ options.reserveState && options.oauthState && (reservedAuthStates.add(options.oauthState), reservedState = options.oauthState);
3034
+ return;
3035
+ }
3036
+ if (pendingAuths.size > 0 || reservedAuthStates.size > 0)
3037
+ throw new Error(`OAuth callback server is running on ${callbackServerHost}:${getOAuthCallbackPort()}, but strict callback endpoint ${requestedHost}:${requiredPort} is required and cannot be switched while authorizations are pending`);
3038
+ }
3039
+ let candidateServer = createServer(handleRequest), listenPort = strictPort ? requiredPort : 0;
3040
+ try {
3041
+ if (await new Promise((resolve, reject) => {
3042
+ candidateServer.once("error", (err) => {
3043
+ reject(err);
3044
+ }), candidateServer.listen(listenPort, requestedHost, () => {
3045
+ resolve();
3046
+ });
3047
+ }), strictPort)
3048
+ setOAuthCallbackPort(requiredPort);
3049
+ else {
3050
+ let address = candidateServer.address();
3051
+ if (!address || typeof address == "string" || typeof address.port != "number")
3052
+ throw new Error("OAuth callback server did not report an assigned port");
3053
+ setOAuthCallbackPort(address.port);
3054
+ }
3055
+ previousServer && (needsStrictRebind || needsHostSwitch) && await new Promise((resolve) => {
3056
+ previousServer.close(() => resolve());
3057
+ }), callbackServerHost = requestedHost, setOAuthCallbackPath(requestedPath), server = candidateServer, options.reserveState && options.oauthState && (reservedAuthStates.add(options.oauthState), reservedState = options.oauthState), server.unref();
3058
+ } catch (error) {
3059
+ reservedState && reservedAuthStates.delete(reservedState);
3060
+ let nodeError = error;
3061
+ throw await new Promise((resolve) => {
3062
+ candidateServer.close(() => resolve());
3063
+ }), strictPort && nodeError.code === "EADDRINUSE" ? new Error(`OAuth callback port ${requiredPort} is already in use. Pre-registered OAuth clients require an exact redirect URI; set MCP_OAUTH_CALLBACK_PORT to your registered port or free port ${requiredPort}`, { cause: error }) : error;
3064
+ }
3065
+ }
3066
+ function releaseCallbackServer(oauthState) {
3067
+ reservedAuthStates.delete(oauthState);
3068
+ }
3069
+ function waitForCallback(oauthState) {
3070
+ return reservedAuthStates.delete(oauthState), new Promise((resolve, reject) => {
3071
+ let timeout = setTimeout(() => {
3072
+ pendingAuths.has(oauthState) && (pendingAuths.delete(oauthState), reject(new Error("OAuth callback timeout - authorization took too long")));
3073
+ }, CALLBACK_TIMEOUT_MS);
3074
+ pendingAuths.set(oauthState, { resolve, reject, timeout });
3075
+ });
3076
+ }
3077
+ function cancelPendingCallback(oauthState) {
3078
+ reservedAuthStates.delete(oauthState);
3079
+ let pending = pendingAuths.get(oauthState);
3080
+ pending && (clearTimeout(pending.timeout), pendingAuths.delete(oauthState), pending.reject(new Error("Authorization cancelled")));
3081
+ }
3082
+ async function stopCallbackServer() {
3083
+ server && (await new Promise((resolve) => {
3084
+ server.close(() => {
3085
+ resolve();
3086
+ });
3087
+ }), server = void 0), setOAuthCallbackPort(getConfiguredOAuthCallbackPort()), callbackServerHost = DEFAULT_OAUTH_CALLBACK_HOST, setOAuthCallbackPath(DEFAULT_OAUTH_CALLBACK_PATH);
3088
+ let pendingList = Array.from(pendingAuths.entries());
3089
+ pendingAuths.clear(), reservedAuthStates.clear(), setTimeout(() => {
3090
+ for (let [, pending] of pendingList)
3091
+ clearTimeout(pending.timeout), pending.reject(new Error("OAuth callback server stopped"));
3092
+ }, 0);
3093
+ }
3094
+
3095
+ // packages/coding-agent/dist/builtin-extensions/pi-mcp-adapter/mcp-auth-flow.js
3096
+ var pendingTransports = /* @__PURE__ */ new Map(), pendingAuthStates = /* @__PURE__ */ new Map(), pendingAuthCleanupTimers = /* @__PURE__ */ new Map(), pendingAuthentications = /* @__PURE__ */ new Map(), MANUAL_AUTH_TIMEOUT_MS = 300 * 1e3;
3097
+ function generateState() {
3098
+ return Array.from(crypto.getRandomValues(new Uint8Array(32))).map((b) => b.toString(16).padStart(2, "0")).join("");
3099
+ }
3100
+ function extractOAuthConfig(definition) {
3101
+ if (definition.oauth === !1)
3102
+ return {};
3103
+ let config = {};
3104
+ if (definition.oauth?.grantType !== void 0 && (config.grantType = definition.oauth.grantType), definition.oauth?.clientId !== void 0 && (config.clientId = definition.oauth.clientId), definition.oauth?.clientSecret !== void 0 && (config.clientSecret = definition.oauth.clientSecret), definition.oauth?.scope !== void 0 && (config.scope = definition.oauth.scope), definition.oauth?.redirectUri !== void 0) {
3105
+ if (typeof definition.oauth.redirectUri != "string")
3106
+ throw new Error("OAuth redirectUri must be a string");
3107
+ let redirectUri = definition.oauth.redirectUri.trim();
3108
+ if (!redirectUri)
3109
+ throw new Error("OAuth redirectUri must not be empty");
3110
+ config.redirectUri = redirectUri;
3111
+ }
3112
+ if (definition.oauth?.clientName !== void 0) {
3113
+ if (typeof definition.oauth.clientName != "string")
3114
+ throw new Error("OAuth clientName must be a string");
3115
+ let clientName = definition.oauth.clientName.trim();
3116
+ if (!clientName)
3117
+ throw new Error("OAuth clientName must not be empty");
3118
+ config.clientName = clientName;
3119
+ }
3120
+ if (definition.oauth?.clientUri !== void 0) {
3121
+ if (typeof definition.oauth.clientUri != "string")
3122
+ throw new Error("OAuth clientUri must be a string");
3123
+ let clientUri = definition.oauth.clientUri.trim();
3124
+ if (!clientUri)
3125
+ throw new Error("OAuth clientUri must not be empty");
3126
+ config.clientUri = clientUri;
3127
+ }
3128
+ return config;
3129
+ }
3130
+ function parseOAuthRedirectUri(redirectUri) {
3131
+ let url2;
3132
+ try {
3133
+ url2 = new URL(redirectUri);
3134
+ } catch (error) {
3135
+ throw new Error(`Invalid OAuth redirectUri: ${redirectUri}`, { cause: error });
3136
+ }
3137
+ let hostname = url2.hostname.toLowerCase(), isLocalhost = hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
3138
+ if (url2.protocol !== "http:" || !isLocalhost)
3139
+ throw new Error("OAuth redirectUri must be an http:// localhost or loopback URI");
3140
+ if (url2.username || url2.password)
3141
+ throw new Error("OAuth redirectUri must not include username or password");
3142
+ if (url2.hash)
3143
+ throw new Error("OAuth redirectUri must not include a fragment");
3144
+ if (!url2.port)
3145
+ throw new Error("OAuth redirectUri must include an explicit numeric port");
3146
+ let port = Number.parseInt(url2.port, 10);
3147
+ if (!Number.isInteger(port) || port <= 0 || port > 65535)
3148
+ throw new Error("OAuth redirectUri must include an explicit numeric port");
3149
+ return { port, callbackHost: hostname === "[::1]" ? "::1" : hostname, callbackPath: url2.pathname };
3150
+ }
3151
+ async function startAuth(serverName, serverUrl, definition) {
3152
+ let config = definition ? extractOAuthConfig(definition) : {};
3153
+ if (config.grantType === "client_credentials") {
3154
+ let storedAuth = await getAuthForUrl(serverName, serverUrl);
3155
+ storedAuth?.clientInfo && !storedAuth.tokens && !config.clientId && (clearClientInfo(serverName), clearCodeVerifier(serverName), await clearOAuthState(serverName));
3156
+ let authProvider2 = new McpOAuthProvider(serverName, serverUrl, config, {
3157
+ onRedirect: async () => {
3158
+ throw new Error("Browser redirect is not used for client_credentials flow");
3159
+ }
3160
+ });
3161
+ if (await auth(authProvider2, { serverUrl }) !== "AUTHORIZED")
3162
+ throw new UnauthorizedError("Failed to authorize");
3163
+ return { authorizationUrl: "" };
3164
+ }
3165
+ let redirectCallback = config.redirectUri !== void 0 ? parseOAuthRedirectUri(config.redirectUri) : void 0, oauthState = generateState();
3166
+ try {
3167
+ await ensureCallbackServer({
3168
+ strictPort: !!config.clientId || config.redirectUri !== void 0,
3169
+ oauthState,
3170
+ reserveState: !0,
3171
+ ...redirectCallback ? { port: redirectCallback.port, callbackHost: redirectCallback.callbackHost, callbackPath: redirectCallback.callbackPath } : {}
3172
+ });
3173
+ } catch (error) {
3174
+ throw await clearOAuthState(serverName), error;
3175
+ }
3176
+ let capturedUrl, authProvider = new McpOAuthProvider(serverName, serverUrl, config, {
3177
+ onRedirect: async (url2) => {
3178
+ capturedUrl = url2;
3179
+ }
3180
+ });
3181
+ try {
3182
+ let storedAuth = await getAuthForUrl(serverName, serverUrl);
3183
+ if (storedAuth?.clientInfo && !config.clientId)
3184
+ if (!storedAuth.tokens)
3185
+ clearClientInfo(serverName), clearCodeVerifier(serverName), await clearOAuthState(serverName);
3186
+ else {
3187
+ let redirectUris = storedAuth.clientInfo.redirectUris;
3188
+ (!Array.isArray(redirectUris) || !redirectUris.includes(authProvider.redirectUrl ?? "")) && (clearClientInfo(serverName), clearTokens(serverName), clearCodeVerifier(serverName), await clearOAuthState(serverName));
3189
+ }
3190
+ if (await updateOAuthState(serverName, oauthState, serverUrl), await auth(authProvider, { serverUrl }) === "AUTHORIZED")
3191
+ return releaseCallbackServer(oauthState), await clearOAuthState(serverName), { authorizationUrl: "" };
3192
+ if (!capturedUrl)
3193
+ throw new UnauthorizedError("OAuth authorization URL was not provided");
3194
+ let pendingTransport = new StreamableHTTPClientTransport(new URL(serverUrl), { authProvider });
3195
+ return await setPendingTransport(serverName, pendingTransport, oauthState), { authorizationUrl: capturedUrl.toString() };
3196
+ } catch (error) {
3197
+ throw await clearPendingAuth(serverName, oauthState), error;
3198
+ }
3199
+ }
3200
+ async function setPendingTransport(serverName, transport, oauthState) {
3201
+ await clearPendingAuth(serverName), pendingTransports.set(serverName, transport), pendingAuthStates.set(serverName, oauthState);
3202
+ let cleanupTimer = setTimeout(() => {
3203
+ clearPendingAuth(serverName, oauthState);
3204
+ }, MANUAL_AUTH_TIMEOUT_MS);
3205
+ cleanupTimer.unref?.(), pendingAuthCleanupTimers.set(serverName, cleanupTimer);
3206
+ }
3207
+ async function clearPendingAuth(serverName, oauthState) {
3208
+ let pendingState = pendingAuthStates.get(serverName);
3209
+ if (oauthState && pendingState && pendingState !== oauthState)
3210
+ return;
3211
+ let timer = pendingAuthCleanupTimers.get(serverName);
3212
+ timer && (clearTimeout(timer), pendingAuthCleanupTimers.delete(serverName));
3213
+ let transport = pendingTransports.get(serverName);
3214
+ pendingTransports.delete(serverName), pendingAuthStates.delete(serverName);
3215
+ let stateToRelease = pendingState ?? oauthState;
3216
+ stateToRelease && (releaseCallbackServer(stateToRelease), await getOAuthState(serverName) === stateToRelease && await clearOAuthState(serverName)), transport && await transport.close().catch(() => {
3217
+ });
3218
+ }
3219
+ function getSearchParamsFromInput(input) {
3220
+ try {
3221
+ let url2 = new URL(input), params = new URLSearchParams(url2.search);
3222
+ if (url2.hash) {
3223
+ let hash = url2.hash.startsWith("#") ? url2.hash.slice(1) : url2.hash, hashParams = new URLSearchParams(hash);
3224
+ for (let [key, value] of hashParams)
3225
+ params.has(key) || params.set(key, value);
3226
+ }
3227
+ return params;
3228
+ } catch {
3229
+ let query = input.includes("?") ? input.slice(input.indexOf("?") + 1) : input, params = new URLSearchParams(query.startsWith("#") ? query.slice(1) : query);
3230
+ return params.has("code") || params.has("state") || params.has("error") ? params : void 0;
3231
+ }
3232
+ }
3233
+ function parseAuthorizationCodeInput(input, expectedState) {
3234
+ let trimmed = input.trim();
3235
+ if (!trimmed)
3236
+ throw new Error("Authorization code or redirect URL is required");
3237
+ let params = getSearchParamsFromInput(trimmed);
3238
+ if (params) {
3239
+ let error = params.get("error");
3240
+ if (error) {
3241
+ let description = params.get("error_description");
3242
+ throw new Error(description ? `${error}: ${description}` : error);
3243
+ }
3244
+ let state = params.get("state");
3245
+ if (expectedState && !state)
3246
+ throw new Error("OAuth state missing from redirect URL");
3247
+ if (expectedState && state !== expectedState)
3248
+ throw new Error("OAuth state mismatch - potential CSRF attack");
3249
+ let code = params.get("code");
3250
+ if (code)
3251
+ return code;
3252
+ }
3253
+ if (/^[A-Za-z0-9._~+/=-]+$/.test(trimmed))
3254
+ return trimmed;
3255
+ throw new Error("Could not find an OAuth authorization code in the provided input");
3256
+ }
3257
+ async function completeAuthFromInput(serverName, input) {
3258
+ let oauthState = await getOAuthState(serverName), code = parseAuthorizationCodeInput(input, oauthState);
3259
+ return completeAuth(serverName, code);
3260
+ }
3261
+ async function completeAuth(serverName, authorizationCode) {
3262
+ let transport = pendingTransports.get(serverName);
3263
+ if (!transport)
3264
+ throw new Error(`No pending OAuth flow for server: ${serverName}`);
3265
+ let oauthState = await getOAuthState(serverName);
3266
+ try {
3267
+ return await transport.finishAuth(authorizationCode), "authenticated";
3268
+ } finally {
3269
+ await clearPendingAuth(serverName, oauthState);
3270
+ }
3271
+ }
3272
+ async function authenticate(serverName, serverUrl, definition, options = {}) {
3273
+ let inFlight = pendingAuthentications.get(serverName);
3274
+ if (inFlight)
3275
+ return inFlight;
3276
+ let operation = (async () => {
3277
+ let { authorizationUrl } = await startAuth(serverName, serverUrl, definition);
3278
+ if (!authorizationUrl)
3279
+ return "authenticated";
3280
+ let oauthState = await getOAuthState(serverName);
3281
+ if (!oauthState)
3282
+ throw new Error("OAuth state not found - this should not happen");
3283
+ let callbackPromise = waitForCallback(oauthState);
3284
+ try {
3285
+ options.onAuthorizationUrl ? await options.onAuthorizationUrl(authorizationUrl) : console.log(`MCP Auth: Open this URL to authenticate ${serverName}:
3286
+ ${authorizationUrl}`);
3287
+ try {
3288
+ await open(authorizationUrl);
3289
+ } catch (error) {
3290
+ console.warn(`MCP Auth: Failed to open browser for ${serverName}; waiting for manual callback`, { error });
3291
+ }
3292
+ let code = await callbackPromise;
3293
+ if (await getOAuthState(serverName) !== oauthState)
3294
+ throw await clearOAuthState(serverName), new Error("OAuth state mismatch - potential CSRF attack");
3295
+ return await clearOAuthState(serverName), await completeAuth(serverName, code);
3296
+ } catch (error) {
3297
+ throw cancelPendingCallback(oauthState), await clearPendingAuth(serverName, oauthState), error;
3298
+ }
3299
+ })();
3300
+ pendingAuthentications.set(serverName, operation);
3301
+ try {
3302
+ return await operation;
3303
+ } finally {
3304
+ pendingAuthentications.get(serverName) === operation && pendingAuthentications.delete(serverName);
3305
+ }
3306
+ }
3307
+ async function getValidToken(serverName, serverUrl) {
3308
+ let entry = await getAuthForUrl(serverName, serverUrl);
3309
+ if (!entry?.tokens)
3310
+ return null;
3311
+ let expired = await isTokenExpired(serverName);
3312
+ if (expired === !1)
3313
+ return entry.tokens;
3314
+ if (expired === !0 && entry.tokens.refreshToken) {
3315
+ console.log(`MCP Auth: Token expired for ${serverName}, attempting refresh`);
3316
+ try {
3317
+ let authProvider = new McpOAuthProvider(serverName, serverUrl, {}, {
3318
+ onRedirect: async () => {
3319
+ }
3320
+ });
3321
+ return await authProvider.clientInformation() ? await auth(authProvider, { serverUrl }) !== "AUTHORIZED" ? null : (await getAuthForUrl(serverName, serverUrl))?.tokens ?? null : (console.log(`MCP Auth: No client info for refresh for ${serverName}`), null);
3322
+ } catch (error) {
3323
+ return console.error(`MCP Auth: Token refresh failed for ${serverName}`, { error }), null;
3324
+ }
3325
+ }
3326
+ return entry.tokens;
3327
+ }
3328
+ async function getAuthStatus(serverName) {
3329
+ return await hasStoredTokens(serverName) ? await isTokenExpired(serverName) ? "expired" : "authenticated" : "not_authenticated";
3330
+ }
3331
+ async function removeAuth(serverName) {
3332
+ let oauthState = await getOAuthState(serverName);
3333
+ oauthState && cancelPendingCallback(oauthState), await clearPendingAuth(serverName, oauthState), clearAllCredentials(serverName), await clearOAuthState(serverName), console.log(`MCP Auth: Removed credentials for ${serverName}`);
3334
+ }
3335
+ function supportsOAuth(definition) {
3336
+ return !definition.url || definition.auth === !1 || definition.oauth === !1 ? !1 : definition.auth === "oauth" ? !0 : definition.headers && Object.keys(definition.headers).length > 0 ? !1 : definition.auth === void 0;
3337
+ }
3338
+ async function initializeOAuth() {
3339
+ }
3340
+ async function shutdownOAuth() {
3341
+ for (let serverName of Array.from(pendingTransports.keys()))
3342
+ await clearPendingAuth(serverName);
3343
+ await stopCallbackServer();
3344
+ }
3345
+
3346
+ export {
3347
+ LATEST_PROTOCOL_VERSION,
3348
+ SUPPORTED_PROTOCOL_VERSIONS,
3349
+ RELATED_TASK_META_KEY,
3350
+ isTaskAugmentedRequestParams,
3351
+ RequestIdSchema,
3352
+ isJSONRPCRequest,
3353
+ isJSONRPCNotification,
3354
+ isJSONRPCResultResponse,
3355
+ ErrorCode,
3356
+ isJSONRPCErrorResponse,
3357
+ JSONRPCMessageSchema,
3358
+ EmptyResultSchema,
3359
+ CancelledNotificationSchema,
3360
+ ImplementationSchema,
3361
+ InitializeResultSchema,
3362
+ PingRequestSchema,
3363
+ ProgressNotificationSchema,
3364
+ CreateTaskResultSchema,
3365
+ TaskStatusNotificationSchema,
3366
+ GetTaskRequestSchema,
3367
+ GetTaskResultSchema,
3368
+ GetTaskPayloadRequestSchema,
3369
+ ListTasksRequestSchema,
3370
+ ListTasksResultSchema,
3371
+ CancelTaskRequestSchema,
3372
+ CancelTaskResultSchema,
3373
+ ListResourcesResultSchema,
3374
+ ListResourceTemplatesResultSchema,
3375
+ ReadResourceResultSchema,
3376
+ ResourceListChangedNotificationSchema,
3377
+ ListPromptsResultSchema,
3378
+ EmbeddedResourceSchema,
3379
+ ResourceLinkSchema,
3380
+ ContentBlockSchema,
3381
+ GetPromptResultSchema,
3382
+ PromptListChangedNotificationSchema,
3383
+ ToolSchema,
3384
+ ListToolsResultSchema,
3385
+ CallToolResultSchema,
3386
+ ToolListChangedNotificationSchema,
3387
+ ListChangedOptionsBaseSchema,
3388
+ CreateMessageRequestSchema,
3389
+ CreateMessageResultSchema,
3390
+ CreateMessageResultWithToolsSchema,
3391
+ ElicitRequestSchema,
3392
+ ElicitationCompleteNotificationSchema,
3393
+ ElicitResultSchema,
3394
+ CompleteResultSchema,
3395
+ McpError,
3396
+ UrlElicitationRequiredError,
3397
+ normalizeHeaders,
3398
+ createFetchWithInit,
3399
+ UnauthorizedError,
3400
+ auth,
3401
+ extractWWWAuthenticateParams,
3402
+ createParser,
3403
+ StreamableHTTPClientTransport,
3404
+ getAuthForUrl,
3405
+ McpOAuthProvider,
3406
+ extractOAuthConfig,
3407
+ startAuth,
3408
+ parseAuthorizationCodeInput,
3409
+ completeAuthFromInput,
3410
+ completeAuth,
3411
+ authenticate,
3412
+ getValidToken,
3413
+ getAuthStatus,
3414
+ removeAuth,
3415
+ supportsOAuth,
3416
+ initializeOAuth,
3417
+ shutdownOAuth
3418
+ };
3419
+ /*! Bundled license information:
3420
+
3421
+ content-type/index.js:
3422
+ (*!
3423
+ * content-type
3424
+ * Copyright(c) 2015 Douglas Christopher Wilson
3425
+ * MIT Licensed
3426
+ *)
3427
+ */