@arcgis/ai-components 6.0.0-next.0 → 6.0.0-next.2

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 (374) hide show
  1. package/dist/agent-utils/BaseAgent.js +1 -1
  2. package/dist/agent-utils/FunctionAgent.js +1 -1
  3. package/dist/agent-utils/LLMAgent.d.ts +9 -2
  4. package/dist/agent-utils/LLMAgent.js +46 -37
  5. package/dist/agent-utils/SkillAgent.js +1 -1
  6. package/dist/agent-utils/WorkflowAgent.js +1 -1
  7. package/dist/agent-utils/createSchema.js +1 -1
  8. package/dist/agent-utils/middlewares/humanInTheLoop.js +1 -1
  9. package/dist/agent-utils/middlewares/middleware.js +1 -1
  10. package/dist/agent-utils/middlewares/trace.js +1 -1
  11. package/dist/agent-utils/middlewares/types.js +1 -1
  12. package/dist/agent-utils/tools/FunctionTool.d.ts +12 -1
  13. package/dist/agent-utils/tools/FunctionTool.js +16 -15
  14. package/dist/agent-utils/tools/MCPToolProvider.d.ts +54 -0
  15. package/dist/agent-utils/tools/MCPToolProvider.js +120 -0
  16. package/dist/agent-utils/tools/ToolProvider.d.ts +13 -0
  17. package/dist/agent-utils/tools/WebMCPToolProvider.d.ts +37 -0
  18. package/dist/agent-utils/tools/WebMCPToolProvider.js +71 -0
  19. package/dist/agent-utils/workflows/ConditionalWorkflow.js +1 -1
  20. package/dist/agent-utils/workflows/LoopWorkflow.js +1 -1
  21. package/dist/agent-utils/workflows/ParallelWorkflow.js +1 -1
  22. package/dist/agent-utils/workflows/RouterWorkflow.js +1 -1
  23. package/dist/agent-utils/workflows/SequentialWorkflow.js +1 -1
  24. package/dist/agent-utils/workflows/SwitchWorkflow.js +1 -1
  25. package/dist/agents/agents/arcgisKnowledge/graph/arcgisKnowledgeGraph.js +1 -1
  26. package/dist/agents/agents/dataExploration/dataExplorationAgent.js +1 -1
  27. package/dist/agents/agents/dataExplorationGraph/graph/dataExplorationGraph.js +1 -1
  28. package/dist/agents/agents/help/helpAgent.js +1 -1
  29. package/dist/agents/agents/helpGraph/graph/helpGraph.js +1 -1
  30. package/dist/agents/agents/layerStyling/context/layerStylingContext.js +1 -1
  31. package/dist/agents/agents/layerStyling/graph/layerStylingGraph.js +1 -1
  32. package/dist/agents/agents/navigation/navigationAgent.js +1 -1
  33. package/dist/agents/agents/navigationGraph/graph/navigationGraph.js +1 -1
  34. package/dist/agents/tools/filter/clearFilters/adapter.js +1 -1
  35. package/dist/agents/tools/filter/resetMap/adapter.js +1 -1
  36. package/dist/agents/tools/filter/setFeatureEffect/adapter.js +1 -1
  37. package/dist/agents/tools/help/listFields/adapter.js +1 -1
  38. package/dist/agents/tools/navigation/goToAddress/adapter.js +1 -1
  39. package/dist/agents/tools/navigation/goToBookmark/adapter.js +1 -1
  40. package/dist/agents/tools/navigation/goToFeatures/adapter.js +1 -1
  41. package/dist/agents/tools/navigation/goToFullExtent/adapter.js +1 -1
  42. package/dist/agents/tools/navigation/goToHomeExtent/adapter.js +1 -1
  43. package/dist/agents/tools/navigation/goToLayer/adapter.js +1 -1
  44. package/dist/agents/tools/navigation/goToScale/adapter.js +1 -1
  45. package/dist/agents/tools/navigation/goToViewpoint/adapter.js +1 -1
  46. package/dist/agents/tools/navigation/goToZoom/adapter.js +1 -1
  47. package/dist/agents/tools/query/getAttribute/adapter.js +29 -25
  48. package/dist/agents/tools/query/getStatistics/adapter.js +71 -67
  49. package/dist/agents/tools/query/getTopFeatures/adapter.js +75 -71
  50. package/dist/agents/tools/query/queryFeatures/adapter.js +41 -37
  51. package/dist/agents/tools/search/findRelevantFields/adapter.js +1 -1
  52. package/dist/agents/tools/search/findRelevantLayers/adapter.js +1 -1
  53. package/dist/agents/tools/shared/resolveToolArtifact.js +1 -1
  54. package/dist/agents/tools/shared/types.js +1 -1
  55. package/dist/cdn/24KEZCPF.js +2 -0
  56. package/dist/cdn/{2UKFCF2J.js → 272R36XK.js} +2 -2
  57. package/dist/cdn/{FX4LV2S3.js → 2H32MDP2.js} +1 -1
  58. package/dist/cdn/{VAXH6RUQ.js → 2HNGMLFD.js} +2 -2
  59. package/dist/cdn/{3HV6OXCZ.js → 2JD3G7IW.js} +2 -2
  60. package/dist/cdn/2NOLMOEP.js +9 -0
  61. package/dist/cdn/{ZU2FHVNK.js → 2OW3DCUT.js} +2 -2
  62. package/dist/cdn/2PGZDONH.js +2 -0
  63. package/dist/cdn/2WY5MPMY.js +2 -0
  64. package/dist/cdn/{4OLV5LA7.js → 3COVQI26.js} +2 -2
  65. package/dist/cdn/{VIJVRJHL.js → 3UVQLYUK.js} +2 -2
  66. package/dist/cdn/{BIEX4MVV.js → 5HNKH5OK.js} +2 -2
  67. package/dist/cdn/{46DT6BIG.js → 5INBG23U.js} +1 -1
  68. package/dist/cdn/{MHUEU6MR.js → 5LBUP33F.js} +2 -2
  69. package/dist/cdn/{UZLQALHY.js → 5PV2GUZW.js} +1 -1
  70. package/dist/cdn/{UYEF3IKE.js → 5SRRG7WG.js} +2 -2
  71. package/dist/cdn/{AMFZY5QK.js → 5XZ5VL42.js} +2 -2
  72. package/dist/cdn/{IEAHAC6B.js → 63OF33IL.js} +2 -2
  73. package/dist/cdn/{7OQA4GCM.js → 6ELWX4W5.js} +2 -2
  74. package/dist/cdn/{OKVLGJAG.js → 6J3J7VLW.js} +2 -2
  75. package/dist/cdn/{AOVJ34QE.js → 6QOSUG64.js} +2 -2
  76. package/dist/cdn/{GVFJHADC.js → 6UGT2UG5.js} +2 -2
  77. package/dist/cdn/{VVWKEN53.js → 7APXFHDF.js} +3 -3
  78. package/dist/cdn/{QJOO6IIX.js → 7GDMXAF5.js} +2 -2
  79. package/dist/cdn/7JIXXYZR.js +2 -0
  80. package/dist/cdn/{2ZH5JNHL.js → 7OQK2F7O.js} +2 -2
  81. package/dist/cdn/{I7PHDOEQ.js → 7XVIZ7HK.js} +2 -2
  82. package/dist/cdn/{TRZJYWEB.js → A4ZVCRVF.js} +3 -3
  83. package/dist/cdn/{OVIQ5NSE.js → AGDGDULE.js} +2 -2
  84. package/dist/cdn/{TPULIO6I.js → AMA67DVI.js} +2 -2
  85. package/dist/cdn/AO42IPOX.js +2 -0
  86. package/dist/cdn/AOT3PM2Q.js +2 -0
  87. package/dist/cdn/{YO3L3XIH.js → AQ7KG25Q.js} +2 -2
  88. package/dist/cdn/{KKXOSV62.js → AWH4VDPD.js} +2 -2
  89. package/dist/cdn/AY2ZONWQ.js +2 -0
  90. package/dist/cdn/{B2JRBDJZ.js → BMVPOFHU.js} +2 -2
  91. package/dist/cdn/BWUQRZPK.js +2 -0
  92. package/dist/cdn/{EXIA3APU.js → C3VLDYS2.js} +2 -2
  93. package/dist/cdn/{PQ2DPOFM.js → C5Q6E7UC.js} +2 -2
  94. package/dist/cdn/{FDOMMK2M.js → CETIZ4IQ.js} +1 -1
  95. package/dist/cdn/{W3OJTTVX.js → COANVCKH.js} +2 -2
  96. package/dist/cdn/D7CRICBG.js +2 -0
  97. package/dist/cdn/D7FEOAW3.js +2 -0
  98. package/dist/cdn/{37EJSNE3.js → DY6MO2CA.js} +2 -2
  99. package/dist/cdn/EKMCGN6R.js +2 -0
  100. package/dist/cdn/EUIURCPS.js +2 -0
  101. package/dist/cdn/{NN6MELJ7.js → FGQH46Z2.js} +2 -2
  102. package/dist/cdn/FIZMK7GS.js +1 -0
  103. package/dist/cdn/FONIQ7VF.js +2 -0
  104. package/dist/cdn/G3KILEGJ.js +2 -0
  105. package/dist/cdn/{FYZATVB3.js → G7MCIFV2.js} +2 -2
  106. package/dist/cdn/{SDWWUWAF.js → GGAXXX5X.js} +2 -2
  107. package/dist/cdn/GS5JDPZH.js +2 -0
  108. package/dist/cdn/{KJZVYKWL.js → H4QWVTEZ.js} +2 -2
  109. package/dist/cdn/{HWNPZ4CF.js → H6J65TWL.js} +2 -2
  110. package/dist/cdn/{UHEYPSOR.js → HCPI2RJE.js} +2 -2
  111. package/dist/cdn/{TPMZRJEC.js → HJOWCZPL.js} +2 -2
  112. package/dist/cdn/HOMSK66Q.js +2 -0
  113. package/dist/cdn/{SBIYXWXZ.js → HTNKDDEV.js} +2 -2
  114. package/dist/cdn/{OFM2S6U7.js → HU527DML.js} +2 -2
  115. package/dist/cdn/I37ZJHTM.js +2 -0
  116. package/dist/cdn/{7DRHB24Z.js → I724KIFI.js} +2 -2
  117. package/dist/cdn/IH5P2PWJ.js +2 -0
  118. package/dist/cdn/{ZBRZU4XB.js → J3T5HB77.js} +2 -2
  119. package/dist/cdn/{ZMMUAYDN.js → JCWFLYB4.js} +2 -2
  120. package/dist/cdn/{IHP25JWI.js → JSRNLNOE.js} +2 -2
  121. package/dist/cdn/{MPWEXYYB.js → KDA5VPLO.js} +2 -2
  122. package/dist/cdn/KRPPMEOF.js +2 -0
  123. package/dist/cdn/{W6TS2TIE.js → KURNYULZ.js} +2 -2
  124. package/dist/cdn/{YOQCQAKT.js → L46O52F7.js} +2 -2
  125. package/dist/cdn/{W3ZLMBEE.js → L5OYOLWV.js} +3 -3
  126. package/dist/cdn/{M7TMD2HP.js → LDDP7NSY.js} +2 -2
  127. package/dist/cdn/{ZQTCPJUV.js → LGIXZLOP.js} +2 -2
  128. package/dist/cdn/{ENVTUTY6.js → LMAIOLS2.js} +2 -2
  129. package/dist/cdn/{CFAC4FN3.js → LWEKPFV6.js} +2 -2
  130. package/dist/cdn/M52LKZN7.js +2 -0
  131. package/dist/cdn/{6GQCLDLJ.js → M5UMOOL2.js} +2 -2
  132. package/dist/cdn/MHXM37QI.js +2 -0
  133. package/dist/cdn/{XI4BPYGB.js → MR3R5YHQ.js} +2 -2
  134. package/dist/cdn/{H7WJUUJT.js → MUSLUFKI.js} +2 -2
  135. package/dist/cdn/MYLY2ABI.js +2 -0
  136. package/dist/cdn/{2XXM52PS.js → N2GN5WOI.js} +3 -3
  137. package/dist/cdn/{2FUTKTNO.js → NAVK5JJ2.js} +3 -3
  138. package/dist/cdn/NDSYDURO.js +2 -0
  139. package/dist/cdn/{EU6YSCZL.js → NK2QRPS6.js} +2 -2
  140. package/dist/cdn/{GMZUN5SF.js → NYFL2F5L.js} +2 -2
  141. package/dist/cdn/{O62IJLTZ.js → OKDXM5D4.js} +2 -2
  142. package/dist/cdn/{I5OBL24F.js → OMUWBY75.js} +2 -2
  143. package/dist/cdn/{34O57OGV.js → OPQCY33W.js} +1 -1
  144. package/dist/cdn/{R74ZHFA6.js → OUMTV5H5.js} +1 -1
  145. package/dist/cdn/OZDRETY2.js +5 -0
  146. package/dist/cdn/{DYSPEU7W.js → PR4VMSKD.js} +1 -1
  147. package/dist/cdn/{V7ERVXIO.js → PXBS2FXE.js} +2 -2
  148. package/dist/cdn/{B4C7NIB5.js → Q7BJGEFH.js} +3 -3
  149. package/dist/cdn/QAVDW7A7.js +2 -0
  150. package/dist/cdn/{ONQ6JSBJ.js → QBZP6XOE.js} +1 -1
  151. package/dist/cdn/{OT5ECP4V.js → RFIN7KO6.js} +2 -2
  152. package/dist/cdn/RNJ7T5GF.js +2 -0
  153. package/dist/cdn/{Q6PCXSZT.js → S6OUM5X2.js} +2 -2
  154. package/dist/cdn/SG6PAUVR.js +2 -0
  155. package/dist/cdn/{U53SVXZK.js → SRXUC4QB.js} +2 -2
  156. package/dist/cdn/SUMXIUIS.js +2 -0
  157. package/dist/cdn/SW3D6QD4.js +2 -0
  158. package/dist/cdn/{GEFFWUB2.js → T2OYUOSO.js} +1 -1
  159. package/dist/cdn/T7LYQ56H.js +2 -0
  160. package/dist/cdn/{T2FKFOHE.js → TFXK2POV.js} +2 -2
  161. package/dist/cdn/{XQ3NBBQ3.js → TIQUULA4.js} +1 -1
  162. package/dist/cdn/{LCI5MEDN.js → TOUYGIGK.js} +2 -2
  163. package/dist/cdn/{DWMZ23QK.js → UJMM5QA4.js} +2 -2
  164. package/dist/cdn/UMTRLI63.js +2 -0
  165. package/dist/cdn/{MQSOVP27.js → UP7RW5K2.js} +2 -2
  166. package/dist/cdn/{J37GSI7C.js → UR2S7L6Z.js} +2 -2
  167. package/dist/cdn/{CEKOEHB3.js → UWHRBGWN.js} +2 -2
  168. package/dist/cdn/UXDRYDOD.js +11 -0
  169. package/dist/cdn/UZ7XFHYI.js +2 -0
  170. package/dist/cdn/V66TS2BB.js +2 -0
  171. package/dist/cdn/{AAUVOBPS.js → VINKTQFR.js} +1 -1
  172. package/dist/cdn/{U3ZTF2BC.js → VU7IOGNS.js} +2 -2
  173. package/dist/cdn/W2SIOY2B.js +3 -0
  174. package/dist/cdn/{WVMQ3I6F.js → W36IUEUB.js} +2 -2
  175. package/dist/cdn/{V6AQFRUC.js → WEBAQIUT.js} +2 -2
  176. package/dist/cdn/{WSIZ2OTL.js → WHIWOYHN.js} +1 -1
  177. package/dist/cdn/WOL5YMJ2.js +2 -0
  178. package/dist/cdn/{RBRHDEOB.js → X3YFCWQZ.js} +2 -2
  179. package/dist/cdn/{ICBIUFK7.js → X4EQEKM7.js} +2 -2
  180. package/dist/cdn/{UPSFL6U3.js → XBWGOD6I.js} +2 -2
  181. package/dist/cdn/XGDXTTYW.js +2 -0
  182. package/dist/cdn/{FFWPUYGD.js → XLHYQNAM.js} +2 -2
  183. package/dist/cdn/{NEV6OZN3.js → XMQJWPXI.js} +2 -2
  184. package/dist/cdn/{FXRZCD5Y.js → XQUKC4YK.js} +2 -2
  185. package/dist/cdn/{JEBRN3EU.js → XSH4B7FP.js} +2 -2
  186. package/dist/cdn/{LK7ZIQW6.js → XVWSIDZV.js} +2 -2
  187. package/dist/cdn/{J6A4AS7E.js → XYMIFFBW.js} +2 -2
  188. package/dist/cdn/{645SDZBB.js → Y3ZKMD47.js} +2 -2
  189. package/dist/cdn/{2GSHUAQ2.js → YAANCUW2.js} +2 -2
  190. package/dist/cdn/{XJUYG2M3.js → YD5LVM7V.js} +2 -2
  191. package/dist/cdn/{TTPTZBCM.js → YGI277SH.js} +2 -2
  192. package/dist/cdn/YGSDJ4V3.js +14 -0
  193. package/dist/cdn/YJEARDAZ.js +2 -0
  194. package/dist/cdn/{DXCDVRGL.js → YSEHJQ4L.js} +2 -2
  195. package/dist/cdn/Z44NI2YQ.js +2 -0
  196. package/dist/cdn/{74CVYM72.js → ZEDDYT24.js} +2 -2
  197. package/dist/cdn/{ZBBI5M2X.js → ZROI63CW.js} +2 -2
  198. package/dist/cdn/{ZKDCEL6K.js → ZUKM4DGB.js} +2 -2
  199. package/dist/cdn/ZVVNATCX.js +2 -0
  200. package/dist/cdn/agent-utils/BaseAgent.js +2 -2
  201. package/dist/cdn/agent-utils/FunctionAgent.js +2 -2
  202. package/dist/cdn/agent-utils/LLMAgent.js +2 -2
  203. package/dist/cdn/agent-utils/SkillAgent.js +2 -2
  204. package/dist/cdn/agent-utils/WorkflowAgent.js +2 -2
  205. package/dist/cdn/agent-utils/createSchema.js +2 -2
  206. package/dist/cdn/agent-utils/middlewares/humanInTheLoop.js +2 -2
  207. package/dist/cdn/agent-utils/middlewares/middleware.js +2 -2
  208. package/dist/cdn/agent-utils/middlewares/trace.js +2 -2
  209. package/dist/cdn/agent-utils/tools/FunctionTool.js +2 -2
  210. package/dist/cdn/agent-utils/tools/MCPToolProvider.js +15 -0
  211. package/dist/cdn/agent-utils/tools/WebMCPToolProvider.js +2 -0
  212. package/dist/cdn/agent-utils/workflows/ConditionalWorkflow.js +2 -2
  213. package/dist/cdn/agent-utils/workflows/LoopWorkflow.js +2 -2
  214. package/dist/cdn/agent-utils/workflows/ParallelWorkflow.js +2 -2
  215. package/dist/cdn/agent-utils/workflows/RouterWorkflow.js +2 -2
  216. package/dist/cdn/agent-utils/workflows/SequentialWorkflow.js +2 -2
  217. package/dist/cdn/agent-utils/workflows/SwitchWorkflow.js +2 -2
  218. package/dist/cdn/index.js +2 -2
  219. package/dist/cdn/orchestrator/embeddings/getEmbeddings.js +2 -2
  220. package/dist/cdn/orchestrator/models/chatModel.js +2 -2
  221. package/dist/cdn/orchestrator/models/prompts.js +2 -2
  222. package/dist/cdn/orchestrator/signals.js +2 -2
  223. package/dist/cdn/orchestrator/state/runtime.js +2 -2
  224. package/dist/chunks/BaseWorkflow.js +1 -1
  225. package/dist/chunks/SKILL.js +1 -1
  226. package/dist/chunks/SKILL2.js +1 -1
  227. package/dist/chunks/SKILL3.js +1 -1
  228. package/dist/chunks/SKILL4.js +1 -1
  229. package/dist/chunks/adapter.js +1 -1
  230. package/dist/chunks/adapter2.js +1 -1
  231. package/dist/chunks/aiFactory.js +1 -1
  232. package/dist/chunks/aiUtilityService.js +1 -1
  233. package/dist/chunks/arcgisToolRegistry.js +1 -1
  234. package/dist/chunks/arcgis_knowledge_current_lc_context.js +1 -1
  235. package/dist/chunks/arcgis_knowledge_current_map_context.js +1 -1
  236. package/dist/chunks/arcgis_knowledge_cypher_query_prompt.js +1 -1
  237. package/dist/chunks/arcgis_knowledge_lucene_generation_prompt.js +1 -1
  238. package/dist/chunks/arcgis_knowledge_summarize_result_prompt.js +1 -1
  239. package/dist/chunks/arcgis_knowledge_tool_prompt.js +1 -1
  240. package/dist/chunks/converterUtils.js +66 -110
  241. package/dist/chunks/createSkillAgent.js +1 -1
  242. package/dist/chunks/data_explore_filter_prompt.js +1 -1
  243. package/dist/chunks/data_explore_query_prompt.js +1 -1
  244. package/dist/chunks/embeddings.worker.js +1 -1
  245. package/dist/chunks/fetchAgentContext.js +1 -1
  246. package/dist/chunks/fetchService.js +1 -1
  247. package/dist/chunks/fetchUtils.js +1 -1
  248. package/dist/chunks/fieldStatistics.js +1 -1
  249. package/dist/chunks/field_descriptions_prompt.js +1 -1
  250. package/dist/chunks/formatFeatureAttributes.js +1 -1
  251. package/dist/chunks/getPrompt.js +1 -1
  252. package/dist/chunks/graph.js +1 -1
  253. package/dist/chunks/helpState.js +1 -1
  254. package/dist/chunks/help_prompt.js +1 -1
  255. package/dist/chunks/intent_prompt.js +1 -1
  256. package/dist/chunks/layerQueryToolCalling.js +1 -1
  257. package/dist/chunks/layerStylingState.js +1 -1
  258. package/dist/chunks/layer_descriptions_prompt.js +1 -1
  259. package/dist/chunks/layer_styling_prompt.js +1 -1
  260. package/dist/chunks/localization.js +1 -1
  261. package/dist/chunks/mergeWhereClauses.js +1 -1
  262. package/dist/chunks/modelConfig.js +1 -1
  263. package/dist/chunks/modelPricing.js +1 -1
  264. package/dist/chunks/navigationState.js +1 -1
  265. package/dist/chunks/navigation_intent_prompt.js +1 -1
  266. package/dist/chunks/navigation_tool_prompt.js +1 -1
  267. package/dist/chunks/observationSnapshot.js +1 -1
  268. package/dist/chunks/reducers.js +1 -1
  269. package/dist/chunks/requireAgentServices.js +1 -1
  270. package/dist/chunks/resolveFieldNames.js +9 -0
  271. package/dist/chunks/resolveGeometryFilter.js +1 -1
  272. package/dist/chunks/runtime.js +2 -2
  273. package/dist/chunks/runtime2.js +1 -1
  274. package/dist/chunks/runtimeSpans.js +1 -1
  275. package/dist/chunks/schema.js +1 -1
  276. package/dist/chunks/slottableRequestUtils.js +1 -1
  277. package/dist/chunks/state.js +1 -1
  278. package/dist/chunks/summarize_query_response_prompt.js +1 -1
  279. package/dist/chunks/textFormatters.js +1 -1
  280. package/dist/chunks/toolCallResponse.js +1 -1
  281. package/dist/chunks/useT9n.js +1 -1
  282. package/dist/chunks/utils.js +1 -1
  283. package/dist/chunks/utils2.js +1 -1
  284. package/dist/chunks/utils3.js +1 -1
  285. package/dist/chunks/webmapSchema.js +1 -1
  286. package/dist/components/arcgis-assistant/customElement.js +1 -1
  287. package/dist/components/arcgis-assistant-agent/customElement.js +1 -1
  288. package/dist/components/arcgis-assistant-chat/customElement.js +1 -1
  289. package/dist/components/arcgis-assistant-chat-entry/customElement.js +1 -1
  290. package/dist/components/arcgis-assistant-data-exploration-agent/customElement.js +1 -1
  291. package/dist/components/arcgis-assistant-help-agent/customElement.js +1 -1
  292. package/dist/components/arcgis-assistant-interrupt/customElement.js +1 -1
  293. package/dist/components/arcgis-assistant-interrupt-preview/customElement.js +1 -1
  294. package/dist/components/arcgis-assistant-knowledge-agent/customElement.js +1 -1
  295. package/dist/components/arcgis-assistant-layer-styling-agent/customElement.js +1 -1
  296. package/dist/components/arcgis-assistant-message/customElement.js +1 -1
  297. package/dist/components/arcgis-assistant-message-block/customElement.js +1 -1
  298. package/dist/components/arcgis-assistant-message-feedback/customElement.js +1 -1
  299. package/dist/components/arcgis-assistant-message-footer/customElement.js +1 -1
  300. package/dist/components/arcgis-assistant-message-loading/customElement.js +1 -1
  301. package/dist/components/arcgis-assistant-message-log/customElement.js +5 -6
  302. package/dist/components/arcgis-assistant-message-log/index.js +5 -0
  303. package/dist/components/arcgis-assistant-message-read-aloud/customElement.js +1 -1
  304. package/dist/components/arcgis-assistant-message-text/customElement.js +11 -12
  305. package/dist/components/arcgis-assistant-message-text/index.js +5 -0
  306. package/dist/components/arcgis-assistant-navigation-agent/customElement.js +1 -1
  307. package/dist/components/arcgis-assistant-observation-inspector/customElement.js +1 -1
  308. package/dist/components/arcgis-assistant-observation-latency/customElement.js +1 -1
  309. package/dist/components/arcgis-assistant-observation-panel/customElement.js +1 -1
  310. package/dist/components/arcgis-assistant-observation-run/customElement.js +1 -1
  311. package/dist/components/arcgis-assistant-observation-usage/customElement.js +1 -1
  312. package/dist/components/arcgis-assistant-speech-input/customElement.js +1 -1
  313. package/dist/components/arcgis-assistant-suggested-prompts/customElement.js +1 -1
  314. package/dist/components/arcgis-assistant-user-message/customElement.js +8 -9
  315. package/dist/components/arcgis-assistant-user-message/index.js +5 -0
  316. package/dist/docs/api.json +1 -1
  317. package/dist/docs/docs.json +1 -1
  318. package/dist/docs/web-types.json +1 -1
  319. package/dist/index.js +1 -1
  320. package/dist/loader.js +1 -1
  321. package/dist/orchestrator/embeddings/cosineSimilarity.js +1 -1
  322. package/dist/orchestrator/embeddings/getEmbeddings.js +1 -1
  323. package/dist/orchestrator/embeddings/webmapEmbeddings.js +1 -1
  324. package/dist/orchestrator/models/chatModel.js +1 -1
  325. package/dist/orchestrator/models/prompts.js +1 -1
  326. package/dist/orchestrator/orchestrator/orchestrator.js +1 -1
  327. package/dist/orchestrator/orchestrator/orchestratorEvents.js +1 -1
  328. package/dist/orchestrator/signals.js +1 -1
  329. package/dist/orchestrator/state/runtime.js +1 -1
  330. package/dist/orchestrator/state/types.js +1 -1
  331. package/dist/orchestrator/types.js +1 -1
  332. package/dist/utils/index.js +1 -1
  333. package/package.json +8 -5
  334. package/dist/cdn/25CQLMB4.js +0 -2
  335. package/dist/cdn/34HKOU3T.js +0 -2
  336. package/dist/cdn/3WS4DSWD.js +0 -2
  337. package/dist/cdn/434TAA3J.js +0 -2
  338. package/dist/cdn/43OJZMBB.js +0 -2
  339. package/dist/cdn/4BRIOLDJ.js +0 -2
  340. package/dist/cdn/4KFTUBFL.js +0 -2
  341. package/dist/cdn/4ZPGFIE2.js +0 -2
  342. package/dist/cdn/6JCDY4FL.js +0 -2
  343. package/dist/cdn/7GQCNR4P.js +0 -11
  344. package/dist/cdn/A3KIOUWB.js +0 -2
  345. package/dist/cdn/BKKLQUK2.js +0 -2
  346. package/dist/cdn/CADNOKIK.js +0 -2
  347. package/dist/cdn/DQRKGYR3.js +0 -2
  348. package/dist/cdn/EOSKJPQV.js +0 -2
  349. package/dist/cdn/F7VQ3WH2.js +0 -2
  350. package/dist/cdn/FBIPIDP7.js +0 -2
  351. package/dist/cdn/GOET2CH4.js +0 -2
  352. package/dist/cdn/ISDNOFHU.js +0 -3
  353. package/dist/cdn/JZS6ZSWH.js +0 -2
  354. package/dist/cdn/KEBMHD4R.js +0 -9
  355. package/dist/cdn/KPHHXMRK.js +0 -2
  356. package/dist/cdn/LVSIZRTB.js +0 -2
  357. package/dist/cdn/OJP56R5R.js +0 -2
  358. package/dist/cdn/OYHYHALE.js +0 -2
  359. package/dist/cdn/QQPVN5MG.js +0 -2
  360. package/dist/cdn/QUZTFUWM.js +0 -1
  361. package/dist/cdn/REE4K4J7.js +0 -2
  362. package/dist/cdn/RFKOCMMT.js +0 -2
  363. package/dist/cdn/RKHDRUX5.js +0 -2
  364. package/dist/cdn/TGI7QCB2.js +0 -2
  365. package/dist/cdn/UALF45Q2.js +0 -2
  366. package/dist/cdn/WB5AFS42.js +0 -2
  367. package/dist/cdn/WC6SHIEX.js +0 -2
  368. package/dist/cdn/XPSPAZUD.js +0 -2
  369. package/dist/cdn/YAUQJ6NV.js +0 -2
  370. package/dist/cdn/YD3DLETZ.js +0 -2
  371. package/dist/cdn/YKKIJTJY.js +0 -2
  372. package/dist/cdn/ZCNCYKXW.js +0 -14
  373. package/dist/cdn/ZESTW6HJ.js +0 -2
  374. package/dist/cdn/ZS5P7NRI.js +0 -2
@@ -0,0 +1,15 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
+ import{Fa as yi}from"../../A4ZVCRVF.js";import{A as l,B as x,C as q,D as Xt,E as at,F as b,G as F,H as p,I as $,J as Jo,K as qt,L as Ri,M as zi,a as fi,n as ra,o as Pt,q as Si,r,s as gi,t as er,u as _,v as P,w as Ct,x as _i,y as N,z as m}from"../../N2GN5WOI.js";import"../../272R36XK.js";import"../../5PV2GUZW.js";var Tl=Object.create,tr=Object.defineProperty,El=Object.getOwnPropertyDescriptor,Pl=Object.getOwnPropertyNames,Cl=Object.getPrototypeOf,ql=Object.prototype.hasOwnProperty,bi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),vi=(e,t)=>{let o={};for(var s in e)tr(o,s,{get:e[s],enumerable:!0});return t&&tr(o,Symbol.toStringTag,{value:"Module"}),o},Il=(e,t,o,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(var n=Pl(t),i=0,a=n.length,c;i<a;i++)c=n[i],!ql.call(e,c)&&c!==o&&tr(e,c,{get:(u=>t[u]).bind(null,c),enumerable:!(s=El(t,c))||s.enumerable});return e},wi=(e,t,o)=>(o=e!=null?Tl(Cl(e)):{},Il(t||!e||!e.__esModule?tr(o,"default",{value:e,enumerable:!0}):o,e));var kl=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),Ti=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),Ol=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),$l=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function Ei(e){return typeof e=="string"&&Ti.has(e.replace(/#$/,""))}function Pi(e,t){if(!("$schema"in e)||typeof e.$schema!="string")return"2020-12";let o=e.$schema.replace(/#$/,"");if(kl.has(o))return"2020-12";if(Ti.has(o))return"2019-09";if(Ol.has(o)||$l.has(o))return"draft-7";throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}var Zt="2025-11-25";var or=[Zt,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],sr="io.modelcontextprotocol/related-task",Ye="io.modelcontextprotocol/protocolVersion",Qt="io.modelcontextprotocol/clientInfo",Xe="io.modelcontextprotocol/serverInfo",kt="io.modelcontextprotocol/clientCapabilities",Bo="io.modelcontextprotocol/subscriptionId",eo="io.modelcontextprotocol/logLevel";var Ot="2.0";var it=Jo(()=>q([r(),_(),P(),Ct(),b(r(),it),m(it)])),ee=b(r(),it),aa=m(it),Go=q([r(),_().int()]),Wo=r(),rr=l({ttl:_().optional()}),nr=l({taskId:r()}),Ko=x({progressToken:Go.optional(),[sr]:nr.optional()}),ae=l({_meta:Ko.optional()}),$t=ae.extend({task:rr.optional()}),te=l({method:r(),params:ae.loose().optional()}),de=l({_meta:Ko.optional()}),he=l({method:r(),params:de.loose().optional()}),Yo=x({get[Xe](){return so.optional().catch(void 0)}}),oe=x({_meta:Yo.optional()}),ct=q([r(),_().int()]),Xo=l({jsonrpc:p(Ot),id:ct,...te.shape}).strict(),Zo=l({jsonrpc:p(Ot),...he.shape}).strict(),to=l({jsonrpc:p(Ot),id:ct,result:oe}).strict(),oo=l({jsonrpc:p(Ot),id:ct.optional(),error:l({code:_().int(),message:r(),data:N().optional()})}).strict(),lt=q([Xo,Zo,to,oo]),ia=q([to,oo]),Qo=oe.strict(),ar=de.extend({requestId:ct.optional(),reason:r().optional()}),es=he.extend({method:p("notifications/cancelled"),params:ar}),ir=l({src:r(),mimeType:r().optional(),sizes:m(r()).optional(),theme:F(["light","dark"]).optional()}),ut=l({icons:m(ir).optional()}),Ke=l({name:r(),title:r().optional()}),so=Ke.extend({...Ke.shape,...ut.shape,version:r(),websiteUrl:r().optional(),description:r().optional()}),Nl=at(l({applyDefaults:P().optional()}),ee),xl=qt(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,at(l({form:Nl.optional(),url:ee.optional()}),ee.optional())),cr=x({list:ee.optional(),cancel:ee.optional(),requests:x({sampling:x({createMessage:ee.optional()}).optional(),elicitation:x({create:ee.optional()}).optional()}).optional()}),lr=x({list:ee.optional(),cancel:ee.optional(),requests:x({tools:x({call:ee.optional()}).optional()}).optional()}),ur=l({experimental:b(r(),ee).optional(),sampling:l({context:ee.optional(),tools:ee.optional()}).optional(),elicitation:xl.optional(),roots:l({listChanged:P().optional()}).optional(),tasks:cr.optional(),extensions:b(r(),ee).optional()}),dr=ae.extend({protocolVersion:r(),capabilities:ur,clientInfo:so}),ts=te.extend({method:p("initialize"),params:dr}),os=l({experimental:b(r(),ee).optional(),logging:ee.optional(),completions:ee.optional(),prompts:l({listChanged:P().optional()}).optional(),resources:l({subscribe:P().optional(),listChanged:P().optional()}).optional(),tools:l({listChanged:P().optional()}).optional(),tasks:lr.optional(),extensions:b(r(),ee).optional()}),hr=oe.extend({protocolVersion:r(),capabilities:os,serverInfo:so,instructions:r().optional()}),ss=he.extend({method:p("notifications/initialized"),params:de.optional()}),mr=te.extend({method:p("server/discover"),params:ae.optional()}),Mt=oe.extend({supportedVersions:m(r()),capabilities:os,instructions:r().optional()}),rs=te.extend({method:p("ping"),params:ae.optional()}),pr=l({progress:_(),total:$(_()),message:$(r())}),fr=l({...de.shape,...pr.shape,progressToken:Go}),ns=he.extend({method:p("notifications/progress"),params:fr}),Sr=ae.extend({cursor:Wo.optional()}),dt=te.extend({params:Sr.optional()}),ht=oe.extend({nextCursor:Wo.optional()}),as=l({uri:r(),mimeType:$(r()),_meta:b(r(),N()).optional()}),is=as.extend({text:r()}),ca=r().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),cs=as.extend({blob:ca}),mt=F(["user","assistant"]),Ze=l({audience:m(mt).optional(),priority:_().min(0).max(1).optional(),lastModified:Pt.datetime({offset:!0}).optional()}),ls=l({...Ke.shape,...ut.shape,uri:r(),description:$(r()),mimeType:$(r()),size:$(_()),annotations:Ze.optional(),_meta:$(x({}))}),gr=l({...Ke.shape,...ut.shape,uriTemplate:r(),description:$(r()),mimeType:$(r()),annotations:Ze.optional(),_meta:$(x({}))}),_r=dt.extend({method:p("resources/list")}),Rr=ht.extend({resources:m(ls)}),zr=dt.extend({method:p("resources/templates/list")}),yr=ht.extend({resourceTemplates:m(gr)}),ro=ae.extend({uri:r()}),br=ro,vr=te.extend({method:p("resources/read"),params:br}),wr=oe.extend({contents:m(q([is,cs]))}),Tr=he.extend({method:p("notifications/resources/list_changed"),params:de.optional()}),Er=ro,Pr=te.extend({method:p("resources/subscribe"),params:Er}),Cr=ro,qr=te.extend({method:p("resources/unsubscribe"),params:Cr}),us=l({toolsListChanged:P().optional(),promptsListChanged:P().optional(),resourcesListChanged:P().optional(),resourceSubscriptions:m(r()).optional()}),Ir=ae.extend({notifications:us}),kr=te.extend({method:p("subscriptions/listen"),params:Ir}),Or=de.extend({notifications:us}),$r=he.extend({method:p("notifications/subscriptions/acknowledged"),params:Or}),Mr=Yo.extend({[Bo]:ct}),Nr=oe.extend({_meta:Mr}),xr=de.extend({uri:r()}),Ar=he.extend({method:p("notifications/resources/updated"),params:xr}),jr=l({name:r(),description:$(r()),required:$(P())}),Lr=l({...Ke.shape,...ut.shape,description:$(r()),arguments:$(m(jr)),_meta:$(x({}))}),Ur=dt.extend({method:p("prompts/list")}),Dr=ht.extend({prompts:m(Lr)}),Vr=ae.extend({name:r(),arguments:b(r(),r()).optional()}),Hr=te.extend({method:p("prompts/get"),params:Vr}),no=l({type:p("text"),text:r(),annotations:Ze.optional(),_meta:b(r(),N()).optional()}),ao=l({type:p("image"),data:ca,mimeType:r(),annotations:Ze.optional(),_meta:b(r(),N()).optional()}),io=l({type:p("audio"),data:ca,mimeType:r(),annotations:Ze.optional(),_meta:b(r(),N()).optional()}),Fr=l({type:p("tool_use"),name:r(),id:r(),input:b(r(),N()),_meta:b(r(),N()).optional()}),Jr=l({type:p("resource"),resource:q([is,cs]),annotations:Ze.optional(),_meta:b(r(),N()).optional()}),Br=ls.extend({type:p("resource_link")}),co=q([no,ao,io,Br,Jr]),Gr=l({role:mt,content:co}),Wr=oe.extend({description:r().optional(),messages:m(Gr)}),Kr=he.extend({method:p("notifications/prompts/list_changed"),params:de.optional()}),Yr=l({title:r().optional(),readOnlyHint:P().optional(),destructiveHint:P().optional(),idempotentHint:P().optional(),openWorldHint:P().optional()}),Xr=l({taskSupport:F(["required","optional","forbidden"]).optional()}),ds=l({...Ke.shape,...ut.shape,description:r().optional(),inputSchema:l({type:p("object"),properties:b(r(),it).optional(),required:m(r()).optional()}).catchall(N()),outputSchema:x({$schema:r().optional()}).optional(),annotations:Yr.optional(),execution:Xr.optional(),_meta:b(r(),N()).optional()}),Zr=dt.extend({method:p("tools/list")}),Qr=ht.extend({tools:m(ds)}),hs=oe.extend({content:m(co).default([]),structuredContent:N().optional(),isError:P().optional()}),la=hs.or(oe.extend({toolResult:N()})),en=$t.extend({name:r(),arguments:b(r(),N()).optional()}),tn=te.extend({method:p("tools/call"),params:en}),on=he.extend({method:p("notifications/tools/list_changed"),params:de.optional()}),ms=l({autoRefresh:P().default(!0),debounceMs:_().int().nonnegative().default(300)}),ps=F(["debug","info","notice","warning","error","critical","alert","emergency"]),sn=ae.extend({level:ps}),rn=te.extend({method:p("logging/setLevel"),params:sn}),nn=de.extend({level:ps,logger:r().optional(),data:N()}),an=he.extend({method:p("notifications/message"),params:nn}),cn=l({name:r().optional()}),ln=l({hints:m(cn).optional(),costPriority:_().min(0).max(1).optional(),speedPriority:_().min(0).max(1).optional(),intelligencePriority:_().min(0).max(1).optional()}),un=l({mode:F(["auto","required","none"]).optional()}),dn=l({type:p("tool_result"),toolUseId:r().describe("The unique identifier for the corresponding tool call."),content:m(co),structuredContent:N().optional(),isError:P().optional(),_meta:b(r(),N()).optional()}),hn=Xt("type",[no,ao,io]),It=Xt("type",[no,ao,io,Fr,dn]),mn=l({role:mt,content:q([It,m(It)]),_meta:b(r(),N()).optional()}),pn=$t.extend({messages:m(mn),modelPreferences:ln.optional(),systemPrompt:r().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:_().optional(),maxTokens:_().int(),stopSequences:m(r()).optional(),metadata:ee.optional(),tools:m(ds).optional(),toolChoice:un.optional()}),fn=te.extend({method:p("sampling/createMessage"),params:pn}),Sn=oe.extend({model:r(),stopReason:$(F(["endTurn","stopSequence","maxTokens"]).or(r())),role:mt,content:hn}),gn=oe.extend({model:r(),stopReason:$(F(["endTurn","stopSequence","maxTokens","toolUse"]).or(r())),role:mt,content:q([It,m(It)])}),fs=l({type:p("boolean"),title:r().optional(),description:r().optional(),default:P().optional()}),lo=l({type:p("string"),title:r().optional(),description:r().optional(),minLength:_().optional(),maxLength:_().optional(),format:F(["email","uri","date","date-time"]).optional(),default:r().optional()}),uo=l({type:F(["number","integer"]),title:r().optional(),description:r().optional(),minimum:_().optional(),maximum:_().optional(),default:_().optional()}),Ss=l({type:p("string"),title:r().optional(),description:r().optional(),enum:m(r()),default:r().optional()}),gs=l({type:p("string"),title:r().optional(),description:r().optional(),oneOf:m(l({const:r(),title:r()})),default:r().optional()}),_s=l({type:p("string"),title:r().optional(),description:r().optional(),enum:m(r()),enumNames:m(r()).optional(),default:r().optional()}),_n=q([Ss,gs]),Rs=l({type:p("array"),title:r().optional(),description:r().optional(),minItems:_().optional(),maxItems:_().optional(),items:l({type:p("string"),enum:m(r())}),default:m(r()).optional()}),zs=l({type:p("array"),title:r().optional(),description:r().optional(),minItems:_().optional(),maxItems:_().optional(),items:l({anyOf:m(l({const:r(),title:r()}))}),default:m(r()).optional()}),Rn=q([Rs,zs]),zn=q([_s,_n,Rn]),ys=q([zn,fs,lo,uo]),ho=$t.extend({mode:p("form").optional(),message:r(),requestedSchema:l({type:p("object"),properties:b(r(),ys),required:m(r()).optional()}).catchall(N())}),yn=$t.extend({mode:p("url"),message:r(),elicitationId:r(),url:r().url()}),bn=q([ho,yn]),vn=te.extend({method:p("elicitation/create"),params:bn}),wn=de.extend({elicitationId:r()}),Tn=he.extend({method:p("notifications/elicitation/complete"),params:wn}),En=oe.extend({action:F(["accept","decline","cancel"]),content:qt(e=>e===null?void 0:e,b(r(),q([r(),_(),P(),m(r())])).optional())}),Pn=l({type:p("ref/resource"),uri:r()}),Cn=l({type:p("ref/prompt"),name:r()}),qn=ae.extend({ref:q([Cn,Pn]),argument:l({name:r(),value:r()}),context:l({arguments:b(r(),r()).optional()}).optional()}),In=te.extend({method:p("completion/complete"),params:qn}),kn=oe.extend({completion:x({values:m(r()).max(100),total:$(_().int()),hasMore:$(P())})}),On=l({uri:r().startsWith("file://"),name:r().optional(),_meta:b(r(),N()).optional()}),$n=te.extend({method:p("roots/list"),params:ae.optional()}),Mn=oe.extend({roots:m(On)}),Nn=he.extend({method:p("notifications/roots/list_changed"),params:de.optional()}),ua=x({ttl:_().optional(),pollInterval:_().optional()}),xn=F(["working","input_required","completed","failed","cancelled"]),pt=l({taskId:r(),status:xn,ttl:q([_(),Ct()]),createdAt:r(),lastUpdatedAt:r(),pollInterval:$(_()),statusMessage:$(r())}),da=oe.extend({task:pt}),An=de.merge(pt),ha=he.extend({method:p("notifications/tasks/status"),params:An}),ma=te.extend({method:p("tasks/get"),params:ae.extend({taskId:r()})}),pa=oe.merge(pt),fa=te.extend({method:p("tasks/result"),params:ae.extend({taskId:r()})}),Sa=oe.loose(),ga=dt.extend({method:p("tasks/list")}),_a=ht.extend({tasks:m(pt)}),Ra=te.extend({method:p("tasks/cancel"),params:ae.extend({taskId:r()})}),za=oe.merge(pt),ya=q([rs,ts,mr,In,rn,Hr,Ur,_r,zr,vr,Pr,qr,kr,tn,Zr]),ba=q([es,ns,ss,Nn]),va=q([Qo,Sn,gn,En,Mn]),wa=q([rs,fn,vn,$n]),Ta=q([es,ns,an,Ar,Tr,on,Kr,$r,Tn]),Ea=q([Qo,hr,Mt,kn,Wr,Dr,Rr,yr,wr,hs,Qr,Nr]),ne=er().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Ri.custom,message:"URL must be parseable",fatal:!0}),fi}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),bs=x({resource:r().url(),authorization_servers:m(ne).optional(),jwks_uri:r().url().optional(),scopes_supported:m(r()).optional(),bearer_methods_supported:m(r()).optional(),resource_signing_alg_values_supported:m(r()).optional(),resource_name:r().optional(),resource_documentation:r().optional(),resource_policy_uri:r().url().optional(),resource_tos_uri:r().url().optional(),tls_client_certificate_bound_access_tokens:P().optional(),authorization_details_types_supported:m(r()).optional(),dpop_signing_alg_values_supported:m(r()).optional(),dpop_bound_access_tokens_required:P().optional()}),mo=x({issuer:r(),authorization_endpoint:ne,token_endpoint:ne,registration_endpoint:ne.optional(),scopes_supported:m(r()).optional(),response_types_supported:m(r()),response_modes_supported:m(r()).optional(),grant_types_supported:m(r()).optional(),token_endpoint_auth_methods_supported:m(r()).optional(),token_endpoint_auth_signing_alg_values_supported:m(r()).optional(),service_documentation:ne.optional(),revocation_endpoint:ne.optional(),revocation_endpoint_auth_methods_supported:m(r()).optional(),revocation_endpoint_auth_signing_alg_values_supported:m(r()).optional(),introspection_endpoint:r().optional(),introspection_endpoint_auth_methods_supported:m(r()).optional(),introspection_endpoint_auth_signing_alg_values_supported:m(r()).optional(),code_challenge_methods_supported:m(r()).optional(),client_id_metadata_document_supported:P().optional(),authorization_response_iss_parameter_supported:P().optional().catch(void 0),dpop_signing_alg_values_supported:m(r()).optional()}),jn=x({issuer:r(),authorization_endpoint:ne,token_endpoint:ne,userinfo_endpoint:ne.optional(),jwks_uri:ne,registration_endpoint:ne.optional(),scopes_supported:m(r()).optional(),response_types_supported:m(r()),response_modes_supported:m(r()).optional(),grant_types_supported:m(r()).optional(),acr_values_supported:m(r()).optional(),subject_types_supported:m(r()),id_token_signing_alg_values_supported:m(r()),id_token_encryption_alg_values_supported:m(r()).optional(),id_token_encryption_enc_values_supported:m(r()).optional(),userinfo_signing_alg_values_supported:m(r()).optional(),userinfo_encryption_alg_values_supported:m(r()).optional(),userinfo_encryption_enc_values_supported:m(r()).optional(),request_object_signing_alg_values_supported:m(r()).optional(),request_object_encryption_alg_values_supported:m(r()).optional(),request_object_encryption_enc_values_supported:m(r()).optional(),token_endpoint_auth_methods_supported:m(r()).optional(),token_endpoint_auth_signing_alg_values_supported:m(r()).optional(),display_values_supported:m(r()).optional(),claim_types_supported:m(r()).optional(),claims_supported:m(r()).optional(),service_documentation:r().optional(),claims_locales_supported:m(r()).optional(),ui_locales_supported:m(r()).optional(),claims_parameter_supported:P().optional(),request_parameter_supported:P().optional(),request_uri_parameter_supported:P().optional(),require_request_uri_registration:P().optional(),op_policy_uri:ne.optional(),op_tos_uri:ne.optional(),client_id_metadata_document_supported:P().optional(),authorization_response_iss_parameter_supported:P().optional().catch(void 0)}),vs=l({...jn.shape,...mo.pick({code_challenge_methods_supported:!0}).shape}),ws=l({access_token:r(),id_token:r().optional(),token_type:r(),expires_in:zi.number().optional(),scope:r().optional(),refresh_token:r().optional(),issuer:r().optional().catch(void 0)}).strip(),Ln=l({issued_token_type:p("urn:ietf:params:oauth:token-type:id-jag"),access_token:r(),token_type:r().optional(),expires_in:_().optional(),scope:r().optional()}).strip(),Ts=l({error:r(),error_description:r().optional(),error_uri:r().optional()}),na=ne.optional().or(p("").transform(()=>{})),Un=l({redirect_uris:m(ne),token_endpoint_auth_method:r().optional(),grant_types:m(r()).optional(),response_types:m(r()).optional(),application_type:r().optional(),client_name:r().optional(),client_uri:ne.optional(),logo_uri:na,scope:r().optional(),contacts:m(r()).optional(),tos_uri:na,policy_uri:r().optional(),jwks_uri:ne.optional(),jwks:_i().optional(),software_id:r().optional(),software_version:r().optional(),software_statement:r().optional()}).strip(),Dn=l({client_id:r(),client_secret:r().optional(),client_id_issued_at:_().optional(),client_secret_expires_at:_().optional(),issuer:r().optional().catch(void 0)}).strip(),Es=Un.merge(Dn),Pa=l({error:r(),error_description:r().optional()}).strip(),Ca=l({token:r(),token_type_hint:r().optional()}).strip();var $a=Symbol.for("mcp.sdk.errorBrands");function Nt(e,t){let o=new Set,s=t;for(;typeof s=="function";){let n=s.mcpBrand;Object.prototype.hasOwnProperty.call(s,"mcpBrand")&&typeof n=="string"&&o.add(n),s=Object.getPrototypeOf(s)}o.size!==0&&Object.defineProperty(e,$a,{value:o,enumerable:!1,configurable:!0})}function Pe(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,$a)){let o=t[$a];if(o&&typeof o.has=="function"&&o.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var et=(function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e.InvalidDpopProof="invalid_dpop_proof",e.UseDpopNonce="use_dpop_nonce",e})({}),xt=class Yi extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Pe(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Pe(this,t)}constructor(t,o,s){super(o),this.code=t,this.errorUri=s,this.name="OAuthError",Nt(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new Yi(t.error,t.error_description??t.error,t.error_uri)}},I=(function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e})({}),k=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Pe(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Pe(this,e)}constructor(e,t,o,s){super(t,s),this.code=e,this.data=o,this.name="SdkError",Nt(this,new.target)}},Fe=class extends k{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,o,s){super(e,t,o,s),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function Xi(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function ja(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}function Zi({requestedResource:e,configuredResource:t}){let o=typeof e=="string"?new URL(e):new URL(e.href),s=typeof t=="string"?new URL(t):new URL(t.href);if(o.origin!==s.origin||o.pathname.length<s.pathname.length)return!1;let n=o.pathname.endsWith("/")?o.pathname:o.pathname+"/",i=s.pathname.endsWith("/")?s.pathname:s.pathname+"/";return n.startsWith(i)}var Qi="2026-07-28",La=[Qi];function tt(e){return e>=Qi}function Ua(e){return e.filter(t=>!tt(t))}function Os(e){return e.filter(t=>tt(t))}function ec(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(o=>o.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}var tc=["task","inputRequests","requestState"];function Al(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||tc.some(t=>t in e)?e:{...e,content:[]}}function jl(){let e=Jo(()=>q([r(),_(),P(),Ct(),b(r(),e),m(e)])),t=b(r(),e),o=q([r(),_().int()]),s=r(),n=l({ttl:_().optional()}),i=l({taskId:r()}),a=x({progressToken:o.optional(),"io.modelcontextprotocol/related-task":i.optional()}),c=l({_meta:a.optional()}),u=c.extend({task:n.optional()}),h=l({method:r(),params:c.loose().optional()}),d=l({_meta:a.optional()}),f=l({method:r(),params:d.loose().optional()}),S=x({_meta:a.optional()}),R=q([r(),_().int()]),v=S.strict(),z=d.extend({requestId:R.optional(),reason:r().optional()}),y=f.extend({method:p("notifications/cancelled"),params:z}),V=l({src:r(),mimeType:r().optional(),sizes:m(r()).optional(),theme:F(["light","dark"]).optional()}),H=l({icons:m(V).optional()}),M=l({name:r(),title:r().optional()}),W=M.extend({...M.shape,...H.shape,version:r(),websiteUrl:r().optional(),description:r().optional()}),T=at(l({applyDefaults:P().optional()}),t),g=qt(ue=>ue&&typeof ue=="object"&&!Array.isArray(ue)&&Object.keys(ue).length===0?{form:{}}:ue,at(l({form:T.optional(),url:t.optional()}),t.optional())),j=x({list:t.optional(),cancel:t.optional(),requests:x({sampling:x({createMessage:t.optional()}).optional(),elicitation:x({create:t.optional()}).optional()}).optional()}),G=x({list:t.optional(),cancel:t.optional(),requests:x({tools:x({call:t.optional()}).optional()}).optional()}),B=l({experimental:b(r(),t).optional(),sampling:l({context:t.optional(),tools:t.optional()}).optional(),elicitation:g.optional(),roots:l({listChanged:P().optional()}).optional(),tasks:j.optional(),extensions:b(r(),t).optional()}),Z=c.extend({protocolVersion:r(),capabilities:B,clientInfo:W}),me=h.extend({method:p("initialize"),params:Z}),Y=l({experimental:b(r(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:l({listChanged:P().optional()}).optional(),resources:l({subscribe:P().optional(),listChanged:P().optional()}).optional(),tools:l({listChanged:P().optional()}).optional(),tasks:G.optional(),extensions:b(r(),t).optional()}),X=S.extend({protocolVersion:r(),capabilities:Y,serverInfo:W,instructions:r().optional()}),ie=f.extend({method:p("notifications/initialized"),params:d.optional()}),pe=h.extend({method:p("ping"),params:c.optional()}),xe=l({progress:_(),total:$(_()),message:$(r())}),Re=l({...d.shape,...xe.shape,progressToken:o}),Ce=f.extend({method:p("notifications/progress"),params:Re}),Ae=c.extend({cursor:s.optional()}),be=h.extend({params:Ae.optional()}),fe=S.extend({nextCursor:s.optional()}),Ge=l({uri:r(),mimeType:$(r()),_meta:b(r(),N()).optional()}),We=Ge.extend({text:r()}),je=r().refine(ue=>{try{return atob(ue),!0}catch{return!1}},{message:"Invalid Base64 string"}),ce=Ge.extend({blob:je}),Se=F(["user","assistant"]),ge=l({audience:m(Se).optional(),priority:_().min(0).max(1).optional(),lastModified:Pt.datetime({offset:!0}).optional()}),$e=l({...M.shape,...H.shape,uri:r(),description:$(r()),mimeType:$(r()),size:$(_()),annotations:ge.optional(),_meta:$(x({}))}),St=l({...M.shape,...H.shape,uriTemplate:r(),description:$(r()),mimeType:$(r()),annotations:ge.optional(),_meta:$(x({}))}),ve=be.extend({method:p("resources/list")}),we=fe.extend({resources:m($e)}),ze=be.extend({method:p("resources/templates/list")}),qe=fe.extend({resourceTemplates:m(St)}),Ie=c.extend({uri:r()}),Le=Ie,Ue=h.extend({method:p("resources/read"),params:Le}),ot=S.extend({contents:m(q([We,ce]))}),De=f.extend({method:p("notifications/resources/list_changed"),params:d.optional()}),gt=Ie,E=h.extend({method:p("resources/subscribe"),params:gt}),Ve=Ie,A=h.extend({method:p("resources/unsubscribe"),params:Ve}),O=d.extend({uri:r()}),J=f.extend({method:p("notifications/resources/updated"),params:O}),C=l({name:r(),description:$(r()),required:$(P())}),w=l({...M.shape,...H.shape,description:$(r()),arguments:$(m(C)),_meta:$(x({}))}),U=be.extend({method:p("prompts/list")}),L=fe.extend({prompts:m(w)}),re=c.extend({name:r(),arguments:b(r(),r()).optional()}),_t=h.extend({method:p("prompts/get"),params:re}),He=l({type:p("text"),text:r(),annotations:ge.optional(),_meta:b(r(),N()).optional()}),Rt=l({type:p("image"),data:je,mimeType:r(),annotations:ge.optional(),_meta:b(r(),N()).optional()}),zt=l({type:p("audio"),data:je,mimeType:r(),annotations:ge.optional(),_meta:b(r(),N()).optional()}),go=l({type:p("tool_use"),name:r(),id:r(),input:b(r(),N()),_meta:b(r(),N()).optional()}),st=l({type:p("resource"),resource:q([We,ce]),annotations:ge.optional(),_meta:b(r(),N()).optional()}),_o=$e.extend({type:p("resource_link")}),ke=q([He,Rt,zt,_o,st]),Ut=l({role:Se,content:ke}),Dt=S.extend({description:r().optional(),messages:m(Ut)}),yt=f.extend({method:p("notifications/prompts/list_changed"),params:d.optional()}),Ro=l({title:r().optional(),readOnlyHint:P().optional(),destructiveHint:P().optional(),idempotentHint:P().optional(),openWorldHint:P().optional()}),Vt=l({taskSupport:F(["required","optional","forbidden"]).optional()}),bt=l({...M.shape,...H.shape,description:r().optional(),inputSchema:l({type:p("object"),properties:b(r(),e).optional(),required:m(r()).optional()}).catchall(N()),outputSchema:l({type:p("object"),properties:b(r(),e).optional(),required:m(r()).optional()}).catchall(N()).optional(),annotations:Ro.optional(),execution:Vt.optional(),_meta:b(r(),N()).optional()}),Ht=be.extend({method:p("tools/list")}),Ft=fe.extend({tools:m(bt)}),Jt=S.extend({content:m(ke),structuredContent:b(r(),N()).optional(),isError:P().optional()}),le=u.extend({name:r(),arguments:b(r(),N()).optional()}),zo=h.extend({method:p("tools/call"),params:le}),js=f.extend({method:p("notifications/tools/list_changed"),params:d.optional()}),Bt=F(["debug","info","notice","warning","error","critical","alert","emergency"]),yo=c.extend({level:Bt}),bo=h.extend({method:p("logging/setLevel"),params:yo}),vo=d.extend({level:Bt,logger:r().optional(),data:N()}),wo=f.extend({method:p("notifications/message"),params:vo}),To=l({name:r().optional()}),Eo=l({hints:m(To).optional(),costPriority:_().min(0).max(1).optional(),speedPriority:_().min(0).max(1).optional(),intelligencePriority:_().min(0).max(1).optional()}),Po=l({mode:F(["auto","required","none"]).optional()}),Ls=l({type:p("tool_result"),toolUseId:r().describe("The unique identifier for the corresponding tool call."),content:m(ke),structuredContent:l({}).loose().optional(),isError:P().optional(),_meta:b(r(),N()).optional()}),Co=Xt("type",[He,Rt,zt]),rt=Xt("type",[He,Rt,zt,go,Ls]),qo=l({role:Se,content:q([rt,m(rt)]),_meta:b(r(),N()).optional()}),Io=u.extend({messages:m(qo),modelPreferences:Eo.optional(),systemPrompt:r().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:_().optional(),maxTokens:_().int(),stopSequences:m(r()).optional(),metadata:t.optional(),tools:m(bt).optional(),toolChoice:Po.optional()}),ko=h.extend({method:p("sampling/createMessage"),params:Io}),Oo=S.extend({model:r(),stopReason:$(F(["endTurn","stopSequence","maxTokens"]).or(r())),role:Se,content:Co}),$o=S.extend({model:r(),stopReason:$(F(["endTurn","stopSequence","maxTokens","toolUse"]).or(r())),role:Se,content:q([rt,m(rt)])}),Mo=l({type:p("boolean"),title:r().optional(),description:r().optional(),default:P().optional()}),No=l({type:p("string"),title:r().optional(),description:r().optional(),minLength:_().optional(),maxLength:_().optional(),format:F(["email","uri","date","date-time"]).optional(),default:r().optional()}),xo=l({type:F(["number","integer"]),title:r().optional(),description:r().optional(),minimum:_().optional(),maximum:_().optional(),default:_().optional()}),Ao=l({type:p("string"),title:r().optional(),description:r().optional(),enum:m(r()),default:r().optional()}),jo=l({type:p("string"),title:r().optional(),description:r().optional(),oneOf:m(l({const:r(),title:r()})),default:r().optional()}),Lo=l({type:p("string"),title:r().optional(),description:r().optional(),enum:m(r()),enumNames:m(r()).optional(),default:r().optional()}),Uo=q([Ao,jo]),vt=l({type:p("array"),title:r().optional(),description:r().optional(),minItems:_().optional(),maxItems:_().optional(),items:l({type:p("string"),enum:m(r())}),default:m(r()).optional()}),wt=l({type:p("array"),title:r().optional(),description:r().optional(),minItems:_().optional(),maxItems:_().optional(),items:l({anyOf:m(l({const:r(),title:r()}))}),default:m(r()).optional()}),Us=q([vt,wt]),Ds=q([Lo,Uo,Us]),Te=q([Ds,Mo,No,xo]),Ee=u.extend({mode:p("form").optional(),message:r(),requestedSchema:l({type:p("object"),properties:b(r(),Te),required:m(r()).optional()}).catchall(N())}),Do=u.extend({mode:p("url"),message:r(),elicitationId:r(),url:r().url()}),Me=q([Ee,Do]),Vs=h.extend({method:p("elicitation/create"),params:Me}),Hs=d.extend({elicitationId:r()}),Fs=f.extend({method:p("notifications/elicitation/complete"),params:Hs}),Js=S.extend({action:F(["accept","decline","cancel"]),content:qt(ue=>ue===null?void 0:ue,b(r(),q([r(),_(),P(),m(r())])).optional())}),Bs=l({type:p("ref/resource"),uri:r()}),Gs=l({type:p("ref/prompt"),name:r()}),Ws=c.extend({ref:q([Gs,Bs]),argument:l({name:r(),value:r()}),context:l({arguments:b(r(),r()).optional()}).optional()}),Vo=h.extend({method:p("completion/complete"),params:Ws}),Ks=S.extend({completion:x({values:m(r()).max(100),total:$(_().int()),hasMore:$(P())})}),Ys=l({uri:r().startsWith("file://"),name:r().optional(),_meta:b(r(),N()).optional()}),Gt=h.extend({method:p("roots/list"),params:c.optional()}),Ho=S.extend({roots:m(Ys)}),Xs=f.extend({method:p("notifications/roots/list_changed"),params:d.optional()}),Zs=x({ttl:_().optional(),pollInterval:_().optional()}),Fo=F(["working","input_required","completed","failed","cancelled"]),nt=l({taskId:r(),status:Fo,ttl:q([_(),Ct()]),createdAt:r(),lastUpdatedAt:r(),pollInterval:$(_()),statusMessage:$(r())}),ye=S.extend({task:nt}),Qs=d.merge(nt),Tt=f.extend({method:p("notifications/tasks/status"),params:Qs}),Wt=h.extend({method:p("tasks/get"),params:c.extend({taskId:r()})}),Kt=S.merge(nt),Yt=h.extend({method:p("tasks/result"),params:c.extend({taskId:r()})}),sa=S.loose(),_e=be.extend({method:p("tasks/list")}),se=fe.extend({tasks:m(nt)}),Et=h.extend({method:p("tasks/cancel"),params:c.extend({taskId:r()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:o,CursorSchema:s,TaskMetadataSchema:n,RelatedTaskMetadataSchema:i,RequestMetaSchema:a,BaseRequestParamsSchema:c,TaskAugmentedRequestParamsSchema:u,RequestSchema:h,NotificationsParamsSchema:d,NotificationSchema:f,ResultSchema:S,RequestIdSchema:R,EmptyResultSchema:v,CancelledNotificationParamsSchema:z,CancelledNotificationSchema:y,IconSchema:V,IconsSchema:H,BaseMetadataSchema:M,ImplementationSchema:W,ClientTasksCapabilitySchema:j,ServerTasksCapabilitySchema:G,ClientCapabilitiesSchema:B,InitializeRequestParamsSchema:Z,InitializeRequestSchema:me,ServerCapabilitiesSchema:Y,InitializeResultSchema:X,InitializedNotificationSchema:ie,PingRequestSchema:pe,ProgressSchema:xe,ProgressNotificationParamsSchema:Re,ProgressNotificationSchema:Ce,PaginatedRequestParamsSchema:Ae,PaginatedRequestSchema:be,PaginatedResultSchema:fe,ResourceContentsSchema:Ge,TextResourceContentsSchema:We,BlobResourceContentsSchema:ce,RoleSchema:Se,AnnotationsSchema:ge,ResourceSchema:$e,ResourceTemplateSchema:St,ListResourcesRequestSchema:ve,ListResourcesResultSchema:we,ListResourceTemplatesRequestSchema:ze,ListResourceTemplatesResultSchema:qe,ResourceRequestParamsSchema:Ie,ReadResourceRequestParamsSchema:Le,ReadResourceRequestSchema:Ue,ReadResourceResultSchema:ot,ResourceListChangedNotificationSchema:De,SubscribeRequestParamsSchema:gt,SubscribeRequestSchema:E,UnsubscribeRequestParamsSchema:Ve,UnsubscribeRequestSchema:A,ResourceUpdatedNotificationParamsSchema:O,ResourceUpdatedNotificationSchema:J,PromptArgumentSchema:C,PromptSchema:w,ListPromptsRequestSchema:U,ListPromptsResultSchema:L,GetPromptRequestParamsSchema:re,GetPromptRequestSchema:_t,TextContentSchema:He,ImageContentSchema:Rt,AudioContentSchema:zt,ToolUseContentSchema:go,EmbeddedResourceSchema:st,ResourceLinkSchema:_o,ContentBlockSchema:ke,PromptMessageSchema:Ut,GetPromptResultSchema:Dt,PromptListChangedNotificationSchema:yt,ToolAnnotationsSchema:Ro,ToolExecutionSchema:Vt,ToolSchema:bt,ListToolsRequestSchema:Ht,ListToolsResultSchema:Ft,CallToolResultSchema:Jt,CallToolRequestParamsSchema:le,CallToolRequestSchema:zo,ToolListChangedNotificationSchema:js,LoggingLevelSchema:Bt,SetLevelRequestParamsSchema:yo,SetLevelRequestSchema:bo,LoggingMessageNotificationParamsSchema:vo,LoggingMessageNotificationSchema:wo,ModelHintSchema:To,ModelPreferencesSchema:Eo,ToolChoiceSchema:Po,ToolResultContentSchema:Ls,SamplingContentSchema:Co,SamplingMessageContentBlockSchema:rt,SamplingMessageSchema:qo,CreateMessageRequestParamsSchema:Io,CreateMessageRequestSchema:ko,CreateMessageResultSchema:Oo,CreateMessageResultWithToolsSchema:$o,BooleanSchemaSchema:Mo,StringSchemaSchema:No,NumberSchemaSchema:xo,UntitledSingleSelectEnumSchemaSchema:Ao,TitledSingleSelectEnumSchemaSchema:jo,LegacyTitledEnumSchemaSchema:Lo,SingleSelectEnumSchemaSchema:Uo,UntitledMultiSelectEnumSchemaSchema:vt,TitledMultiSelectEnumSchemaSchema:wt,MultiSelectEnumSchemaSchema:Us,EnumSchemaSchema:Ds,PrimitiveSchemaDefinitionSchema:Te,ElicitRequestFormParamsSchema:Ee,ElicitRequestURLParamsSchema:Do,ElicitRequestParamsSchema:Me,ElicitRequestSchema:Vs,ElicitationCompleteNotificationParamsSchema:Hs,ElicitationCompleteNotificationSchema:Fs,ElicitResultSchema:Js,ResourceTemplateReferenceSchema:Bs,PromptReferenceSchema:Gs,CompleteRequestParamsSchema:Ws,CompleteRequestSchema:Vo,CompleteResultSchema:Ks,RootSchema:Ys,ListRootsRequestSchema:Gt,ListRootsResultSchema:Ho,RootsListChangedNotificationSchema:Xs,TaskCreationParamsSchema:Zs,TaskStatusSchema:Fo,TaskSchema:nt,CreateTaskResultSchema:ye,TaskStatusNotificationParamsSchema:Qs,TaskStatusNotificationSchema:Tt,GetTaskRequestSchema:Wt,GetTaskResultSchema:Kt,GetTaskPayloadRequestSchema:Yt,GetTaskPayloadResultSchema:sa,ListTasksRequestSchema:_e,ListTasksResultSchema:se,CancelTaskRequestSchema:Et,CancelTaskResultSchema:S.merge(nt),ClientRequestSchema:q([pe,me,Vo,bo,_t,U,ve,ze,Ue,E,A,zo,Ht,Wt,Yt,_e,Et]),ClientNotificationSchema:q([y,Ce,ie,Xs,Tt]),ClientResultSchema:q([v,Oo,$o,Js,Ho,Kt,se,ye]),ServerRequestSchema:q([pe,ko,Vs,Gt,Wt,Yt,_e,Et]),ServerNotificationSchema:q([y,Ce,wo,J,De,js,yt,Tt,Fs]),ServerResultSchema:q([v,X,Ks,Dt,L,we,qe,ot,Jt,Ft,Kt,se,ye]),CallToolResultWireSchema:N().superRefine((ue,wl)=>{if(!(typeof ue!="object"||ue===null||Array.isArray(ue)||ue.content!==void 0)){for(let pi of tc)if(pi in ue){wl.addIssue({code:"custom",message:`content is required when the body carries '${pi}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(Al).pipe(Jt)}}var Ll;function oc(){return Ll??=jl()}function sc(e){return e.type!=="object"}var Ul=new Set(["const","enum","default","examples"]),Dl=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function Ai(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}function Vl(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(Ai(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let o=Ei(e.$schema)&&e.$recursiveAnchor!==!0,s=(n,i)=>{if(Array.isArray(n))return n.map(u=>s(u,!1));if(n===null||typeof n!="object"||!i&&Ai(n.$id))return n;let a={},c=!1;for(let[u,h]of Object.entries(n))i?a[u]=s(h,!1):(u==="$ref"||u==="$dynamicRef")&&typeof h=="string"?a[u]=h==="#"?"#/properties/result":h.startsWith("#/")?`#/properties/result${h.slice(1)}`:h:u==="$recursiveRef"&&h==="#"&&o?c=!0:Ul.has(u)?a[u]=h:Dl.has(u)?a[u]=s(h,!0):a[u]=s(h,!1);return c&&("$ref"in a?a.allOf=[...Array.isArray(a.allOf)?a.allOf:[],{$ref:"#/properties/result"}]:a.$ref="#/properties/result"),a};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:s(e,!1)},required:["result"]}}var rc={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},nc={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},Hl={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Vn;function Da(){if(Vn)return Vn;let e=oc();return Vn={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},Vn}function ac(e){return Object.prototype.hasOwnProperty.call(rc,e)}function ic(e){return Object.prototype.hasOwnProperty.call(nc,e)}function Fl(e){return Object.prototype.hasOwnProperty.call(Hl,e)}function Jl(e){return Fl(e)?Da().resultSchemas[e]:void 0}function Bl(e){return ac(e)?Da().requestSchemas[e]:void 0}function Gl(e){return ic(e)?Da().notificationSchemas[e]:void 0}var fm=Object.keys(rc),Sm=Object.keys(nc);function Ma(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Hn(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let o=e.safeParse(t);return o.success?{ok:!0,value:o.data}:{ok:!1,reason:"invalid",message:String(o.error)}}var ji={ok:!1,reason:"not-in-era"};function Li(e){return Ma(e)&&Ma(e.outputSchema)&&sc(e.outputSchema)}var Va={era:"2025-11-25",hasRequestMethod:ac,hasNotificationMethod:ic,validateRequest:(e,t)=>Hn(Bl(e),t),validateResult:(e,t)=>Hn(Jl(e),t),validateNotification:(e,t)=>Hn(Gl(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>ji,validateInputResponse:()=>ji,samplingResultVariant:((e,t)=>{let o=oc();return Hn(e?o.CreateMessageResultWithToolsSchema:o.CreateMessageResultSchema,t)}),outboundEnvelope:e=>{},validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){let o=ec(e),s=o.structuredContent;if(s===void 0)return o;let n=typeof s!="object"||s===null||Array.isArray(s),i=t!==void 0&&sc(t);return!n&&!i?o:{...o,structuredContent:{result:s}}},decodeResult(e,t){if(Ma(t)&&"resultType"in t){let o={...t};return delete o.resultType,{kind:"complete",result:o}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let o=t.tools;return!Array.isArray(o)||!o.some(s=>Li(s))?t:{...t,tools:o.map(s=>Li(s)?{...s,outputSchema:Vl(s.outputSchema)}:s)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>{}};function Wl(){let e=Jo(()=>q([r(),_(),P(),Ct(),b(r(),e),m(e)])),t=b(r(),e),o=q([r(),_().int()]),s=r(),n=q([r(),_().int()]),i=F(["user","assistant"]),a=F(["debug","info","notice","warning","error","critical","alert","emergency"]),c=r().refine(se=>{try{return atob(se),!0}catch{return!1}},{message:"Invalid Base64 string"}),u=l({ttl:_().optional()}),h=l({taskId:r()}),d=x({progressToken:o.optional(),"io.modelcontextprotocol/related-task":h.optional()}),f=l({_meta:d.optional()}),S=f.extend({task:u.optional()}),R=l({_meta:d.optional()}),v=l({method:r(),params:R.loose().optional()}),z=l({src:r(),mimeType:r().optional(),sizes:m(r()).optional(),theme:F(["light","dark"]).optional()}),y=l({icons:m(z).optional()}),V=l({name:r(),title:r().optional()}),H=V.extend({...V.shape,...y.shape,version:r(),websiteUrl:r().optional(),description:r().optional()}),M=at(l({applyDefaults:P().optional()}),t),W=qt(se=>se&&typeof se=="object"&&!Array.isArray(se)&&Object.keys(se).length===0?{form:{}}:se,at(l({form:M.optional(),url:t.optional()}),t.optional())),T=x({list:t.optional(),cancel:t.optional(),requests:x({sampling:x({createMessage:t.optional()}).optional(),elicitation:x({create:t.optional()}).optional()}).optional()}),g=x({list:t.optional(),cancel:t.optional(),requests:x({tools:x({call:t.optional()}).optional()}).optional()}),j=l({experimental:b(r(),t).optional(),sampling:l({context:t.optional(),tools:t.optional()}).optional(),elicitation:W.optional(),roots:l({listChanged:P().optional()}).optional(),tasks:T.optional(),extensions:b(r(),t).optional()}),G=l({experimental:b(r(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:l({listChanged:P().optional()}).optional(),resources:l({subscribe:P().optional(),listChanged:P().optional()}).optional(),tools:l({listChanged:P().optional()}).optional(),tasks:g.optional(),extensions:b(r(),t).optional()}),B=l({progress:_(),total:$(_()),message:$(r())}),Z=l({...R.shape,...B.shape,progressToken:o}),me=v.extend({method:p("notifications/progress"),params:Z}),Y=R.extend({level:a,logger:r().optional(),data:N()}),X=v.extend({method:p("notifications/message"),params:Y}),ie=l({uri:r(),mimeType:$(r()),_meta:b(r(),N()).optional()}),pe=ie.extend({text:r()}),xe=ie.extend({blob:c}),Re=l({audience:m(i).optional(),priority:_().min(0).max(1).optional(),lastModified:Pt.datetime({offset:!0}).optional()}),Ce=l({...V.shape,...y.shape,uri:r(),description:$(r()),mimeType:$(r()),size:$(_()),annotations:Re.optional(),_meta:$(x({}))}),Ae=l({...V.shape,...y.shape,uriTemplate:r(),description:$(r()),mimeType:$(r()),annotations:Re.optional(),_meta:$(x({}))}),be=v.extend({method:p("notifications/resources/list_changed"),params:R.optional()}),fe=R.extend({uri:r()}),Ge=v.extend({method:p("notifications/resources/updated"),params:fe}),We=l({name:r(),description:$(r()),required:$(P())}),je=l({...V.shape,...y.shape,description:$(r()),arguments:$(m(We)),_meta:$(x({}))}),ce=v.extend({method:p("notifications/prompts/list_changed"),params:R.optional()}),Se=l({type:p("text"),text:r(),annotations:Re.optional(),_meta:b(r(),N()).optional()}),ge=l({type:p("image"),data:c,mimeType:r(),annotations:Re.optional(),_meta:b(r(),N()).optional()}),$e=l({type:p("audio"),data:c,mimeType:r(),annotations:Re.optional(),_meta:b(r(),N()).optional()}),St=l({type:p("tool_use"),name:r(),id:r(),input:b(r(),N()),_meta:b(r(),N()).optional()}),ve=l({type:p("resource"),resource:q([pe,xe]),annotations:Re.optional(),_meta:b(r(),N()).optional()}),we=Ce.extend({type:p("resource_link")}),ze=q([Se,ge,$e,we,ve]),qe=l({role:i,content:ze}),Ie=l({title:r().optional(),readOnlyHint:P().optional(),destructiveHint:P().optional(),idempotentHint:P().optional(),openWorldHint:P().optional()}),Le=v.extend({method:p("notifications/tools/list_changed"),params:R.optional()}),Ue=l({name:r().optional()}),ot=l({hints:m(Ue).optional(),costPriority:_().min(0).max(1).optional(),speedPriority:_().min(0).max(1).optional(),intelligencePriority:_().min(0).max(1).optional()}),De=l({mode:F(["auto","required","none"]).optional()}),gt=l({type:p("boolean"),title:r().optional(),description:r().optional(),default:P().optional()}),E=l({type:p("string"),title:r().optional(),description:r().optional(),minLength:_().optional(),maxLength:_().optional(),format:F(["email","uri","date","date-time"]).optional(),default:r().optional()}),Ve=l({type:F(["number","integer"]),title:r().optional(),description:r().optional(),minimum:_().optional(),maximum:_().optional(),default:_().optional()}),A=l({type:p("string"),title:r().optional(),description:r().optional(),enum:m(r()),default:r().optional()}),O=l({type:p("string"),title:r().optional(),description:r().optional(),oneOf:m(l({const:r(),title:r()})),default:r().optional()}),J=l({type:p("string"),title:r().optional(),description:r().optional(),enum:m(r()),enumNames:m(r()).optional(),default:r().optional()}),C=q([A,O]),w=l({type:p("array"),title:r().optional(),description:r().optional(),minItems:_().optional(),maxItems:_().optional(),items:l({type:p("string"),enum:m(r())}),default:m(r()).optional()}),U=l({type:p("array"),title:r().optional(),description:r().optional(),minItems:_().optional(),maxItems:_().optional(),items:l({anyOf:m(l({const:r(),title:r()}))}),default:m(r()).optional()}),L=q([w,U]),re=q([J,C,L]),_t=q([re,gt,E,Ve]),He=S.extend({mode:p("form").optional(),message:r(),requestedSchema:l({type:p("object"),properties:b(r(),_t),required:m(r()).optional()}).catchall(N())}),Rt=l({type:p("ref/resource"),uri:r()}),zt=l({type:p("ref/prompt"),name:r()}),go=l({uri:r().startsWith("file://"),name:r().optional(),_meta:b(r(),N()).optional()}),st=j.shape,_o=l({experimental:st.experimental,sampling:st.sampling,elicitation:st.elicitation,roots:st.roots,extensions:st.extensions}),ke=G.shape,Ut=l({experimental:ke.experimental,logging:ke.logging,completions:ke.completions,prompts:ke.prompts,resources:ke.resources,tools:ke.tools,extensions:ke.extensions}),Dt=x({progressToken:o.optional(),[Ye]:r(),[Qt]:H.optional(),[kt]:_o,[eo]:a.optional()}),yt=l({...V.shape,...y.shape,description:r().optional(),inputSchema:x({$schema:r().optional(),type:p("object")}),outputSchema:x({$schema:r().optional()}).optional(),annotations:Ie.optional(),_meta:b(r(),N()).optional()}),Ro=l({type:p("tool_result"),toolUseId:r(),content:m(ze),structuredContent:N().optional(),isError:P().optional(),_meta:b(r(),N()).optional()}),Vt=q([Se,ge,$e,St,Ro]),bt=l({role:i,content:q([Vt,m(Vt)]),_meta:b(r(),N()).optional()}),Ht=r(),Ft=x({[Xe]:H.optional().catch(void 0)}),Jt=Ft.optional();function le(se){return x({_meta:Jt,resultType:Ht.default("complete"),...se})}let zo=le({}),js=le({nextCursor:s.optional()}),Bt=le({content:m(ze),structuredContent:N().optional(),isError:P().optional()}),yo=le({ttlMs:_().int().min(0),cacheScope:F(["public","private"]),tools:m(yt),nextCursor:s.optional()}),bo=le({ttlMs:_().int().min(0),cacheScope:F(["public","private"]),prompts:m(je),nextCursor:s.optional()}),vo=le({description:r().optional(),messages:m(qe)}),wo=le({ttlMs:_().int().min(0),cacheScope:F(["public","private"]),resources:m(Ce),nextCursor:s.optional()}),To=le({ttlMs:_().int().min(0),cacheScope:F(["public","private"]),resourceTemplates:m(Ae),nextCursor:s.optional()}),Eo=le({ttlMs:_().int().min(0),cacheScope:F(["public","private"]),contents:m(q([pe,xe]))}),Po=le({completion:l({values:m(r()).max(100),total:_().int().optional(),hasMore:P().optional()}).loose()}),Ls=le({ttlMs:_().int().min(0),cacheScope:F(["public","private"])}),Co=le({ttlMs:_().int().min(0).catch(0),cacheScope:F(["public","private"]).catch("private"),supportedVersions:m(r()),capabilities:Ut,instructions:r().optional()}),rt=l({messages:m(bt),modelPreferences:ot.optional(),systemPrompt:r().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:_().optional(),maxTokens:_().int(),stopSequences:m(r()).optional(),metadata:t.optional(),tools:m(yt).optional(),toolChoice:De.optional()}),qo=l({method:p("sampling/createMessage"),params:rt}),Io=l({method:p("roots/list"),params:l({_meta:b(r(),N()).optional()}).optional()}),ko=l({...bt.shape,model:r(),stopReason:r().optional()}),Oo=l({roots:m(go)}),$o=l({action:F(["accept","decline","cancel"]),content:b(r(),q([r(),_(),P(),m(r())])).optional()}),Mo=l({mode:p("url"),message:r(),url:r().url()}),No=q([He,Mo]),xo=l({method:p("elicitation/create"),params:No}),Ao=q([qo,Io,xo]),jo=q([ko,Oo,$o]),Lo=b(r(),Ao),Uo=b(r(),jo),vt=le({inputRequests:Lo.optional(),requestState:r().optional()}),wt={inputResponses:Uo.optional(),requestState:r().optional()},Us=l({_meta:Dt,...wt}),Ds=x({progressToken:o.optional()});function Te(se,Et){return l({method:p(se),params:l({_meta:Dt,...Et})})}function Ee(se,Et){return l({method:p(se),params:l({_meta:Ds.optional(),...Et}).optional()})}let Do={name:r(),arguments:b(r(),N()).optional(),...wt},Me={cursor:s.optional()},Vs=Te("tools/call",Do),Hs=Te("tools/list",Me),Fs=Te("prompts/list",Me),Js=Te("prompts/get",{name:r(),arguments:b(r(),r()).optional(),...wt}),Bs=Te("resources/list",Me),Gs=Te("resources/templates/list",Me),Ws=Te("resources/read",{uri:r(),...wt}),Vo={ref:q([zt,Rt]),argument:l({name:r(),value:r()}),context:l({arguments:b(r(),r()).optional()}).optional()},Ks=Te("completion/complete",Vo),Ys=Te("server/discover",{}),Gt=l({toolsListChanged:P().optional(),promptsListChanged:P().optional(),resourcesListChanged:P().optional(),resourceSubscriptions:m(r()).optional()}),Ho={notifications:Gt},Xs=Te("subscriptions/listen",Ho),Zs=Ft.extend({"io.modelcontextprotocol/subscriptionId":n}),Fo=x({_meta:Zs,resultType:Ht.default("complete")}),nt={"tools/call":Ee("tools/call",Do),"tools/list":Ee("tools/list",Me),"prompts/get":Ee("prompts/get",{name:r(),arguments:b(r(),r()).optional()}),"prompts/list":Ee("prompts/list",Me),"resources/list":Ee("resources/list",Me),"resources/templates/list":Ee("resources/templates/list",Me),"resources/read":Ee("resources/read",{uri:r()}),"completion/complete":Ee("completion/complete",Vo),"server/discover":Ee("server/discover",{}),"subscriptions/listen":Ee("subscriptions/listen",Ho)};function ye(se){return x({_meta:Jt,...se})}let Qs={"tools/call":ye({content:m(ze),structuredContent:N().optional(),isError:P().optional()}),"tools/list":ye({ttlMs:_().int().min(0),cacheScope:F(["public","private"]),tools:m(yt),nextCursor:s.optional()}),"prompts/get":ye({description:r().optional(),messages:m(qe)}),"prompts/list":ye({ttlMs:_().int().min(0),cacheScope:F(["public","private"]),prompts:m(je),nextCursor:s.optional()}),"resources/list":ye({ttlMs:_().int().min(0),cacheScope:F(["public","private"]),resources:m(Ce),nextCursor:s.optional()}),"resources/templates/list":ye({ttlMs:_().int().min(0),cacheScope:F(["public","private"]),resourceTemplates:m(Ae),nextCursor:s.optional()}),"resources/read":ye({ttlMs:_().int().min(0),cacheScope:F(["public","private"]),contents:m(q([pe,xe]))}),"completion/complete":ye({completion:l({values:m(r()).max(100),total:_().int().optional(),hasMore:P().optional()}).loose()}),"server/discover":ye({ttlMs:_().int().min(0).catch(0),cacheScope:F(["public","private"]).catch("private"),supportedVersions:m(r()),capabilities:Ut,instructions:r().optional()}),"subscriptions/listen":ye({})},Tt=x({"io.modelcontextprotocol/subscriptionId":n.optional()}),Wt=l({method:p("notifications/subscriptions/acknowledged"),params:l({_meta:Tt.optional(),notifications:Gt})}),Kt=l({_meta:Tt.optional(),requestId:n,reason:r().optional()}),Yt=l({method:p("notifications/cancelled"),params:Kt}),sa={"notifications/cancelled":Yt,"notifications/progress":me,"notifications/message":X,"notifications/resources/updated":Ge,"notifications/resources/list_changed":be,"notifications/tools/list_changed":Le,"notifications/prompts/list_changed":ce,"notifications/subscriptions/acknowledged":Wt},_e=se=>l({jsonrpc:p("2.0"),id:q([r(),_().int()]),result:se}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:o,CursorSchema:s,RequestIdSchema:n,RoleSchema:i,LoggingLevelSchema:a,TaskMetadataSchema:u,RelatedTaskMetadataSchema:h,RequestMetaSchema:d,BaseRequestParamsSchema:f,TaskAugmentedRequestParamsSchema:S,NotificationsParamsSchema:R,NotificationSchema:v,IconSchema:z,IconsSchema:y,BaseMetadataSchema:V,ImplementationSchema:H,ClientTasksCapabilitySchema:T,ServerTasksCapabilitySchema:g,ClientCapabilitiesSchema:j,ServerCapabilitiesSchema:G,ProgressSchema:B,ProgressNotificationParamsSchema:Z,ProgressNotificationSchema:me,LoggingMessageNotificationParamsSchema:Y,LoggingMessageNotificationSchema:X,ResourceContentsSchema:ie,TextResourceContentsSchema:pe,BlobResourceContentsSchema:xe,AnnotationsSchema:Re,ResourceSchema:Ce,ResourceTemplateSchema:Ae,ResourceListChangedNotificationSchema:be,ResourceUpdatedNotificationParamsSchema:fe,ResourceUpdatedNotificationSchema:Ge,PromptArgumentSchema:We,PromptSchema:je,PromptListChangedNotificationSchema:ce,TextContentSchema:Se,ImageContentSchema:ge,AudioContentSchema:$e,ToolUseContentSchema:St,EmbeddedResourceSchema:ve,ResourceLinkSchema:we,ContentBlockSchema:ze,PromptMessageSchema:qe,ToolAnnotationsSchema:Ie,ToolListChangedNotificationSchema:Le,ModelHintSchema:Ue,ModelPreferencesSchema:ot,ToolChoiceSchema:De,BooleanSchemaSchema:gt,StringSchemaSchema:E,NumberSchemaSchema:Ve,UntitledSingleSelectEnumSchemaSchema:A,TitledSingleSelectEnumSchemaSchema:O,LegacyTitledEnumSchemaSchema:J,SingleSelectEnumSchemaSchema:C,UntitledMultiSelectEnumSchemaSchema:w,TitledMultiSelectEnumSchemaSchema:U,MultiSelectEnumSchemaSchema:L,EnumSchemaSchema:re,PrimitiveSchemaDefinitionSchema:_t,ElicitRequestFormParamsSchema:He,ResourceTemplateReferenceSchema:Rt,PromptReferenceSchema:zt,RootSchema:go,ClientCapabilities2026Schema:_o,ServerCapabilities2026Schema:Ut,RequestMetaEnvelopeSchema:Dt,ToolSchema:yt,ToolResultContentSchema:Ro,SamplingMessageContentBlockSchema:Vt,SamplingMessageSchema:bt,ResultTypeSchema:Ht,ResultMetaSchema:Ft,ResultSchema:zo,PaginatedResultSchema:js,CallToolResultSchema:Bt,ListToolsResultSchema:yo,ListPromptsResultSchema:bo,GetPromptResultSchema:vo,ListResourcesResultSchema:wo,ListResourceTemplatesResultSchema:To,ReadResourceResultSchema:Eo,CompleteResultSchema:Po,CacheableResultSchema:Ls,DiscoverResultSchema:Co,CreateMessageRequestParamsSchema:rt,CreateMessageRequestSchema:qo,ListRootsRequestSchema:Io,CreateMessageResultSchema:ko,ListRootsResultSchema:Oo,ElicitResultSchema:$o,ElicitRequestURLParamsSchema:Mo,ElicitRequestParamsSchema:No,ElicitRequestSchema:xo,InputRequestSchema:Ao,InputResponseSchema:jo,InputRequestsSchema:Lo,InputResponsesSchema:Uo,InputRequiredResultSchema:vt,InputResponseRequestParamsSchema:Us,CallToolRequestSchema:Vs,ListToolsRequestSchema:Hs,ListPromptsRequestSchema:Fs,GetPromptRequestSchema:Js,ListResourcesRequestSchema:Bs,ListResourceTemplatesRequestSchema:Gs,ReadResourceRequestSchema:Ws,CompleteRequestSchema:Ks,DiscoverRequestSchema:Ys,SubscriptionFilterSchema:Gt,SubscriptionsListenRequestSchema:Xs,SubscriptionsListenResultMetaSchema:Zs,SubscriptionsListenResultSchema:Fo,dispatchRequestSchemas:nt,dispatchResultSchemas:Qs,NotificationMetaSchema:Tt,SubscriptionsAcknowledgedNotificationSchema:Wt,CancelledNotificationParamsSchema:Kt,CancelledNotificationSchema:Yt,notificationSchemas2026:sa,JSONRPCResultResponseSchema:_e(zo),CallToolResultResponseSchema:_e(q([Bt,vt])),ListToolsResultResponseSchema:_e(yo),ListPromptsResultResponseSchema:_e(bo),GetPromptResultResponseSchema:_e(q([vo,vt])),ListResourcesResultResponseSchema:_e(wo),ListResourceTemplatesResultResponseSchema:_e(To),ReadResourceResultResponseSchema:_e(q([Eo,vt])),CompleteResultResponseSchema:_e(Po),DiscoverResultResponseSchema:_e(Co),SubscriptionsListenResultResponseSchema:_e(Fo)}}var Kl;function ft(){return Kl??=Wl()}var Yl=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function Xl(e){return Yl.includes(e)}var Ha=Symbol("modelcontextprotocol.resultCacheHintFallback");function Zl(e){return e[Ha]}function cc(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function lc(e){return e==="public"||e==="private"}var D=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),K=class uc extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Pe(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Pe(this,t)}constructor(t,o,s){super(o),this.code=t,this.data=s,this.name="ProtocolError",Nt(this,new.target)}static fromError(t,o,s){if(t===D.UrlElicitationRequired&&s){let n=s;if(n.elicitations)return new hc(n.elicitations,o)}if(t===D.UnsupportedProtocolVersion&&s){let n=s;if(Array.isArray(n.supported)&&typeof n.requested=="string")return new Wn({supported:n.supported,requested:n.requested},o)}if(t===D.InvalidParams||t===D.ResourceNotFound){let n=s;if(typeof n?.uri=="string"&&(t===D.ResourceNotFound||Object.keys(n).length===1))return new dc(n.uri,o)}if(t===D.MissingRequiredClientCapability&&s){let n=s;if(n.requiredCapabilities!==null&&typeof n.requiredCapabilities=="object"&&!Array.isArray(n.requiredCapabilities))return new mc({requiredCapabilities:n.requiredCapabilities},o)}return new uc(t,o,s)}},dc=class extends K{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(D.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},hc=class extends K{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(D.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Wn=class extends K{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(D.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},mc=class extends K{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(D.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},Ql=0,eu="private",tu=["tools/call","prompts/get","resources/read"];function ou(e,t){let o=t.resultType;if(o===void 0)return{...t,resultType:"complete"};if(o==="complete"||tu.includes(e))return t;throw new K(D.InternalError,`Handler for ${e} returned resultType '${String(o)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function su(e,t){let o=Zl(t);if(t.resultType!=="complete"||!Xl(e))return o===void 0?t:cu(t);let s=t,n=cc(s.ttlMs)?s.ttlMs:au(o),i=lc(s.cacheScope)?s.cacheScope:iu(o),a={...s,ttlMs:n,cacheScope:i};return delete a[Ha],a}function ru(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function nu(e,t){if(t===void 0)return e;let o=e._meta;return o===void 0?{...e,_meta:{[Xe]:t}}:!ru(o)||o[Xe]!==void 0?e:{...e,_meta:{...o,[Xe]:t}}}function au(e){return e!==void 0&&cc(e.ttlMs)?e.ttlMs:Ql}function iu(e){return e!==void 0&&lc(e.cacheScope)?e.cacheScope:eu}function cu(e){let t={...e};return delete t[Ha],t}var lu=["elicitation/create","sampling/createMessage","roots/list"],Fn;function pc(){if(Fn)return Fn;let e=ft();return Fn={request:{"elicitation/create":l({method:p("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":l({method:p("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":l({method:p("roots/list"),params:x({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Fn}function fc(e){return lu.includes(e)}function qa(e){return fc(e)?pc().request[e]:void 0}function uu(e){return fc(e)?pc().response[e]:void 0}var Fa={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},Sc={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function gc(e){return Object.prototype.hasOwnProperty.call(Fa,e)}function _c(e){return Object.prototype.hasOwnProperty.call(Sc,e)}function du(e){return Object.prototype.hasOwnProperty.call(Fa,e)}function hu(e){return gc(e)?ft().dispatchRequestSchemas[e]:void 0}function mu(e){return du(e)?ft().dispatchResultSchemas[e]:void 0}function pu(e){return _c(e)?ft().notificationSchemas2026[e]:void 0}var gm=Object.keys(Fa),_m=Object.keys(Sc);function qs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ps(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let o=e.safeParse(t);return o.success?{ok:!0,value:o.data}:{ok:!1,reason:"invalid",message:String(o.error)}}var fu={ok:!1,reason:"not-in-era"},Su=[Ye,kt];function gu(e,t){let o=t,s=!1,n=()=>(s||(o={...o},s=!0),o),i=t.tools;e==="tools/list"&&Array.isArray(i)&&i.some(c=>qs(c)&&"execution"in c)&&(n().tools=i.map(c=>{if(!qs(c)||!("execution"in c))return c;let u={...c};return delete u.execution,u}));let a=t.capabilities;if(qs(a)&&"tasks"in a){let c={...a};delete c.tasks,n().capabilities=c}return o}var Ja={era:"2026-07-28",hasRequestMethod:gc,hasNotificationMethod:_c,hasInputRequestMethod:e=>qa(e)!==void 0,validateRequest:(e,t)=>Ps(hu(e),t),validateResult:(e,t)=>Ps(mu(e),t),validateNotification:(e,t)=>Ps(pu(e),t),validateInputRequest:(e,t)=>Ps(qa(e),t),validateInputResponse:(e,t)=>Ps(uu(e),t),samplingResultVariant:()=>fu,outboundEnvelope(e){return{[Ye]:e.protocolVersion,[Qt]:e.clientInfo,[kt]:e.clientCapabilities,...e.logLevel!==void 0&&{[eo]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let s of Su)s in e||t.push({key:s,problem:"missing"});let o=ft().RequestMetaEnvelopeSchema.safeParse(e);if(!o.success)for(let s of o.error.issues){let n=s.path.map(String),i=n.length>0?n.join("."):"_meta";n.length===1&&t.some(a=>a.key===i&&a.problem==="missing")||t.push({key:i,problem:s.message})}return t},projectCallToolResult:e=>ec(e),inputRequestSchema:qa,decodeResult(e,t){if(!qs(t))return{kind:"invalid",error:new k(I.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let o=t.resultType;if(o===void 0)return{kind:"invalid",error:new k(I.InvalidResult,`Invalid result for ${e}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof o!="string")return{kind:"invalid",error:new k(I.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:o})};if(o==="input_required"){let a=t.inputRequests,c=qs(a)?a:{},u=t.requestState,h=t._meta===void 0?void 0:ft().ResultMetaSchema.safeParse(t._meta),d=h?.success?h.data:void 0;return Object.keys(c).length===0&&typeof u!="string"?{kind:"invalid",error:new k(I.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:c,...typeof u=="string"&&{requestState:u},...d!==void 0&&{_meta:d}}}if(o!=="complete")return{kind:"invalid",error:new k(I.UnsupportedResultType,`Unsupported result type '${o}' for ${e}`,{resultType:o,method:e})};let s=_u(),n=Object.hasOwn(s,e)?s[e]:void 0;if(n!==void 0){let a=n.safeParse(t);if(!a.success)return{kind:"invalid",error:new k(I.InvalidResult,`Invalid result for ${e}: ${a.error}`,{method:e})}}let i={...t};return delete i.resultType,{kind:"complete",result:i}},encodeResult(e,t,o){return nu(su(e,ou(e,gu(e,t))),o)},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=ft().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(o=>o.message).join("; ")}`}},Jn;function _u(){if(Jn)return Jn;let e=ft();return Jn={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},Jn}var Kn="2026-07-28";function Qe(e){return e!==void 0&&tt(e)?Ja:Va}function Ui(e){return e.revision!==void 0?Qe(e.revision).era:e.era==="modern"?Ja.era:Va.era}function Ia(e){return Rc.some(t=>t.hasRequestMethod(e))}function ka(e){return Rc.some(t=>t.hasNotificationMethod(e))}function Di(e){return e==="tasks/get"||e==="tasks/cancel"}var Rc=[Va,Ja],Ru=vi({AnnotationsSchema:()=>Ze,AudioContentSchema:()=>io,BaseMetadataSchema:()=>Ke,BaseRequestParamsSchema:()=>ae,BlobResourceContentsSchema:()=>cs,BooleanSchemaSchema:()=>fs,CallToolRequestParamsSchema:()=>en,CallToolRequestSchema:()=>tn,CallToolResultSchema:()=>hs,CancelTaskRequestSchema:()=>Ra,CancelTaskResultSchema:()=>za,CancelledNotificationParamsSchema:()=>ar,CancelledNotificationSchema:()=>es,ClientCapabilitiesSchema:()=>ur,ClientNotificationSchema:()=>ba,ClientRequestSchema:()=>ya,ClientResultSchema:()=>va,ClientTasksCapabilitySchema:()=>cr,CompatibilityCallToolResultSchema:()=>la,CompleteRequestParamsSchema:()=>qn,CompleteRequestSchema:()=>In,CompleteResultSchema:()=>kn,ContentBlockSchema:()=>co,CreateMessageRequestParamsSchema:()=>pn,CreateMessageRequestSchema:()=>fn,CreateMessageResultSchema:()=>Sn,CreateMessageResultWithToolsSchema:()=>gn,CreateTaskResultSchema:()=>da,CursorSchema:()=>Wo,DiscoverRequestSchema:()=>mr,DiscoverResultSchema:()=>Mt,ElicitRequestFormParamsSchema:()=>ho,ElicitRequestParamsSchema:()=>bn,ElicitRequestSchema:()=>vn,ElicitRequestURLParamsSchema:()=>yn,ElicitResultSchema:()=>En,ElicitationCompleteNotificationParamsSchema:()=>wn,ElicitationCompleteNotificationSchema:()=>Tn,EmbeddedResourceSchema:()=>Jr,EmptyResultSchema:()=>Qo,EnumSchemaSchema:()=>zn,GetPromptRequestParamsSchema:()=>Vr,GetPromptRequestSchema:()=>Hr,GetPromptResultSchema:()=>Wr,GetTaskPayloadRequestSchema:()=>fa,GetTaskPayloadResultSchema:()=>Sa,GetTaskRequestSchema:()=>ma,GetTaskResultSchema:()=>pa,IconSchema:()=>ir,IconsSchema:()=>ut,ImageContentSchema:()=>ao,ImplementationSchema:()=>so,InitializeRequestParamsSchema:()=>dr,InitializeRequestSchema:()=>ts,InitializeResultSchema:()=>hr,InitializedNotificationSchema:()=>ss,JSONArraySchema:()=>aa,JSONObjectSchema:()=>ee,JSONRPCErrorResponseSchema:()=>oo,JSONRPCMessageSchema:()=>lt,JSONRPCNotificationSchema:()=>Zo,JSONRPCRequestSchema:()=>Xo,JSONRPCResponseSchema:()=>ia,JSONRPCResultResponseSchema:()=>to,JSONValueSchema:()=>it,LegacyTitledEnumSchemaSchema:()=>_s,ListChangedOptionsBaseSchema:()=>ms,ListPromptsRequestSchema:()=>Ur,ListPromptsResultSchema:()=>Dr,ListResourceTemplatesRequestSchema:()=>zr,ListResourceTemplatesResultSchema:()=>yr,ListResourcesRequestSchema:()=>_r,ListResourcesResultSchema:()=>Rr,ListRootsRequestSchema:()=>$n,ListRootsResultSchema:()=>Mn,ListTasksRequestSchema:()=>ga,ListTasksResultSchema:()=>_a,ListToolsRequestSchema:()=>Zr,ListToolsResultSchema:()=>Qr,LoggingLevelSchema:()=>ps,LoggingMessageNotificationParamsSchema:()=>nn,LoggingMessageNotificationSchema:()=>an,ModelHintSchema:()=>cn,ModelPreferencesSchema:()=>ln,MultiSelectEnumSchemaSchema:()=>Rn,NotificationSchema:()=>he,NotificationsParamsSchema:()=>de,NumberSchemaSchema:()=>uo,PaginatedRequestParamsSchema:()=>Sr,PaginatedRequestSchema:()=>dt,PaginatedResultSchema:()=>ht,PingRequestSchema:()=>rs,PrimitiveSchemaDefinitionSchema:()=>ys,ProgressNotificationParamsSchema:()=>fr,ProgressNotificationSchema:()=>ns,ProgressSchema:()=>pr,ProgressTokenSchema:()=>Go,PromptArgumentSchema:()=>jr,PromptListChangedNotificationSchema:()=>Kr,PromptMessageSchema:()=>Gr,PromptReferenceSchema:()=>Cn,PromptSchema:()=>Lr,ReadResourceRequestParamsSchema:()=>br,ReadResourceRequestSchema:()=>vr,ReadResourceResultSchema:()=>wr,RelatedTaskMetadataSchema:()=>nr,RequestIdSchema:()=>ct,RequestMetaSchema:()=>Ko,RequestSchema:()=>te,ResourceContentsSchema:()=>as,ResourceLinkSchema:()=>Br,ResourceListChangedNotificationSchema:()=>Tr,ResourceRequestParamsSchema:()=>ro,ResourceSchema:()=>ls,ResourceTemplateReferenceSchema:()=>Pn,ResourceTemplateSchema:()=>gr,ResourceUpdatedNotificationParamsSchema:()=>xr,ResourceUpdatedNotificationSchema:()=>Ar,ResultMetaObjectSchema:()=>Yo,ResultSchema:()=>oe,RoleSchema:()=>mt,RootSchema:()=>On,RootsListChangedNotificationSchema:()=>Nn,SamplingContentSchema:()=>hn,SamplingMessageContentBlockSchema:()=>It,SamplingMessageSchema:()=>mn,ServerCapabilitiesSchema:()=>os,ServerNotificationSchema:()=>Ta,ServerRequestSchema:()=>wa,ServerResultSchema:()=>Ea,ServerTasksCapabilitySchema:()=>lr,SetLevelRequestParamsSchema:()=>sn,SetLevelRequestSchema:()=>rn,SingleSelectEnumSchemaSchema:()=>_n,StringSchemaSchema:()=>lo,SubscribeRequestParamsSchema:()=>Er,SubscribeRequestSchema:()=>Pr,SubscriptionFilterSchema:()=>us,SubscriptionsAcknowledgedNotificationParamsSchema:()=>Or,SubscriptionsAcknowledgedNotificationSchema:()=>$r,SubscriptionsListenRequestParamsSchema:()=>Ir,SubscriptionsListenRequestSchema:()=>kr,SubscriptionsListenResultMetaSchema:()=>Mr,SubscriptionsListenResultSchema:()=>Nr,TaskAugmentedRequestParamsSchema:()=>$t,TaskCreationParamsSchema:()=>ua,TaskMetadataSchema:()=>rr,TaskSchema:()=>pt,TaskStatusNotificationParamsSchema:()=>An,TaskStatusNotificationSchema:()=>ha,TaskStatusSchema:()=>xn,TextContentSchema:()=>no,TextResourceContentsSchema:()=>is,TitledMultiSelectEnumSchemaSchema:()=>zs,TitledSingleSelectEnumSchemaSchema:()=>gs,ToolAnnotationsSchema:()=>Yr,ToolChoiceSchema:()=>un,ToolExecutionSchema:()=>Xr,ToolListChangedNotificationSchema:()=>on,ToolResultContentSchema:()=>dn,ToolSchema:()=>ds,ToolUseContentSchema:()=>Fr,UnsubscribeRequestParamsSchema:()=>Cr,UnsubscribeRequestSchema:()=>qr,UntitledMultiSelectEnumSchemaSchema:()=>Rs,UntitledSingleSelectEnumSchemaSchema:()=>Ss});var At=e=>Xo.safeParse(e).success,zc=e=>Zo.safeParse(e).success,fo=e=>to.safeParse(e).success,So=e=>oo.safeParse(e).success;var yc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required";var Ba=e=>ts.safeParse(e).success,bc=e=>ss.safeParse(e).success;var zu="Mcp-Param-",Vi="x-mcp-header",yu=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,bu=new Set(["string","integer","boolean","number"]);function Ga(e){let t=[],o=new Map,s=(i,a,c)=>{if(i===null||typeof i!="object")return;let u=i;if(Vi in u){if(!c||a.length===0)return`${Bn(a)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let d=u[Vi];if(typeof d!="string"||d.length===0)return`${Bn(a)}: x-mcp-header MUST be a non-empty string`;if(!yu.test(d))return`${Bn(a)}: x-mcp-header '${d}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let f=typeof u.type=="string"?u.type:void 0;if(f===void 0||!bu.has(f))return`${Bn(a)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${f??"<none>"}`;let S=d.toLowerCase(),R=o.get(S);if(R!==void 0)return`x-mcp-header '${d}' is not case-insensitively unique (also declared as '${R}')`;o.set(S,d),t.push({path:a,headerName:d,type:f})}let h=u.properties;if(h!==null&&typeof h=="object")for(let[d,f]of Object.entries(h)){let S=s(f,[...a,d],c);if(S!==void 0)return S}for(let d of vu){let f=u[d];if(f===void 0)continue;let S=Array.isArray(f)?f:f!==null&&typeof f=="object"&&wu.has(d)?Object.values(f):[f];for(let R of S){let v=s(R,[...a,`<${d}>`],!1);if(v!==void 0)return v}}},n=s(e,[],!0);return n===void 0?{valid:!0,declarations:t}:{valid:!1,reason:n}}var vu=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],wu=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function Bn(e){return e.length===0?"<root>":e.join(".")}var vc="=?base64?",wc="?=";function Tu(e){if(typeof e=="string")return e;if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)?void 0:String(e)}function Eu(e){if(e.length===0||e.startsWith(vc)&&e.endsWith(wc)||e!==e.trim())return!0;for(let t=0;t<e.length;t++){let o=e.codePointAt(t);if(!(o===9||o>=32&&o<=126))return!0}return!1}function Pu(e){let t=new TextEncoder().encode(e),o="";for(let s of t)o+=String.fromCodePoint(s);return btoa(o)}function Wa(e){return Eu(e)?`${vc}${Pu(e)}${wc}`:e}function Cu(e,t){let o=e;for(let s of t){if(o===null||typeof o!="object")return;o=o[s]}return o}function Tc(e,t){let o={};for(let s of e){let n=Cu(t,s.path);if(n==null)continue;let i=Tu(n);i!==void 0&&(o[`${zu}${s.headerName}`]=Wa(i))}return o}var po=-32020,Rm=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[D.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[po,D.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[D.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[D.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[D.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[po],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half \u2014 including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[D.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[po],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],zm={[D.ParseError]:400,[D.InvalidRequest]:400,[D.MethodNotFound]:404,[D.UnsupportedProtocolVersion]:400,[D.MissingRequiredClientCapability]:400,[po]:400},Hi={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};function Ec(e,t){let o=Object.hasOwn(Hi,e)?Hi[e]:void 0;if(o===void 0)return;let s=qu(t)?t[o]:void 0;return{field:o,value:typeof s=="string"?s:void 0}}function qu(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Yn(e,t){return Si(e,t)}function Cs(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}function Na(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}var Fi=!1,xa="draft-2020-12";function Iu(e,t="input"){let o=e["~standard"],s;if(o.jsonSchema)s=o.jsonSchema[t]({target:xa});else if(o.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");Fi||(Fi=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),s=ra(e,{target:xa,io:t})}else throw new Error(`Schema library "${o.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return s.type!==void 0?s:Pc(s)?{type:"object",...s}:s;if(s.type!==void 0&&s.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(s.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...s}}function Pc(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let o=e[t];if(Array.isArray(o)&&o.length>0)return o.every(s=>s!==null&&typeof s=="object"&&(s.type==="object"||Pc(s)))}return!1}function ku(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}async function Oa(e,t){let o=await e["~standard"].validate(t);return o.issues&&o.issues.length>0?{success:!1,error:o.issues.map(s=>ku(s)).join(", ")}:{success:!0,data:o.value}}function Ou(e){let t=ra(e,{target:xa,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}var $u=/\\\.\\d\{(\d+)\}/;function Mu(e){let t=$u.exec(e),o=[void 0,-1,0];return t&&o.push(Number(t[1])),[!1,!0].flatMap(s=>[!1,!0].flatMap(n=>o.map(i=>Pt.datetime({local:s,offset:n,precision:i}))))}function Nu(e,t){let o;switch(e){case"email":o=[gi()];break;case"uri":o=[er()];break;case"date":o=[Pt.date()];break;case"date-time":o=Mu(t);break}return new Set(o.map(s=>Ou(s)).filter(s=>s!==void 0))}function xu(e,t,o){return o!=="zod"?!0:Nu(e,t).has(t)}function ks(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Au(e){try{return Iu(e,"input")}catch(t){let o=t instanceof Error?t.message:String(t);throw new K(D.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${o}`)}}var ju=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function Ka(e){return ju.has(e)||e.startsWith("x-")}var Lu=new Set(["$schema",...Object.keys(ho.shape.requestedSchema.shape)]),Ji={string:Cs([lo,Ss,gs,_s]),number:Cs([uo]),integer:Cs([uo]),boolean:Cs([fs]),array:Cs([Rs,zs])},Uu=new Set(lo.shape.format.unwrap().options);function Du(e,t,o,s){if(!ks(e))return e;let n=typeof e.type=="string"&&Object.hasOwn(Ji,e.type)?Ji[e.type]:void 0;if(n===void 0)return e;let i={};for(let[a,c]of Object.entries(e))n.has(a)||Ka(a)?i[a]=c:a==="pattern"&&e.type==="string"&&typeof e.format=="string"?Uu.has(e.format)?(typeof c!="string"||!xu(e.format,c,o))&&s.push(`${t}.${a}`):i[a]=c:s.push(`${t}.${a}`);return i}function Vu(e,t){let o={},s=[];for(let[n,i]of Object.entries(e))n==="properties"&&ks(i)?o[n]=Object.fromEntries(Object.entries(i).map(([a,c])=>[a,Du(c,`properties.${a}`,t,s)])):Lu.has(n)?o[n]=i:Ka(n)||s.push(n);if(s.length>0)throw new K(D.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${s.join(", ")}`);return o}function Hu(e,t){if(!ks(e.properties))return t;let o=Object.entries(e.properties).filter(([,s])=>!Yn(ys,s).success).map(([s])=>`properties.${s}`);return o.length>0?o.join(", "):t}function Aa(e,t,o=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((s,n)=>Aa(s,t[n],`${o}[${n}]`)):!ks(e)||!ks(t)?[]:Object.entries(e).flatMap(([s,n])=>{let i=o?`${o}.${s}`:s;return Object.prototype.hasOwnProperty.call(t,s)?Aa(n,t[s],i):Ka(s)?[]:[i]})}function Fu(e){if(!Na(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,o=Vu(Au(e.requestedSchema),t),s=Yn(ho.shape.requestedSchema,o);if(!s.success)throw new K(D.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${Hu(o,s.error.message)}`);let n=Aa(o,s.data);if(n.length>0)throw new K(D.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);let i=(s.data.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(s.data.properties,a));if(i.length>0)throw new K(D.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:s.data}}function Ju(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,o=typeof e.requestState=="string";if(!t&&!o)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}var ym=Object.assign(Ju,{elicit(e){try{return{method:"elicitation/create",params:Fu(e)}}catch(t){throw t instanceof K?new TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});var Bu=!0,Gu=10,Wu=250;function Cc(e){return{autoFulfill:e?.autoFulfill??Bu,maxRounds:e?.maxRounds??Gu}}function Ku(e,t,o){let s=t!==void 0&&Object.keys(t).length>0;return!s&&o===void 0?e:{...e,...s&&{inputResponses:t},...o!==void 0&&{requestState:o}}}function Yu(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function Xu(e,t){return new Promise((o,s)=>{if(t?.aborted){s(t.reason instanceof k?t.reason:new k(I.RequestTimeout,String(t.reason)));return}let n=setTimeout(()=>{t?.removeEventListener("abort",i),o()},e),i=()=>{clearTimeout(n),s(t?.reason instanceof k?t.reason:new k(I.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",i,{once:!0})})}function Zu(e){let t=new AbortController,o=()=>t.abort(e?.reason);return e?.addEventListener("abort",o,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:s=>t.abort(s),dispose:()=>e?.removeEventListener("abort",o)}}async function Qu(e){let{config:t,method:o,originalParams:s,requestOptions:n,hooks:i,signal:a}=e,c=e.flowStartedAt??Date.now(),u=e.firstPayload,h=0;for(;;){if(h+=1,h>t.maxRounds)throw new k(I.InputRequiredRoundsExceeded,Yu(o,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:u.inputRequests,...u.requestState!==void 0&&{requestState:u.requestState}}});n.onprogress?.({progress:h,message:`Fulfilling input required by '${o}' (round ${h})`});let d=Object.entries(u.inputRequests??{}),f;if(d.length>0){let v=Zu(a);try{let z=await Promise.all(d.map(async([y,V])=>{try{return[y,await i.dispatchInputRequest(y,V,v.signal)]}catch(H){throw v.abort(H),H}}));f=Object.fromEntries(z)}finally{v.dispose()}}else await Xu(Wu,a);let S={...n.timeout!==void 0&&{timeout:n.timeout}};if(n.maxTotalTimeout!==void 0){let v=Date.now()-c,z=n.maxTotalTimeout-v;if(z<=0)throw new k(I.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:v});S.maxTotalTimeout=z}let R=await i.retry(Ku(s,f,u.requestState),S);if(yc(R)){u={inputRequests:R.inputRequests??{},...R.requestState!==void 0&&{requestState:R.requestState}};continue}return R}}var ed=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],td={IdJagTokenExchangeResponseSchema:Ln,OAuthClientInformationFullSchema:Es,OAuthClientInformationSchema:Dn,OAuthClientMetadataSchema:Un,OAuthClientRegistrationErrorSchema:Pa,OAuthErrorResponseSchema:Ts,OAuthMetadataSchema:mo,OAuthProtectedResourceMetadataSchema:bs,OAuthTokenRevocationRequestSchema:Ca,OAuthTokensSchema:ws,OpenIdProviderDiscoveryMetadataSchema:vs,OpenIdProviderMetadataSchema:jn},qc={},Ic={};function kc(e,t){let o=e.slice(0,-6);qc[o]=t,Ic[o]=s=>t.safeParse(s).success}for(let e of ed)kc(e,Ru[e]);for(let[e,t]of Object.entries(td))kc(e,t);var od=Object.freeze(qc),Oc=Object.freeze(Ic);function sd(e){switch(e){case"initialize":case"notifications/initialized":return Qe(void 0);case"server/discover":return Qe(Kn);default:return}}var Xn=6e4,rd=[Ye,Qt,kt,eo],nd=["inputResponses","requestState"];function Bi(e,t){let o=e.params;if(!Is(o))return{message:e,lifted:{}};let s=o._meta,n=Is(s)?rd.filter(u=>u in s):[],i=t==="request"?nd.filter(u=>u in o):[];if(n.length===0&&i.length===0)return{message:e,lifted:{}};let a={},c={...o};if(n.length>0&&Is(s)){let u={},h={...s};for(let d of n)u[d]=s[d],delete h[d];a.envelope=u,Object.keys(h).length>0?c._meta=h:delete c._meta}for(let u of i)u==="inputResponses"&&(a.inputResponses=c[u]),u==="requestState"&&(a.requestState=c[u]),delete c[u];return{message:{...e,params:c},lifted:a}}function Gi(e,t){let o=e.validateResult(t,void 0);if(!(!o.ok&&o.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(s){let n=e.validateResult(t,s);return n.ok?{value:n.value}:{issues:[{message:n.reason==="invalid"?n.message:`not-in-era: ${t}`}]}}}}}function Ya(e){return()=>e}var ad=Ya(void 0),id,$c=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{id=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??or,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let o=e.params??{};return{...e,params:{...o,_meta:{...t,...o._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new k(I.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId!==void 0&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,o,s,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:o,resetTimeoutOnProgress:n,onTimeout:s})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let o=Date.now()-t.startTime;if(t.maxTotalTimeout&&o>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new k(I.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:o});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let o=this.transport?.onerror;this._transport.onerror=n=>{o?.(n),this._onerror(n)};let s=this._transport?.onmessage;this._transport.onmessage=(n,i)=>{s?.(n,i),fo(n)||So(n)?this._onresponse(n):At(n)?this._onrequest(n,i):zc(n)?this._onnotification(n,i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(n)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let s of this._timeoutInfo.values())clearTimeout(s.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let o=new k(I.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let s of e.values())s(o);for(let s of t.values())s.abort(o)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:o}=Bi(e,"notification"),s=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let a=Ui(t.classification);if(a!==s.era){this._onerror(new Error(`Era mismatch on inbound notification '${o.method}': classified as ${a} but this instance serves ${s.era}`));return}}if(ka(o.method)&&!s.hasNotificationMethod(o.method))return;let n=this._notificationHandlers.get(o.method),i=this.fallbackNotificationHandler;n===void 0&&i===void 0||Promise.resolve().then(()=>n===void 0?i(o):n(o,s)).catch(a=>this._onerror(new Error(`Uncaught error in notification handler: ${a}`)))}_onrequest(e,t){let{message:o,lifted:s}=Bi(e,"request"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let i=this._transport,a=(z,y,V)=>{let H={jsonrpc:"2.0",id:o.id,error:{code:z,message:y,...V!==void 0&&{data:V}}};i?.send(H).catch(M=>this._onerror(new Error(`Failed to send an error response: ${M}`)))};if(t?.classification!==void 0){let z=Ui(t.classification);if(z!==n.era){this._onerror(new Error(`Era mismatch on inbound request '${o.method}': classified as ${z} but this instance serves ${n.era}`));let y=t.classification.revision??z;a(D.UnsupportedProtocolVersion,`Unsupported protocol version: ${y}`,{supported:this._supportedProtocolVersions,requested:y});return}}if(Ia(o.method)&&!n.hasRequestMethod(o.method)&&!(Di(o.method)&&this._customSchemaRequestMethods.has(o.method))){a(D.MethodNotFound,"Method not found");return}let c=this._requestHandlers.get(o.method)??this.fallbackRequestHandler;if(c===void 0){a(D.MethodNotFound,"Method not found");return}let u=n.checkInboundEnvelope(s);if(u!==void 0){a(D.InvalidParams,u);return}let h=(z,y)=>this._notificationViaCodec(this._resolveOutboundCodec(z.method),z,{...y,relatedRequestId:o.id}),d=(z,y,V)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(z.method),z,y,{...V,relatedRequestId:o.id}),f=new AbortController;this._requestHandlerAbortControllers.set(o.id,f);let S=s.inputResponses===void 0?void 0:cd(s.inputResponses),R={sessionId:i?.sessionId,mcpReq:{id:o.id,method:o.method,_meta:o.params?._meta,...s.envelope!==void 0&&{envelope:s.envelope},...S!==void 0&&{inputResponses:S.accepted},...S!==void 0&&S.droppedKeys.length>0&&{droppedInputResponseKeys:S.droppedKeys},requestState:s.requestState===void 0?ad:Ya(s.requestState),signal:f.signal,send:((z,y,V)=>{let H=this._resolveOutboundCodec(z.method);if(this._assertOutboundRequestInEra(H,z.method),Na(y))return d(z,y,V);let M=Gi(H,z.method);if(M===void 0)throw new TypeError(`'${z.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return d(z,M,y)}),notify:h},http:t?.authInfo?{authInfo:t.authInfo}:void 0},v=this.buildContext(R,t);Promise.resolve().then(()=>c(o,v)).then(async z=>{if(f.signal.aborted)return;let y;try{y=n.encodeResult(o.method,z,this._outboundServerInfo())}catch(H){this._onerror(new Error(`Failed to encode result for ${o.method}: ${H}`)),a(D.InternalError,"Internal error");return}let V={result:y,jsonrpc:"2.0",id:o.id};await i?.send(V)},async z=>{if(f.signal.aborted)return;let y=Number.isSafeInteger(z.code)?z.code:D.InternalError,V={jsonrpc:"2.0",id:o.id,error:{code:n.encodeErrorCode(y),message:z.message??"Internal error",...z.data!==void 0&&{data:z.data}}};await i?.send(V)}).catch(z=>this._onerror(new Error(`Failed to send response: ${z}`))).finally(()=>{this._requestHandlerAbortControllers.get(o.id)===f&&this._requestHandlerAbortControllers.delete(o.id)})}_onprogress(e){let{progressToken:t,...o}=e.params,s=Number(t),n=this._progressHandlers.get(s);if(!n){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(c);return}n(o)}_onresponse(e){let t=Number(e.id),o=this._responseHandlers.get(t);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),fo(e)?o(e):o(K.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,o){let s=this._resolveOutboundCodec(e.method);if(Na(t))return Di(e.method)||this._assertOutboundRequestInEra(s,e.method),this._requestWithSchemaViaCodec(s,e,t,o);this._assertOutboundRequestInEra(s,e.method);let n=Gi(s,e.method);if(n===void 0)throw new TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(s,e,n,t)}_negotiatedWireCodec(){return Qe(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=sd(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Ia(t)&&!e.hasRequestMethod(t))throw new k(I.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,o){let s=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(s,e.method),this._requestWithSchemaViaCodec(s,e,t,o)}_requestWithSchemaViaCodec(e,t,o,s){let{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a,headers:c}=s??{},u=Date.now(),h,d;return new Promise((f,S)=>{let R=g=>{S(g)};if(!this._transport){R(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(g){R(g);return}if(s?.signal?.aborted){let g=s.signal.reason;throw g instanceof k?g:new k(I.RequestTimeout,String(g))}let v=e.era===Kn&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,z=this._requestMessageId++;d=z;let y={...t,jsonrpc:"2.0",id:z};s?.onprogress&&(this._progressHandlers.set(z,s.onprogress),y.params={...t.params,_meta:{...t.params?._meta,progressToken:z}});let V=this._envelopeOutbound(y),H=!1,M=g=>{H||(this._progressHandlers.delete(z),v===void 0?t.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:z,reason:String(g)}}),{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(j=>this._onerror(new Error(`Failed to send cancellation: ${j}`))):v.abort(),S(g instanceof k?g:new k(I.RequestTimeout,String(g))))};this._responseHandlers.set(z,g=>{if(s?.signal?.aborted)return;if(H=!0,g instanceof Error)return S(g);let j;try{j=e.decodeResult(t.method,g.result)}catch(B){return S(B instanceof Error?B:new Error(String(B)))}if(j.kind==="invalid")return S(j.error);if(j.kind==="input_required"){if(s?.allowInputRequired===!0)return f(hd(j));let B={codec:e,request:t,resultSchema:o,options:s,flowStartedAt:u,retry:(Z,me)=>this._requestWithSchemaViaCodec(e,Z===void 0?{method:t.method}:{method:t.method,params:Z},o,me)};return f(this._resolveNonCompleteResult(j,B))}let G=j.result;Oa(o,G).then(B=>{B.success?f(B.data):S(new k(I.InvalidResult,`Invalid result for ${t.method}: ${B.error}`))},S)}),h=()=>M(s?.signal?.reason),s?.signal?.addEventListener("abort",h,{once:!0});let W=s?.timeout??Xn,T=()=>M(new k(I.RequestTimeout,"Request timed out",{timeout:W}));this._setupTimeout(z,W,s?.maxTotalTimeout,T,s?.resetTimeoutOnProgress??!1),this._transport.send(V,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a,headers:c,requestSignal:v?.signal}).catch(g=>{this._progressHandlers.delete(z),S(g)})}).finally(()=>{h&&s?.signal?.removeEventListener("abort",h),d!==void 0&&(this._responseHandlers.delete(d),this._cleanupTimeout(d))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,o){if(!this._transport)throw new k(I.NotConnected,"Not connected");if(ka(t.method)&&!e.hasNotificationMethod(t.method))throw new k(I.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let s=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&o?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(s,o).catch(n=>this._onerror(n))});return}await this._transport.send(s,o)}setRequestHandler(e,t,o){this.assertRequestHandlerCapability(e);let s;if(typeof t=="function"){if(!Ia(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);s=(n,i)=>{let a=this._negotiatedWireCodec(),c=a.validateRequest(e,n);if(!c.ok&&c.reason==="not-in-era"&&(c=a.validateInputRequest(e,n)),!c.ok)throw c.reason==="not-in-era"?new K(D.InternalError,`No wire schema for ${e} in the resolved era`):new Error(c.message);return Promise.resolve(t(c.value,i))}}else if(o)s=async(n,i)=>{let a=await Oa(t.params,{...n.params});if(!a.success)throw new K(D.InvalidParams,`Invalid params for ${e}: ${a.error}`);return o(a.data,i)};else throw new TypeError("setRequestHandler: handler is required");typeof t=="function"?this._customSchemaRequestMethods.delete(e):this._customSchemaRequestMethods.add(e),this._requestHandlers.set(e,this._wrapHandler(e,s))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,o){if(typeof t=="function"){if(!ka(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(s,n)=>{let i=n.validateNotification(e,s);if(!i.ok)throw i.reason==="not-in-era"?new K(D.InternalError,`No wire schema for ${e} in the resolved era`):new Error(i.message);return Promise.resolve(t(i.value))});return}if(!o)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async s=>{let n=await Oa(t.params,{...s.params});if(!n.success)throw new K(D.InvalidParams,`Invalid params for notification ${e}: ${n.error}`);await o(n.data,s)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Is(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Mc(e,t){let o={...e};for(let s in t){let n=s,i=t[n];if(i===void 0)continue;let a=o[n];o[n]=Is(a)&&Is(i)?{...a,...i}:i}return o}function Gn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cd(e){let t={},o=[];if(!Gn(e))return{accepted:t,droppedKeys:o};for(let[s,n]of Object.entries(e)){if(!Gn(n)||"method"in n||"result"in n){o.push(s);continue}t[s]=n}return{accepted:t,droppedKeys:o}}function Wi(e){throw new k(I.SendFailed,`ctx.mcpReq.${e} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function ld(e,t,o,s,n){return{sessionId:n,mcpReq:{id:e,method:t,_meta:o?._meta,requestState:Ya(void 0),signal:s,send:(()=>Wi("send")),notify:()=>Wi("notify")}}}async function ud(e,t,o,s,n){if(!Gn(s)||typeof s.method!="string")throw new k(I.InvalidResult,`Invalid input request '${o}': each inputRequests entry must be an embedded request object with a method`,{key:o});let i=s.method;if(!t.hasInputRequestMethod(i))throw new k(I.InvalidResult,`Invalid input request '${o}': '${i}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:o,method:i});let a=e.getRequestHandler(i);if(a===void 0)throw new k(I.CapabilityNotSupported,`Cannot fulfil input request '${o}': no handler is registered for '${i}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:o,method:i});let c=Gn(s.params)?s.params:void 0;return await a({jsonrpc:"2.0",id:o,method:i,...c!==void 0&&{params:c}},e.buildContext(ld(o,i,c,n,e.sessionId)))}function dd(e,t){return{...e?.signal!==void 0&&{signal:e.signal},...e?.onprogress!==void 0&&{onprogress:e.onprogress},...e?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:e.resetTimeoutOnProgress},...e?.headers!==void 0&&{headers:e.headers},...t.timeout!==void 0&&{timeout:t.timeout},...t.maxTotalTimeout!==void 0&&{maxTotalTimeout:t.maxTotalTimeout},allowInputRequired:!0}}function Nc(e,t,o,s){let{codec:n,request:i,options:a,flowStartedAt:c}=s,u={inputRequests:o.inputRequests,...o.requestState!==void 0&&{requestState:o.requestState}},h={dispatchInputRequest:(d,f,S)=>ud(e,n,d,f,S),retry:(d,f)=>s.retry(d,dd(a,f))};return Qu({config:t,method:i.method,originalParams:i.params,firstPayload:u,flowStartedAt:c,signal:a?.signal,requestOptions:{...a?.timeout!==void 0&&{timeout:a.timeout},...a?.maxTotalTimeout!==void 0&&{maxTotalTimeout:a.maxTotalTimeout},...a?.onprogress!==void 0&&{onprogress:a.onprogress}},hooks:h})}function hd(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}var md=bi((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,o=/\\([\u000b\u0020-\u00ff])/g,s=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=n;function n(c){if(!c)throw new TypeError("argument string is required");var u=typeof c=="object"?i(c):c;if(typeof u!="string")throw new TypeError("argument string is required to be a string");var h=u.indexOf(";"),d=h!==-1?u.slice(0,h).trim():u.trim();if(!s.test(d))throw new TypeError("invalid media type");var f=new a(d.toLowerCase());if(h!==-1){var S,R,v;for(t.lastIndex=h;R=t.exec(u);){if(R.index!==h)throw new TypeError("invalid parameter format");h+=R[0].length,S=R[1].toLowerCase(),v=R[2],v.charCodeAt(0)===34&&(v=v.slice(1,-1),v.indexOf("\\")!==-1&&(v=v.replace(o,"$1"))),f.parameters[S]=v}if(h!==u.length)throw new TypeError("invalid parameter format")}return f}function i(c){var u;if(typeof c.getHeader=="function"?u=c.getHeader("content-type"):typeof c.headers=="object"&&(u=c.headers&&c.headers["content-type"]),typeof u!="string")throw new TypeError("content-type header is missing from object");return u}function a(c){this.parameters=Object.create(null),this.type=c}})),pd=wi(md(),1);function xc(e){if(e)try{return pd.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();return t===""||e.slice(t.length).includes(",")?void 0:t}}var fd=10*1024*1024;function Ki(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Ac(e=fetch,t){return t?async(o,s)=>e(o,{...t,...s,headers:s?.headers?{...Ki(t.headers),...Ki(s.headers)}:t.headers}):e}var Sd=new Set([301,302,303,307,308]),gd=5;function _d(e,t){return e.protocol===t.protocol&&e.host===t.host?!0:e.protocol==="http:"&&t.protocol==="https:"&&e.hostname===t.hostname&&!e.port&&!t.port}function jc(e,t){let o=Sd.has(t.status)?t.headers?.get("location"):void 0;if(o)try{return new URL(o,e)}catch{return}}var Lc=new WeakSet;function Uc(e){let t=(o,s)=>e(o,s);return Lc.add(t),t}function $s(e){return Lc.has(e)?e:async(t,o)=>{if(o?.redirect==="error"||o?.redirect==="manual")return e(t,o);let s=(o?.method??"GET").toUpperCase(),n=t;for(let i=0;;i++){let a=await e(n,{...o,redirect:"manual"}),c=jc(n,a);if(!c||i===gd)return a;let u=new URL(n),h=s==="GET"||a.status===307||a.status===308,d=!(c.username||c.password)||c.username===u.username&&c.password===u.password;if(!h||!d||!_d(u,c))return a;await a.text?.().catch(()=>{}),n=c}}}function Dc(e,t){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose where it points";let o=jc(t.url||e,t);if(o)return o.username=o.password=o.search=o.hash="",o.protocol==="http:"&&new URL(t.url||e).protocol==="https:"?(o.protocol="https:",`Redirect from https to plain http not followed; try ${o.href} as the endpoint`):`Redirect to ${o.href} not followed; use that URL as the endpoint if it is the intended server`}function Ms(e,t){let o=typeof e;if(o!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let s=e.length;if(s!==t.length)return!1;for(let n=0;n<s;n++)if(!Ms(e[n],t[n]))return!1;return!0}if(o==="object"){if(!e||!t)return e===t;let s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)return!1;for(let i of s)if(!Ms(e[i],t[i]))return!1;return!0}return e===t}function Ne(e){return encodeURI(Rd(e))}function Rd(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var zd={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},yd={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},bd={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},vd=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function jt(e,t=Object.create(null),o=vd,s=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,o.href);a.hash.length>1?t[a.href]=e:(a.hash="",s===""?o=a:jt(e,t,o))}}else if(e!==!0&&e!==!1)return t;let n=o.href+(s?"#"+s:"");if(t[n]!==void 0)throw new Error(`Duplicate schema URI "${n}".`);if(t[n]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:n}),e.$ref&&e.__absolute_ref__===void 0){let i=new URL(e.$ref,o.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let i=new URL(e.$recursiveRef,o.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){let i=new URL("#"+e.$anchor,o.href);t[i.href]=e}for(let i in e){if(bd[i])continue;let a=`${s}/${Ne(i)}`,c=e[i];if(Array.isArray(c)){if(zd[i]){let u=c.length;for(let h=0;h<u;h++)jt(c[h],t,o,`${a}/${h}`)}}else if(yd[i])for(let u in c)jt(c[u],t,o,`${a}/${Ne(u)}`);else jt(c,t,o,a)}return t}var wd=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Td=[0,31,28,31,30,31,30,31,31,30,31,30,31],Ed=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Pd=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,Cd=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,qd=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Id=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,kd=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Od=/^(?:\/(?:[^~/]|~0|~1)*)*$/,$d=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Md=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Nd=e=>{if(e[0]==='"')return!1;let[t,o,...s]=e.split("@");return!t||!o||s.length!==0||t.length>64||o.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(o)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:o.split(".").every(n=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(n))},xd=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Ad=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,jd=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function Je(e){return e.test.bind(e)}var Vc={date:Hc,time:Fc.bind(void 0,!1),"date-time":Dd,duration:jd,uri:Fd,"uri-reference":Je(Cd),"uri-template":Je(qd),url:Je(Id),email:Nd,hostname:Je(Pd),ipv4:Je(xd),ipv6:Je(Ad),regex:Bd,uuid:Je(kd),"json-pointer":Je(Od),"json-pointer-uri-fragment":Je($d),"relative-json-pointer":Je(Md)};function Ld(e){return e%4===0&&(e%100!==0||e%400===0)}function Hc(e){let t=e.match(wd);if(!t)return!1;let o=+t[1],s=+t[2],n=+t[3];return s>=1&&s<=12&&n>=1&&n<=(s==2&&Ld(o)?29:Td[s])}function Fc(e,t){let o=t.match(Ed);if(!o)return!1;let s=+o[1],n=+o[2],i=+o[3],a=!!o[5];return(s<=23&&n<=59&&i<=59||s==23&&n==59&&i==60)&&(!e||a)}var Ud=/t|\s/i;function Dd(e){let t=e.split(Ud);return t.length==2&&Hc(t[0])&&Fc(!0,t[1])}var Vd=/\/|:/,Hd=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Fd(e){return Vd.test(e)&&Hd.test(e)}var Jd=/[^\\]\\Z/;function Bd(e){if(Jd.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}function Gd(e){let t=0,o=e.length,s=0,n;for(;s<o;)t++,n=e.charCodeAt(s++),n>=55296&&n<=56319&&s<o&&(n=e.charCodeAt(s),(n&64512)==56320&&s++);return t}function Q(e,t,o="2019-09",s=jt(t),n=!0,i=null,a="#",c="#",u=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:a,keyword:"false",keywordLocation:a,error:"False boolean schema."}]};let h=typeof e,d;switch(h){case"boolean":case"number":case"string":d=h;break;case"object":e===null?d="null":Array.isArray(e)?d="array":d="object";break;default:throw new Error(`Instances of "${h}" type are not supported.`)}let{$ref:f,$recursiveRef:S,$recursiveAnchor:R,type:v,const:z,enum:y,required:V,not:H,anyOf:M,allOf:W,oneOf:T,if:g,then:j,else:G,format:B,properties:Z,patternProperties:me,additionalProperties:Y,unevaluatedProperties:X,minProperties:ie,maxProperties:pe,propertyNames:xe,dependentRequired:Re,dependentSchemas:Ce,dependencies:Ae,prefixItems:be,items:fe,additionalItems:Ge,unevaluatedItems:We,contains:je,minContains:ce,maxContains:Se,minItems:ge,maxItems:$e,uniqueItems:St,minimum:ve,maximum:we,exclusiveMinimum:ze,exclusiveMaximum:qe,multipleOf:Ie,minLength:Le,maxLength:Ue,pattern:ot,__absolute_ref__:De,__absolute_recursive_ref__:gt}=t,E=[];if(R===!0&&i===null&&(i=t),S==="#"){let A=i===null?s[gt]:i,O=`${c}/$recursiveRef`,J=Q(e,i===null?t:i,o,s,n,A,a,O,u);J.valid||E.push({instanceLocation:a,keyword:"$recursiveRef",keywordLocation:O,error:"A subschema had errors."},...J.errors)}if(f!==void 0){let A=s[De||f];if(A===void 0){let C=`Unresolved $ref "${f}".`;throw De&&De!==f&&(C+=` Absolute URI "${De}".`),C+=`
3
+ Known schemas:
4
+ - ${Object.keys(s).join(`
5
+ - `)}`,new Error(C)}let O=`${c}/$ref`,J=Q(e,A,o,s,n,i,a,O,u);if(J.valid||E.push({instanceLocation:a,keyword:"$ref",keywordLocation:O,error:"A subschema had errors."},...J.errors),o==="4"||o==="7")return{valid:E.length===0,errors:E}}if(Array.isArray(v)){let A=v.length,O=!1;for(let J=0;J<A;J++)if(d===v[J]||v[J]==="integer"&&d==="number"&&e%1===0&&e===e){O=!0;break}O||E.push({instanceLocation:a,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${v.join('", "')}".`})}else v==="integer"?(d!=="number"||e%1||e!==e)&&E.push({instanceLocation:a,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${v}".`}):v!==void 0&&d!==v&&E.push({instanceLocation:a,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${v}".`});if(z!==void 0&&(d==="object"||d==="array"?Ms(e,z)||E.push({instanceLocation:a,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(z)}.`}):e!==z&&E.push({instanceLocation:a,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(z)}.`})),y!==void 0&&(d==="object"||d==="array"?y.some(A=>Ms(e,A))||E.push({instanceLocation:a,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`}):y.some(A=>e===A)||E.push({instanceLocation:a,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`})),H!==void 0){let A=`${c}/not`;Q(e,H,o,s,n,i,a,A).valid&&E.push({instanceLocation:a,keyword:"not",keywordLocation:A,error:'Instance matched "not" schema.'})}let Ve=[];if(M!==void 0){let A=`${c}/anyOf`,O=E.length,J=!1;for(let C=0;C<M.length;C++){let w=M[C],U=Object.create(u),L=Q(e,w,o,s,n,R===!0?i:null,a,`${A}/${C}`,U);E.push(...L.errors),J=J||L.valid,L.valid&&Ve.push(U)}J?E.length=O:E.splice(O,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:A,error:"Instance does not match any subschemas."})}if(W!==void 0){let A=`${c}/allOf`,O=E.length,J=!0;for(let C=0;C<W.length;C++){let w=W[C],U=Object.create(u),L=Q(e,w,o,s,n,R===!0?i:null,a,`${A}/${C}`,U);E.push(...L.errors),J=J&&L.valid,L.valid&&Ve.push(U)}J?E.length=O:E.splice(O,0,{instanceLocation:a,keyword:"allOf",keywordLocation:A,error:"Instance does not match every subschema."})}if(T!==void 0){let A=`${c}/oneOf`,O=E.length,J=T.filter((C,w)=>{let U=Object.create(u),L=Q(e,C,o,s,n,R===!0?i:null,a,`${A}/${w}`,U);return E.push(...L.errors),L.valid&&Ve.push(U),L.valid}).length;J===1?E.length=O:E.splice(O,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:A,error:`Instance does not match exactly one subschema (${J} matches).`})}if((d==="object"||d==="array")&&Object.assign(u,...Ve),g!==void 0){let A=`${c}/if`;if(Q(e,g,o,s,n,i,a,A,u).valid){if(j!==void 0){let O=Q(e,j,o,s,n,i,a,`${c}/then`,u);O.valid||E.push({instanceLocation:a,keyword:"if",keywordLocation:A,error:'Instance does not match "then" schema.'},...O.errors)}}else if(G!==void 0){let O=Q(e,G,o,s,n,i,a,`${c}/else`,u);O.valid||E.push({instanceLocation:a,keyword:"if",keywordLocation:A,error:'Instance does not match "else" schema.'},...O.errors)}}if(d==="object"){if(V!==void 0)for(let C of V)C in e||E.push({instanceLocation:a,keyword:"required",keywordLocation:`${c}/required`,error:`Instance does not have required property "${C}".`});let A=Object.keys(e);if(ie!==void 0&&A.length<ie&&E.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${c}/minProperties`,error:`Instance does not have at least ${ie} properties.`}),pe!==void 0&&A.length>pe&&E.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${c}/maxProperties`,error:`Instance does not have at least ${pe} properties.`}),xe!==void 0){let C=`${c}/propertyNames`;for(let w in e){let U=`${a}/${Ne(w)}`,L=Q(w,xe,o,s,n,i,U,C);L.valid||E.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:C,error:`Property name "${w}" does not match schema.`},...L.errors)}}if(Re!==void 0){let C=`${c}/dependantRequired`;for(let w in Re)if(w in e){let U=Re[w];for(let L of U)L in e||E.push({instanceLocation:a,keyword:"dependentRequired",keywordLocation:C,error:`Instance has "${w}" but does not have "${L}".`})}}if(Ce!==void 0)for(let C in Ce){let w=`${c}/dependentSchemas`;if(C in e){let U=Q(e,Ce[C],o,s,n,i,a,`${w}/${Ne(C)}`,u);U.valid||E.push({instanceLocation:a,keyword:"dependentSchemas",keywordLocation:w,error:`Instance has "${C}" but does not match dependant schema.`},...U.errors)}}if(Ae!==void 0){let C=`${c}/dependencies`;for(let w in Ae)if(w in e){let U=Ae[w];if(Array.isArray(U))for(let L of U)L in e||E.push({instanceLocation:a,keyword:"dependencies",keywordLocation:C,error:`Instance has "${w}" but does not have "${L}".`});else{let L=Q(e,U,o,s,n,i,a,`${C}/${Ne(w)}`);L.valid||E.push({instanceLocation:a,keyword:"dependencies",keywordLocation:C,error:`Instance has "${w}" but does not match dependant schema.`},...L.errors)}}}let O=Object.create(null),J=!1;if(Z!==void 0){let C=`${c}/properties`;for(let w in Z){if(!(w in e))continue;let U=`${a}/${Ne(w)}`,L=Q(e[w],Z[w],o,s,n,i,U,`${C}/${Ne(w)}`);if(L.valid)u[w]=O[w]=!0;else if(J=n,E.push({instanceLocation:a,keyword:"properties",keywordLocation:C,error:`Property "${w}" does not match schema.`},...L.errors),J)break}}if(!J&&me!==void 0){let C=`${c}/patternProperties`;for(let w in me){let U=new RegExp(w,"u"),L=me[w];for(let re in e){if(!U.test(re))continue;let _t=`${a}/${Ne(re)}`,He=Q(e[re],L,o,s,n,i,_t,`${C}/${Ne(w)}`);He.valid?u[re]=O[re]=!0:(J=n,E.push({instanceLocation:a,keyword:"patternProperties",keywordLocation:C,error:`Property "${re}" matches pattern "${w}" but does not match associated schema.`},...He.errors))}}}if(!J&&Y!==void 0){let C=`${c}/additionalProperties`;for(let w in e){if(O[w])continue;let U=`${a}/${Ne(w)}`,L=Q(e[w],Y,o,s,n,i,U,C);L.valid?u[w]=!0:(J=n,E.push({instanceLocation:a,keyword:"additionalProperties",keywordLocation:C,error:`Property "${w}" does not match additional properties schema.`},...L.errors))}}else if(!J&&X!==void 0){let C=`${c}/unevaluatedProperties`;for(let w in e)if(!u[w]){let U=`${a}/${Ne(w)}`,L=Q(e[w],X,o,s,n,i,U,C);L.valid?u[w]=!0:E.push({instanceLocation:a,keyword:"unevaluatedProperties",keywordLocation:C,error:`Property "${w}" does not match unevaluated properties schema.`},...L.errors)}}}else if(d==="array"){$e!==void 0&&e.length>$e&&E.push({instanceLocation:a,keyword:"maxItems",keywordLocation:`${c}/maxItems`,error:`Array has too many items (${e.length} > ${$e}).`}),ge!==void 0&&e.length<ge&&E.push({instanceLocation:a,keyword:"minItems",keywordLocation:`${c}/minItems`,error:`Array has too few items (${e.length} < ${ge}).`});let A=e.length,O=0,J=!1;if(be!==void 0){let C=`${c}/prefixItems`,w=Math.min(be.length,A);for(;O<w;O++){let U=Q(e[O],be[O],o,s,n,i,`${a}/${O}`,`${C}/${O}`);if(u[O]=!0,!U.valid&&(J=n,E.push({instanceLocation:a,keyword:"prefixItems",keywordLocation:C,error:"Items did not match schema."},...U.errors),J))break}}if(fe!==void 0){let C=`${c}/items`;if(Array.isArray(fe)){let w=Math.min(fe.length,A);for(;O<w;O++){let U=Q(e[O],fe[O],o,s,n,i,`${a}/${O}`,`${C}/${O}`);if(u[O]=!0,!U.valid&&(J=n,E.push({instanceLocation:a,keyword:"items",keywordLocation:C,error:"Items did not match schema."},...U.errors),J))break}}else for(;O<A;O++){let w=Q(e[O],fe,o,s,n,i,`${a}/${O}`,C);if(u[O]=!0,!w.valid&&(J=n,E.push({instanceLocation:a,keyword:"items",keywordLocation:C,error:"Items did not match schema."},...w.errors),J))break}if(!J&&Ge!==void 0){let w=`${c}/additionalItems`;for(;O<A;O++){let U=Q(e[O],Ge,o,s,n,i,`${a}/${O}`,w);u[O]=!0,U.valid||(J=n,E.push({instanceLocation:a,keyword:"additionalItems",keywordLocation:w,error:"Items did not match additional items schema."},...U.errors))}}}if(je!==void 0)if(A===0&&ce===void 0)E.push({instanceLocation:a,keyword:"contains",keywordLocation:`${c}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(ce!==void 0&&A<ce)E.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array has less items (${A}) than minContains (${ce}).`});else{let C=`${c}/contains`,w=E.length,U=0;for(let L=0;L<A;L++){let re=Q(e[L],je,o,s,n,i,`${a}/${L}`,C);re.valid?(u[L]=!0,U++):E.push(...re.errors)}U>=(ce||0)&&(E.length=w),ce===void 0&&Se===void 0&&U===0?E.splice(w,0,{instanceLocation:a,keyword:"contains",keywordLocation:C,error:"Array does not contain item matching schema."}):ce!==void 0&&U<ce?E.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array must contain at least ${ce} items matching schema. Only ${U} items were found.`}):Se!==void 0&&U>Se&&E.push({instanceLocation:a,keyword:"maxContains",keywordLocation:`${c}/maxContains`,error:`Array may contain at most ${Se} items matching schema. ${U} items were found.`})}if(!J&&We!==void 0){let C=`${c}/unevaluatedItems`;for(;O<A;O++){if(u[O])continue;let w=Q(e[O],We,o,s,n,i,`${a}/${O}`,C);u[O]=!0,w.valid||E.push({instanceLocation:a,keyword:"unevaluatedItems",keywordLocation:C,error:"Items did not match unevaluated items schema."},...w.errors)}}if(St)for(let C=0;C<A;C++){let w=e[C],U=typeof w=="object"&&w!==null;for(let L=0;L<A;L++){if(C===L)continue;let re=e[L];(w===re||U&&typeof re=="object"&&re!==null&&Ms(w,re))&&(E.push({instanceLocation:a,keyword:"uniqueItems",keywordLocation:`${c}/uniqueItems`,error:`Duplicate items at indexes ${C} and ${L}.`}),C=Number.MAX_SAFE_INTEGER,L=Number.MAX_SAFE_INTEGER)}}}else if(d==="number"){if(o==="4"?(ve!==void 0&&(ze===!0&&e<=ve||e<ve)&&E.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${ze?"or equal to ":""} ${ve}.`}),we!==void 0&&(qe===!0&&e>=we||e>we)&&E.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${qe?"or equal to ":""} ${we}.`})):(ve!==void 0&&e<ve&&E.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${ve}.`}),we!==void 0&&e>we&&E.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${we}.`}),ze!==void 0&&e<=ze&&E.push({instanceLocation:a,keyword:"exclusiveMinimum",keywordLocation:`${c}/exclusiveMinimum`,error:`${e} is less than ${ze}.`}),qe!==void 0&&e>=qe&&E.push({instanceLocation:a,keyword:"exclusiveMaximum",keywordLocation:`${c}/exclusiveMaximum`,error:`${e} is greater than or equal to ${qe}.`})),Ie!==void 0){let A=e%Ie;Math.abs(0-A)>=11920929e-14&&Math.abs(Ie-A)>=11920929e-14&&E.push({instanceLocation:a,keyword:"multipleOf",keywordLocation:`${c}/multipleOf`,error:`${e} is not a multiple of ${Ie}.`})}}else if(d==="string"){let A=Le===void 0&&Ue===void 0?0:Gd(e);Le!==void 0&&A<Le&&E.push({instanceLocation:a,keyword:"minLength",keywordLocation:`${c}/minLength`,error:`String is too short (${A} < ${Le}).`}),Ue!==void 0&&A>Ue&&E.push({instanceLocation:a,keyword:"maxLength",keywordLocation:`${c}/maxLength`,error:`String is too long (${A} > ${Ue}).`}),ot!==void 0&&!new RegExp(ot,"u").test(e)&&E.push({instanceLocation:a,keyword:"pattern",keywordLocation:`${c}/pattern`,error:"String does not match pattern."}),B!==void 0&&Vc[B]&&!Vc[B](e)&&E.push({instanceLocation:a,keyword:"format",keywordLocation:`${c}/format`,error:`String does not match format "${B}".`})}return{valid:E.length===0,errors:E}}var Wd=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",o=!0){this.schema=e,this.draft=t,this.shortCircuit=o,this.lookup=jt(e)}validate(e){return Q(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),jt(e,this.lookup)}},Xa=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=Pi(e,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return t==="draft-7"?"7":t}getValidator(e){let t=new Wd(e,this.draft??this._draftFor(e),this.shortcircuit);return o=>{let s=t.validate(o);return s.valid?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:s.errors.map(n=>`${n.instanceLocation}: ${n.error}`).join("; ")}}}};var Jc=!0;var Za;Za=globalThis.crypto;async function Kd(e){return(await Za).getRandomValues(new Uint8Array(e))}async function Yd(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",o=Math.pow(2,8)-Math.pow(2,8)%t.length,s="";for(;s.length<e;){let n=await Kd(e-s.length);for(let i of n)i<o&&(s+=t[i%t.length])}return s}async function Xd(e){return await Yd(e)}async function Zd(e){let t=await(await Za).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Qa(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Xd(e),o=await Zd(t);return{code_verifier:t,code_challenge:o}}var Ns=class extends Error{constructor(t,o){super(t),this.name="ParseError",this.type=o.type,this.field=o.field,this.value=o.value,this.line=o.line}},Bc=10,Qd=13,Lt=32;function ei(e){}function Kc(e){if(typeof e=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=ei,onError:o=ei,onRetry:s=ei,onComment:n,maxBufferSize:i}=e,a=[],c=0,u=!0,h,d="",f=0,S,R=!1;function v(T){if(R)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(u&&(u=!1,T.charCodeAt(0)===239&&T.charCodeAt(1)===187&&T.charCodeAt(2)===191&&(T=T.slice(3))),a.length===0){let G=y(T);G!==""&&(a.push(G),c=G.length),z();return}if(T.indexOf(`
6
+ `)===-1&&T.indexOf("\r")===-1){a.push(T),c+=T.length,z();return}a.push(T);let g=a.join("");a.length=0,c=0;let j=y(g);j!==""&&(a.push(j),c=j.length),z()}function z(){i!==void 0&&(c+d.length<=i||(R=!0,a.length=0,c=0,h=void 0,d="",f=0,S=void 0,o(new Ns(`Buffered data exceeded max buffer size of ${i} characters`,{type:"max-buffer-size-exceeded"}))))}function y(T){let g=0;if(T.indexOf("\r")===-1){let j=T.indexOf(`
7
+ `,g);for(;j!==-1;){if(g===j){f>0&&t({id:h,event:S,data:d}),h=void 0,d="",f=0,S=void 0,g=j+1,j=T.indexOf(`
8
+ `,g);continue}let G=T.charCodeAt(g);if(Gc(T,g,G)){let B=T.charCodeAt(g+5)===Lt?g+6:g+5,Z=T.slice(B,j);if(f===0&&T.charCodeAt(j+1)===Bc){t({id:h,event:S,data:Z}),h=void 0,d="",S=void 0,g=j+2,j=T.indexOf(`
9
+ `,g);continue}d=f===0?Z:`${d}
10
+ ${Z}`,f++}else Wc(T,g,G)?S=T.slice(T.charCodeAt(g+6)===Lt?g+7:g+6,j)||void 0:V(T,g,j);g=j+1,j=T.indexOf(`
11
+ `,g)}return T.slice(g)}for(;g<T.length;){let j=T.indexOf("\r",g),G=T.indexOf(`
12
+ `,g),B=-1;if(j!==-1&&G!==-1?B=j<G?j:G:j!==-1?j===T.length-1?B=-1:B=j:G!==-1&&(B=G),B===-1)break;V(T,g,B),g=B+1,T.charCodeAt(g-1)===Qd&&T.charCodeAt(g)===Bc&&g++}return T.slice(g)}function V(T,g,j){if(g===j){M();return}let G=T.charCodeAt(g);if(Gc(T,g,G)){let ie=T.charCodeAt(g+5)===Lt?g+6:g+5,pe=T.slice(ie,j);d=f===0?pe:`${d}
13
+ ${pe}`,f++;return}if(Wc(T,g,G)){S=T.slice(T.charCodeAt(g+6)===Lt?g+7:g+6,j)||void 0;return}if(G===105&&T.charCodeAt(g+1)===100&&T.charCodeAt(g+2)===58){let ie=T.slice(T.charCodeAt(g+3)===Lt?g+4:g+3,j);ie.includes("\0")||(h=ie);return}if(G===58){if(n){let ie=T.slice(g,j);n(ie.slice(T.charCodeAt(g+1)===Lt?2:1))}return}let B=T.slice(g,j),Z=B.indexOf(":");if(Z===-1){H(B,"",B);return}let me=B.slice(0,Z),Y=B.charCodeAt(Z+1)===Lt?2:1,X=B.slice(Z+Y);H(me,X,B)}function H(T,g,j){switch(T){case"event":S=g||void 0;break;case"data":d=f===0?g:`${d}
14
+ ${g}`,f++;break;case"id":g.includes("\0")||(h=g);break;case"retry":/^\d+$/.test(g)?s(parseInt(g,10)):o(new Ns(`Invalid \`retry\` value: "${g}"`,{type:"invalid-retry",value:g,line:j}));break;default:o(new Ns(`Unknown field "${T.length>20?`${T.slice(0,20)}\u2026`:T}"`,{type:"unknown-field",field:T,value:g,line:j}));break}}function M(){f>0&&t({id:h,event:S,data:d}),h=void 0,d="",f=0,S=void 0}function W(T={}){if(T.consume&&a.length>0){let g=a.join("");V(g,0,g.length)}u=!0,h=void 0,d="",f=0,S=void 0,a.length=0,c=0,R=!1}return{feed:v,reset:W}}function Gc(e,t,o){return o===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Wc(e,t,o){return o===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var Zn=class extends TransformStream{constructor({onError:t,onRetry:o,onComment:s,maxBufferSize:n}={}){let i;super({start(a){i=Kc({onEvent:c=>{a.enqueue(c)},onError(c){typeof t=="function"&&t(c),(t==="terminate"||c.type==="max-buffer-size-exceeded")&&a.error(c)},onRetry:o,onComment:s,maxBufferSize:n})},transform(a){i.feed(a)}})}};var As=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return Pe(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Pe(this,e)}constructor(e){super(e),this.name=new.target.name,Nt(this,new.target)}},ii=class extends As{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,o){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 \xA73.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(o)}`),this.kind=e,this.expected=t,this.received=o}},eh=class extends As{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`),this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},cl=class extends As{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},ta=class extends As{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(e)} but this call resolved ${JSON.stringify(t)}; refusing to present them to a different authorization server`),this.recordedIssuer=e,this.currentIssuer=t}},Yc=class extends As{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`),this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function ci(e,t,o){if(e)return typeof e.issuer!="string"?(o?.canPersistStamp!==!1&&console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field."),e.issuer===void 0?e:{...e,issuer:void 0}):ll(e.issuer,t)?e:void 0}function ll(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}function th(e){if(e==null)return!1;let t=e;return typeof t.tokens=="function"&&typeof t.clientInformation=="function"}async function oh(e,t,o){let{resourceMetadataUrl:s,scope:n}=xs(t.response);if(await li(e,{serverUrl:t.serverUrl,resourceMetadataUrl:s,scope:n,fetchFn:t.fetchFn,...o})!=="AUTHORIZED")throw new Be}function sh(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async o=>oh(e,o,t)}}var Be=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return Pe(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Pe(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",Nt(this,new.target)}};function di(e){return e?.authorization_response_iss_parameter_supported===!0}function hi({iss:e,expectedIssuer:t,issParameterSupported:o}){if(t!==void 0){if(e===void 0){if(o)throw new ii("authorization_response",t,void 0);return}if(e!==t)throw new ii("authorization_response",t,e)}}function ti(...e){let t=new Set;for(let o of e)if(o)for(let s of o.split(/\s+/))s&&t.add(s);return t.size>0?[...t].join(" "):void 0}function rh(e,t){if(!e)return!1;let o=new Set((t??"").split(/\s+/).filter(Boolean));for(let s of e.split(/\s+/))if(s&&!o.has(s))return!0;return!1}async function nh(e,t,o,s,n){if(typeof e=="string")return{authorizationCode:e,iss:t};let i=e.get("iss")??void 0,a=e.get("code");if(a)return{authorizationCode:a,iss:i};let c=(await o.discoveryState?.())?.authorizationServerMetadata;if(!c)try{c=(await pl(s,n)).authorizationServerMetadata}catch{c=void 0}if(!c)throw new Be("Authorization callback failed and the issuer could not be verified");hi({iss:i,expectedIssuer:c.issuer,issParameterSupported:di(c)});let u=e.get("error");throw u?new xt(u,e.get("error_description")??u,e.get("error_uri")??void 0):new Be("Authorization callback contained neither `code` nor `error`")}function ah(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var oi="code",si="S256";function ih(e,t){let o=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&ah(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?o?"client_secret_basic":"none":o&&t.includes("client_secret_basic")?"client_secret_basic":o&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":o?"client_secret_post":"none"}function ch(e,t,o,s){let{client_id:n,client_secret:i}=t;switch(e){case"client_secret_basic":lh(n,i,o);return;case"client_secret_post":uh(n,i,s);return;case"none":dh(n,s);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function lh(e,t,o){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let s=btoa(`${e}:${t}`);o.set("Authorization",`Basic ${s}`)}function uh(e,t,o){o.set("client_id",e),t&&o.set("client_secret",t)}function dh(e,t){t.set("client_id",e)}function ul(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function hh(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!ul(t.hostname))throw new cl(t.href);return t}function mh(e){for(let t of e??[]){let o;try{o=new URL(t)}catch{continue}if(o.protocol!=="http:"&&o.protocol!=="https:"||ul(o.hostname))return"native"}return"web"}function ph(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??mh(t.redirect_uris)}}async function Xc(e){let t=e instanceof Response?e.status:void 0,o=e instanceof Response?await e.text():e;try{let s=Ts.parse(JSON.parse(o));return xt.fromResponse(s)}catch(s){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${s}. Raw body: ${o}`;return new xt(et.ServerError,n)}}function Zc(e,t,o){let s=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${o} (provider implements no invalidateCredentials())`:`invalidating the stored ${o} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} \u2014 ${s}. Cause: ${JSON.stringify(t.message)}`)}async function li(e,t){try{return await ri(e,t)}catch(o){if(o instanceof xt){if(o.code===et.InvalidClient||o.code===et.UnauthorizedClient)return Zc(e,o,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await ri(e,t);if(o.code===et.InvalidGrant||o.code===et.InvalidDpopProof)return Zc(e,o,"tokens"),await e.invalidateCredentials?.("tokens"),await ri(e,t)}throw o}}function fh(e){let{requestedScope:t,resourceMetadata:o,authServerMetadata:s,clientMetadata:n}=e,i=t||o?.scopes_supported?.join(" ")||n.scope;return i&&s?.scopes_supported?.includes("offline_access")&&!i.split(" ").includes("offline_access")&&n.grant_types?.includes("refresh_token")&&(i=`${i} offline_access`),i}async function ri(e,{serverUrl:t,authorizationCode:o,iss:s,scope:n,resourceMetadataUrl:i,fetchFn:a,skipIssuerMetadataValidation:c,forceReauthorization:u}){let h=ph(e),d=await e.discoveryState?.(),f,S,R,v,z=i;if(!z&&d?.resourceMetadataUrl&&(z=new URL(d.resourceMetadataUrl)),d?.authorizationServerUrl){if(S=d.authorizationServerUrl,f=d.resourceMetadata,R=d.authorizationServerMetadata??await ml(S,{fetchFn:a,skipIssuerValidation:c}),!f)try{f=await dl(t,{resourceMetadataUrl:z},a)}catch(Y){if(Y instanceof TypeError)throw Y}(R!==d.authorizationServerMetadata||f!==d.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(S),resourceMetadataUrl:z?.toString(),resourceMetadata:f,authorizationServerMetadata:R})}else{let Y=await pl(t,{resourceMetadataUrl:z,fetchFn:a,skipIssuerMetadataValidation:c});S=Y.authorizationServerUrl,R=Y.authorizationServerMetadata,f=Y.resourceMetadata,v={authorizationServerUrl:String(S),resourceMetadataUrl:z?.toString(),resourceMetadata:f,authorizationServerMetadata:R}}let y=R?.issuer??String(S),V={issuer:y};if(await e.saveAuthorizationServerUrl?.(y),o!==void 0){let Y=d?.authorizationServerMetadata?.issuer??d?.authorizationServerUrl;if(Y===void 0){if(e.saveDiscoveryState!==void 0)throw new ta("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",y);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) \u2014 see docs/migration/upgrade-to-v2.md \xA7SEP-2352.")}else if(!ll(Y,y))throw new ta(Y,y)}v&&await e.saveDiscoveryState?.(v);let H=await gh(t,e,f),M=H&&f&&!e.validateResourceURL?f.resource:H;M&&await e.saveResourceUrl?.(mi(M));let W=fh({requestedScope:n,resourceMetadata:f,authServerMetadata:R,clientMetadata:e.clientMetadata}),T=await Promise.resolve(e.clientInformation(V)),g=ci(T,y,{canPersistStamp:e.saveClientInformation!==void 0});if(g===void 0&&T?.issuer&&e.saveClientInformation===void 0)throw new ta(T.issuer,y);if(g&&g.issuer===void 0&&(g={...g,issuer:y},await e.saveClientInformation?.(g,V)),!g){if(o!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let Y=R?.client_id_metadata_document_supported===!0,X=e.clientMetadataUrl;if(X&&!Sh(X))throw new xt(et.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${X}`);if(Y&&X)g={client_id:X,issuer:y},await e.saveClientInformation?.(g,V);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");g={...await Ph(S,{metadata:R,clientMetadata:h,scope:W,fetchFn:a}),issuer:y},await e.saveClientInformation(g,V)}}let j=!e.redirectUrl;if(o!==void 0||j){o!==void 0&&hi({iss:s,expectedIssuer:R?.issuer,issParameterSupported:di(R)});let Y=await Eh(e,S,{metadata:R,resource:M,authorizationCode:o,iss:s,scope:W,fetchFn:a});return await e.saveTokens({...Y,issuer:y},V),"AUTHORIZED"}let G=ci(await e.tokens(V),y);if(G&&G.issuer===void 0&&(G={...G,issuer:y},await e.saveTokens(G,V)),G?.refresh_token&&!u){let Y;try{Y=await Th(S,{metadata:R,clientInformation:g,refreshToken:G.refresh_token,resource:M,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:a})}catch(X){if(X instanceof cl)throw X;if(!(X instanceof xt)||X.code===et.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(X instanceof Error?X.message:String(X))}`);else throw X}if(Y)return await e.saveTokens({...Y,issuer:y},V),"AUTHORIZED"}let B=e.state?await e.state():void 0,{authorizationUrl:Z,codeVerifier:me}=await vh(S,{metadata:R,clientInformation:g,state:B,redirectUrl:e.redirectUrl,scope:W,resource:M});return await e.saveCodeVerifier(me),await e.redirectToAuthorization(Z),"REDIRECT"}function Sh(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function gh(e,t,o){let s=Xi(e);if(t.validateResourceURL)return await t.validateResourceURL(s,o?.resource);if(o){if(!Zi({requestedResource:s,configuredResource:o.resource}))throw new Error(`Protected resource ${o.resource} does not match expected ${s} (or origin)`);return new URL(o.resource)}}var _h=new Set(["bearer","dpop"]);function xs(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[o,s]=t.split(" ");if(!o||!_h.has(o.toLowerCase())||!s)return{};let n=Qn(e,"resource_metadata")||void 0,i;if(n)try{i=new URL(n)}catch{}let a=Qn(e,"scope")||void 0,c=Qn(e,"error")||void 0,u=Qn(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:a,error:c,errorDescription:u}}function Qn(e,t){let o=e.headers.get("WWW-Authenticate");if(!o)return null;let s=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),n=o.match(s);if(n){let i=n[1]||n[2];if(i)return i}return null}async function dl(e,t,o=fetch){let s=await yh(e,"oauth-protected-resource",o,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!s||s.status===404)throw await s?.text?.().catch(()=>{}),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!s.ok)throw await s.text?.().catch(()=>{}),new Error(`HTTP ${s.status} trying to load well-known OAuth protected resource metadata.`);return bs.parse(await s.json())}async function hl(e,t,o=fetch){let s=$s(o);try{return await s(e,{headers:t})}catch(n){if(!(n instanceof TypeError)||!Jc)throw n;if(t)try{return await s(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}function Rh(e,t="",o={}){return t.endsWith("/")&&(t=t.slice(0,-1)),o.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Qc(e,t,o=fetch){return await hl(e,{"MCP-Protocol-Version":t},o)}function zh(e,t){return e?t==="/"?!1:!e.ok&&e.status<500||e.status===502:!0}async function yh(e,t,o,s){let n=new URL(e),i=s?.protocolVersion??Zt,a;if(s?.metadataUrl)a=new URL(s.metadataUrl);else{let u=Rh(t,n.pathname);a=new URL(u,s?.metadataServerUrl??n),a.search=n.search}let c=await Qc(a,i,o);return!s?.metadataUrl&&zh(c,n.pathname)&&(c=await Qc(new URL(`/.well-known/${t}`,n),i,o)),c}function bh(e){let t=typeof e=="string"?new URL(e):e,o=t.pathname!=="/",s=[];if(!o)return s.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),s;let n=t.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),s.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"},{url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),s}async function ml(e,{fetchFn:t=fetch,protocolVersion:o=Zt,skipIssuerValidation:s=!1}={}){let n={"MCP-Protocol-Version":o,Accept:"application/json"},i=bh(e);for(let{url:a,type:c}of i){let u=await hl(a,n,t);if(!u)continue;if(!u.ok){if(await u.text?.().catch(()=>{}),u.status<500||u.status===502)continue;throw new Error(`HTTP ${u.status} trying to load ${c==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}let h=c==="oauth"?mo.parse(await u.json()):vs.parse(await u.json());if(!s){let d=typeof e=="string"?e:e.href;if(!(h.issuer===d||d.endsWith("/")&&h.issuer===d.slice(0,-1)))throw new ii("metadata",d,h.issuer)}return h}}async function pl(e,t){let o,s;try{o=await dl(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),o.authorization_servers&&o.authorization_servers.length>0&&(s=o.authorization_servers[0])}catch(i){if(i instanceof TypeError)throw i}s||(s=String(new URL("/",e)));let n=await ml(s,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:s,authorizationServerMetadata:n,resourceMetadata:o}}function mi(e){return typeof e=="string"?e:e.href}async function vh(e,{metadata:t,clientInformation:o,redirectUrl:s,scope:n,state:i,resource:a}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(oi))throw new Error(`Incompatible auth server: does not support response type ${oi}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(si))throw new Error(`Incompatible auth server: does not support code challenge method ${si}`)}else c=new URL("/authorize",e);let u=await Qa(),h=u.code_verifier,d=u.code_challenge;return c.searchParams.set("response_type",oi),c.searchParams.set("client_id",o.client_id),c.searchParams.set("code_challenge",d),c.searchParams.set("code_challenge_method",si),c.searchParams.set("redirect_uri",String(s)),i&&c.searchParams.set("state",i),n&&c.searchParams.set("scope",n),n?.split(" ").includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",mi(a)),{authorizationUrl:c,codeVerifier:h}}function wh(e,t,o){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(o)})}async function fl(e,{metadata:t,tokenRequestParams:o,clientInformation:s,addClientAuthentication:n,resource:i,dpop:a,fetchFn:c}){let u=hh(t?.token_endpoint??new URL("/token",e)),h=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});i&&o.set("resource",mi(i)),!n&&s&&ch(ih(s,t?.token_endpoint_auth_methods_supported??[]),s,h,o);let d=async()=>{let R=new Headers(h);return n&&await n(R,o,u,t),a&&R.set("DPoP",await a.buildProof({htm:"POST",htu:u})),$s(c??fetch)(u,{method:"POST",headers:R,body:o})},f=await d();if(a&&f.status===400&&(await f.clone().json().catch(()=>{}))?.error===et.UseDpopNonce&&(a.observeNonce(f,u),f=await d()),a?.observeNonce(f,u),!f.ok)throw await Xc(f);let S=await f.json();try{return ws.parse(ja(S))}catch(R){throw typeof S=="object"&&S!==null&&"error"in S?await Xc(JSON.stringify(S)):R}}async function Th(e,{metadata:t,clientInformation:o,refreshToken:s,resource:n,addClientAuthentication:i,dpop:a,fetchFn:c}){return{refresh_token:s,...await fl(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:s}),clientInformation:o,addClientAuthentication:i,resource:n,dpop:a,fetchFn:c})}}async function Eh(e,t,{metadata:o,resource:s,authorizationCode:n,iss:i,scope:a,fetchFn:c}={}){n!==void 0&&hi({iss:i,expectedIssuer:o?.issuer,issParameterSupported:di(o)});let u=o?.issuer??String(t),h=async()=>{let R=await e.clientInformation({issuer:u}),v=ci(R,u,{canPersistStamp:!1});if(R&&v===void 0)throw new ta(String(R.issuer),u);return v},d=await h(),f=a??e.clientMetadata.scope,S;if(e.prepareTokenRequest&&(S=await e.prepareTokenRequest(f)),!S){if(!n)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");S=wh(n,await e.codeVerifier(),e.redirectUrl)}return d??=await h(),fl(t,{metadata:o,tokenRequestParams:S,clientInformation:d,addClientAuthentication:e.addClientAuthentication,resource:s,dpop:await e.dpop?.(),fetchFn:c})}async function Ph(e,{metadata:t,clientMetadata:o,scope:s,fetchFn:n}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let a={...o,...s===void 0?{}:{scope:s}},c=await $s(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!c.ok)throw new eh({status:c.status,body:await c.text(),submittedMetadata:a});return Es.parse(ja(await c.json()))}var ea=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]),Ch=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(ni(e))}set(e,t){let o=ni(e),s=ea.has(e.method),n=!this._entries.has(o);if(!s&&n&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let a of this._entries.keys())if(!ea.has(a.slice(0,a.indexOf("\0")))){this._entries.delete(a),this._cappedSize--;break}}let i=++this._stamp;return this._entries.set(o,{...t,stamp:i}),n&&!s&&this._cappedSize++,i}delete(e){this._entries.delete(ni(e))&&!ea.has(e.method)&&this._cappedSize--}evict(e){let t=`${e}\0`,o=ea.has(e);for(let s of this._entries.keys())s.startsWith(t)&&(this._entries.delete(s),o||this._cappedSize--)}clear(){this._entries.clear(),this._cappedSize=0}};function ni(e){return`${e.method}\0${JSON.stringify([e.partition??"",e.params??""])}`}function ai(e,t){return t===void 0?e:`${e}\0${t}`}var qh=864e5,Ih=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity="";constructor(e,t,o=()=>{},s="",n=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=o,this._cachePartition=s,this._now=n}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e==="public"?"":this._cachePartition])}async _probe(e,t){let o={method:e,params:t??""},s=this._partitionFor("private"),n=await this._store.get({...o,partition:s});if(n!==void 0)return n;let i=this._partitionFor("public");if(i===s)return;let a=await this._store.get({...o,partition:i});return a?.scope==="public"?a:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,"")}async _deleteBoth(e,t){let o=this._partitionFor("private"),s=this._partitionFor("public");try{await this._store.delete({method:e,params:t,partition:o})}catch(n){this._reportError(n)}if(s!==o)try{await this._store.delete({method:e,params:t,partition:s})}catch(n){this._reportError(n)}}async evictKey(e,t){let o=ai(e,t),s=this._evictionGeneration.get(o);s!==void 0&&this._evictionGeneration.set(o,s+1),await this._deleteBoth(e,t)}captureGeneration(e,t){let o=ai(e,t),s=this._evictionGeneration.get(o)??0;return this._evictionGeneration.set(o,s),s}async write(e,t,o,s){if((this._evictionGeneration.get(ai(e,s?.params))??0)!==o)return;let n=s?.params??"",i=this._partitionFor("private"),a=this._partitionFor("public"),c=(s?.scope??"private")==="public"?a:i;try{await this._store.set({method:e,params:n,partition:c},{value:kh(t),expiresAt:s?.expiresAt,scope:s?.scope})}catch(u){this._reportError(u)}if(a!==i)try{await this._store.delete({method:e,params:n,partition:c===i?a:i})}catch(u){this._reportError(u)}}async read(e,t){let o=await this._probe(e,t);if(!(o?.expiresAt===void 0||!(o.expiresAt>this.now())))try{let s=JSON.parse(o.value);if(typeof s!="object"||s===null||Array.isArray(s))throw new TypeError("cached document is not an object");return{value:s}}catch(s){this._reportError(s),await this._deleteBoth(e,t??"");return}}resetForReconnect(){this._isUserSupplied||this._store.clear(),this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=""}async toolDefinition(e){let t=await this._probe("tools/list");if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let o=this._decodeListTools(t),s=new Map;if(o!==void 0)for(let n of o.tools)s.set(n.name,n);this._toolIndex={stamp:t.stamp,byName:s}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let o=await this._probe("tools/list");if(o===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==o.stamp){let s=this._decodeListTools(o)??{tools:[]},n=new Map;for(let i of s.tools){let a=t(i);a!==void 0&&n.set(i.name,a)}this._toolOutputValidatorIndex={stamp:o.stamp,byName:n}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every(o=>o!==null&&typeof o=="object"))throw new TypeError("cached tools/list document has a malformed tools array");return t}catch(t){this._reportError(t);return}}};function kh(e){let t;try{t=JSON.stringify(e)}catch(o){throw new TypeError(`cache value is not JSON-serializable: ${o instanceof Error?o.message:String(o)}`)}if(typeof t!="string")throw new TypeError("cache value is not JSON-serializable: it has no JSON representation");return t}var Sl=Symbol.for("mcp.authSeamEscape");function Oe(e){if(typeof e=="object"&&e!==null||typeof e=="function")try{Object.defineProperty(e,Sl,{value:!0,configurable:!0})}catch{}return e}function Oh(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&e[Sl]===!0}var $h=-32022,Mh=new Set([-32001,-32020,-32021]);function Nh(e,t){switch(e.kind){case"result":return xh(e.result,t);case"rpc-error":return gl(e,t);case"http-error":return Ah(e,t);case"network-error":return el(e.error,t);case"unusable-reply":return{kind:"error",error:new k(I.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${_l(e.error)})`,{cause:e.error},{cause:e.error})};case"auth-required":return{kind:"error",error:e.error};case"closed":return t.transportKind==="stdio"?{kind:"legacy"}:el(new Error("Connection closed during the version negotiation probe"),t);case"timeout":return t.transportKind==="stdio"?{kind:"legacy"}:{kind:"error",error:new k(I.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function xh(e,t){let o=Qe(Kn).validateResult("server/discover",e);if(!o.ok)return{kind:"legacy"};let s=o.value.supportedVersions,n=t.clientModernVersions.find(i=>s.includes(i));return n!==void 0?{kind:"modern",version:n,discover:o.value}:t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:new Wn({supported:[...s],requested:t.requestedVersion})}}function gl(e,t){let{code:o,message:s,data:n}=e;if(o===$h){let i=Lh(n);if(i===void 0)return{kind:"legacy"};let a=new Wn({supported:i,requested:Uh(n)??t.requestedVersion},s),c=Os(i),u=t.clientModernVersions.find(h=>c.includes(h));return u!==void 0?{kind:"corrective",version:u,error:a}:c.length>0?{kind:"error",error:a}:t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:a}}return Mh.has(o)?{kind:"legacy"}:{kind:"legacy"}}function Ah(e,t){if(e.status===401||e.status===403){let s=e.status===403;return{kind:"error",error:new Fe(s?I.ClientHttpForbidden:I.ClientHttpAuthentication,`Version negotiation failed: ${s?"the server denied access (HTTP 403)":"the server requires authorization (HTTP 401)"}`,{status:e.status,statusText:e.statusText,text:e.body})}}if(e.status>=500)return{kind:"error",error:new Fe(I.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};let o=Dh(e.body);return o!==void 0?gl(o,t):{kind:"legacy"}}function el(e,t){return t.environment==="browser"&&jh(e)?{kind:"legacy"}:{kind:"error",error:new k(I.EraNegotiationFailed,`Version negotiation probe failed: ${_l(e)}`,{cause:e},{cause:e})}}function jh(e){return e instanceof TypeError||e instanceof Error&&e.name==="TypeError"}function _l(e){return e instanceof Error?e.message:String(e)}function Lh(e){if(typeof e!="object"||e===null)return;let t=e.supported;if(!(!Array.isArray(t)||t.length===0||!t.every(o=>typeof o=="string")))return t}function Uh(e){if(typeof e!="object"||e===null)return;let t=e.requested;return typeof t=="string"?t:void 0}function Dh(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null)return;let o=t.error;if(typeof o!="object"||o===null)return;let{code:s,message:n,data:i}=o;if(typeof s=="number")return{code:s,message:typeof n=="string"?n:"",data:i}}var Vh="legacy";function Hh(e,t){let o=e?.mode??Vh;if(o==="legacy")return{kind:"legacy"};let s=e?.probe??{};if(typeof o=="object"){if(!tt(o.pin))throw new TypeError(`versionNegotiation: { pin: '${o.pin}' } is not a modern protocol revision \u2014 pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:"pin",version:o.pin,probe:s}}let n=t?Os(t):[];return{kind:"auto",modernVersions:n.length>0?n:[...La],fallbackAvailable:t?Ua(t).length>0:!0,probe:s}}function tl(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?"browser":"node"}function ol(e){return"stderr"in e&&"pid"in e?"stdio":"http"}var Fh=class Rl{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(t){this._transport=t,this._savedOnMessage=t.onmessage,this._savedOnError=t.onerror,this._savedOnClose=t.onclose}static async open(t){let o=new Rl(t);t.onmessage=s=>{let n=o._pending;if(n!==void 0&&(fo(s)||So(s))&&s.id===n.id){o._pending=void 0,fo(s)?n.resolve({kind:"response",result:s.result}):n.resolve({kind:"response",error:s.error});return}},t.onerror=s=>{o._savedOnError?.(s)},t.onclose=()=>{let s=o._pending;s!==void 0&&(o._pending=void 0,s.resolve({kind:"closed"})),o._closeDelivered=!0,o._savedOnClose?.()};try{await t.start()}catch(s){throw o.detach(),s}return o}async exchange(t,o){let s=`server-discover-probe-${++this._probeCounter}`;return new Promise(n=>{let i=!1,a=u=>{i||(i=!0,clearTimeout(c),this._pending?.id===s&&(this._pending=void 0),n(u))},c=setTimeout(()=>a({kind:"timeout"}),o);this._pending={id:s,resolve:a},this._transport.send(t(s)).catch(u=>a({kind:"send-error",error:u}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let t=this._savedOnClose,o=this._transport,s=!1,n=()=>{if(!s){s=!0;return}t()};o.onclose=n,ui.set(o,()=>{o.onclose===n&&(o.onclose=t)})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let t=this._transport,o=t.start,s=!0;t.start=async function(){if(s){s=!1,t.start=o;return}return o.call(t)}}},ui=new WeakMap;function sl(e){let t=ui.get(e);ui.delete(e),t?.()}function Jh(e,t,o,s){return{jsonrpc:"2.0",id:e,method:"server/discover",params:{_meta:Qe(t).outboundEnvelope({protocolVersion:t,clientInfo:o,clientCapabilities:s})}}}function Bh(e){return e instanceof k&&e.code===I.ClientHttpUnexpectedContent?!0:e instanceof Error&&e.name==="SyntaxError"}function Gh(e,t){switch(e.kind){case"response":return e.error===void 0?{kind:"result",result:e.result}:{kind:"rpc-error",...e.error};case"send-error":{let o=e.error;if(Oh(o)||o instanceof Be||o instanceof Error&&o.name==="UnauthorizedError")return{kind:"auth-required",error:o};if(o instanceof Fe){let s=o.data?.text;return{kind:"http-error",status:o.data.status,body:typeof s=="string"?s:void 0,statusText:o.data.statusText}}return Bh(o)?{kind:"unusable-reply",error:o}:{kind:"network-error",error:o}}case"closed":return{kind:"closed"};case"timeout":return{kind:"timeout",timeoutMs:t}}}async function zl(e,t){let o=e.probe.timeoutMs??t.defaultTimeoutMs,s=Math.max(0,e.probe.maxRetries??0),n=e.kind==="pin"?[e.version]:e.modernVersions,i=e.kind==="auto"&&e.fallbackAvailable,a=await Fh.open(t.transport),c=async()=>{let h=n[0],d=!1,f=s;for(;;){let S=await a.exchange(z=>Jh(z,h,t.clientInfo,t.capabilities),o);if(S.kind==="timeout"&&f>0){f--;continue}let R=Gh(S,o),v=Nh(R,{clientModernVersions:n,requestedVersion:h,fallbackAvailable:i,environment:t.environment,transportKind:t.transportKind});switch(v.kind){case"modern":return{era:"modern",version:v.version,discover:v.discover};case"corrective":if(d)throw v.error;d=!0,h=v.version;continue;case"legacy":{let z=R.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(e.kind==="pin")throw new k(I.EraNegotiationFailed,z===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${z} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new k(I.EraNegotiationFailed,z===void 0?"Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to":`Version negotiation failed: ${z} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(z!==void 0&&t.disposableProbe!==!0)throw new k(I.EraNegotiationFailed,`Version negotiation failed: ${z} (this transport probed in place \u2014 the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:"legacy"}}case"error":throw v.error}}},u;try{u=await c()}catch(h){throw a.detach(),h}return a.release(),u}function Wh(e){let t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,"_dispose"))return;let o=e._serverParams;return typeof o=="object"&&o!==null&&typeof o.command=="string"?o:void 0}async function Kh(e,t,o,s){let n=t.constructor,i=new n({...o,stderr:"ignore"}),a=t.close,c=!1,u,h=new Promise((f,S)=>{u=()=>S(rl())});t.close=async function(){return c=!0,u?.(),a.call(t)};let d;try{let f=zl(e,{...s,transport:i,transportKind:"stdio",disposableProbe:!0});f.catch(()=>{}),d=await Promise.race([f,h])}finally{await Yh(i),t.close=a}if(c)throw rl();return d}function rl(){return new k(I.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function Yh(e){try{let t=e._dispose;await(typeof t=="function"?t.call(e):e.close())}catch{}}function nl(e){let t=e._meta?.[Xe];return Oc.Implementation(t)?t:void 0}function oa(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){let o=t,s=e.properties;for(let n of Object.keys(s)){let i=s[n];o[n]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(o[n]=i.default),o[n]!==void 0&&oa(i,o[n])}}if(Array.isArray(e.anyOf))for(let o of e.anyOf)typeof o!="boolean"&&oa(o,t);if(Array.isArray(e.oneOf))for(let o of e.oneOf)typeof o!="boolean"&&oa(o,t)}}function Xh(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,o=e.url!==void 0;return{supportsFormMode:t||!t&&!o,supportsUrlMode:o}}function Zh(e){if(typeof e=="object"&&e!==null&&(e.kind==="legacy"&&!("supportedVersions"in e)&&!("discover"in e)||e.kind==="modern"&&Mt.safeParse(e.discover).success))return e;throw new k(I.EraNegotiationFailed,"connect({ prior }): unrecognized prior \u2014 expected { kind: 'modern', discover } or { kind: 'legacy' }")}var al={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},Qh=64,yl=class extends $c{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let e=new k(I.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(let t of this._listenState.values())t.settle({cause:"remote",error:e})}this._listenState.clear();for(let e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t),this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new Xa,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=Cc(t?.inputRequired),this._cache=new Ih(t?.responseCacheStore??new Ch,t?.responseCacheStore!==void 0,o=>this._reportStoreError(o),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??Qh,t?.listChanged&&(this._listChangedConfig=t.listChanged)}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&tt(this._negotiatedProtocolVersion)&&At(e))return"drop"}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){return this._inputRequiredDriverConfig.autoFulfill?Nc({getRequestHandler:o=>this._getRequestHandler(o),buildContext:o=>this.buildContext(o,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t):Promise.reject(new k(I.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance \u2014 pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:"input_required",method:t.request.method}))}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools","notifications/tools/list_changed",e.tools,async()=>(await this.listTools(void 0,{cacheMode:"refresh"})).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts","notifications/prompts/list_changed",e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources","notifications/resources/list_changed",e.resources,async()=>(await this.listResources(void 0,{cacheMode:"refresh"})).resources)}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Mc(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw new Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=e}_wrapHandler(e,t){return e==="elicitation/create"?async(o,s)=>{let n=Qe(this._negotiatedProtocolVersion),i=n.validateRequest("elicitation/create",o);if(!i.ok&&i.reason==="not-in-era"&&(i=n.validateInputRequest("elicitation/create",o)),!i.ok)throw new K(i.reason==="not-in-era"?D.InternalError:D.InvalidParams,i.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${i.message}`);let{params:a}=i.value;a.mode=a.mode??"form";let{supportsFormMode:c,supportsUrlMode:u}=Xh(this._capabilities.elicitation);if(a.mode==="form"&&!c)throw new K(D.InvalidParams,"Client does not support form-mode elicitation requests");if(a.mode==="url"&&!u)throw new K(D.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await t(o,s),d=n.validateResult("elicitation/create",h);if(!d.ok&&d.reason==="not-in-era"&&(d=n.validateInputResponse("elicitation/create",h)),!d.ok)throw new K(d.reason==="not-in-era"?D.InternalError:D.InvalidParams,d.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${d.message}`);let f=d.value,S=a.mode==="form"?a.requestedSchema:void 0;if(a.mode==="form"&&f.action==="accept"&&f.content&&S&&this._capabilities.elicitation?.form?.applyDefaults)try{oa(S,f.content)}catch{}return f}:e==="sampling/createMessage"?async(o,s)=>{let n=Qe(this._negotiatedProtocolVersion),i=n.validateRequest("sampling/createMessage",o);if(!i.ok&&i.reason==="not-in-era"&&(i=n.validateInputRequest("sampling/createMessage",o)),!i.ok)throw new K(i.reason==="not-in-era"?D.InternalError:D.InvalidParams,i.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${i.message}`);let{params:a}=i.value,c=await t(o,s),u=!!(a.tools||a.toolChoice),h=n.samplingResultVariant(u,c);if(!h.ok&&h.reason==="not-in-era"&&(h=n.validateInputResponse("sampling/createMessage",c)),!h.ok)throw new K(h.reason==="not-in-era"?D.InternalError:D.InvalidParams,h.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${h.message}`);return h.value}:t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new k(I.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,Zh(t.prior),t);let o=Hh(this._versionNegotiation,this._supportedProtocolVersionsOption);return o.kind!=="legacy"?this._connectNegotiated(e,o,t):this._connectPlainLegacy(e,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){let o=this._negotiatedProtocolVersion;o!==void 0&&e.setProtocolVersion?.(o);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let o=Ua(this._supportedProtocolVersions);try{let s=o[0];if(s===void 0)throw new k(I.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");let n=await this.request({method:"initialize",params:{protocolVersion:s,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!o.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=n.protocolVersion,this._listChangedConfig&&this._setupListChangedHandlers(this._listChangedConfig)}catch(s){throw this.close(),s}}async _connectNegotiated(e,t,o){if(e.sessionId!==void 0){await super.connect(e);let n=this._negotiatedProtocolVersion;n!==void 0&&e.setProtocolVersion&&e.setProtocolVersion(n);return}this._resetConnectionState();let s;try{let n=ol(e),i={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:tl(),defaultTimeoutMs:o?.timeout??Xn},a=n==="stdio"?Wh(e):void 0;s=a===void 0?await zl(t,{...i,transport:e,transportKind:n}):await Kh(t,e,a,i)}catch(n){throw await e.close().catch(()=>{}),sl(e),n}if(sl(e),await super.connect(e),s.era==="legacy"){await this._legacyHandshake(e,o);return}if(this._serverCapabilities=s.discover.capabilities,this._serverVersion=nl(s.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=s.discover.instructions,this._discoverResult=s.discover,this._negotiatedProtocolVersion=s.version,e.setProtocolVersion&&e.setProtocolVersion(s.version),this._listChangedConfig){let n=this._listChangedConfig,i=this._serverCapabilities,a={...n.tools&&i?.tools?.listChanged&&{tools:n.tools},...n.prompts&&i?.prompts?.listChanged&&{prompts:n.prompts},...n.resources&&i?.resources?.listChanged&&{resources:n.resources}},c=!0;try{this._setupListChangedHandlers(a)}catch(h){c=!1,this.onerror?.(h instanceof Error?h:new Error(String(h)))}let u=c?{...a.tools&&{toolsListChanged:!0},...a.prompts&&{promptsListChanged:!0},...a.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(u).length>0){let h=new AbortController,d=()=>h.abort(o?.signal?.reason);o?.signal?.aborted&&d(),o?.signal?.addEventListener("abort",d);try{this._autoOpenedSubscription=await this.listen(u,{timeout:o?.timeout,signal:h.signal})}catch(f){if(o?.signal?.aborted)throw await this.close().catch(()=>{}),f;this.onerror?.(f instanceof Error?f:new Error(String(f)))}finally{o?.signal?.removeEventListener("abort",d)}}}}async _connectFromPrior(e,t,o){if(t.kind==="legacy")return this._connectPlainLegacy(e,o);let s=t.discover;this._resetConnectionState();let n=this._supportedProtocolVersionsOption,i=(n&&Os(n).length>0?Os(n):La).find(a=>s.supportedVersions.includes(a));if(i===void 0)throw new k(I.EraNegotiationFailed,"connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.");if(await super.connect(e),this._discoverResult=s,this._serverCapabilities=s.capabilities,this._serverVersion=nl(s),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=s.instructions,this._negotiatedProtocolVersion=i,e.setProtocolVersion?.(i),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(a){this.onerror?.(a instanceof Error?a:new Error(String(a)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;return t!==void 0?`${t.name}@${t.version}`:e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return tt(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new k(I.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new k(I.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new k(I.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new k(I.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new k(I.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new k(I.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"initialize":break;case"server/discover":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new k(I.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new k(I.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new k(I.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new k(I.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},e)}async discover(e){let t=await this._requestWithSchema({method:"server/discover"},Mt,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:"completion/complete",params:e},t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:"prompts/list",params:e},t);let o=await this._serveFromCache("prompts/list",void 0,t);return o!==void 0?o:this._listAllPages("prompts/list",e,t,s=>s.prompts)}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"),{resources:[]};if(e?.cursor!==void 0)return this.request({method:"resources/list",params:e},t);let o=await this._serveFromCache("resources/list",void 0,t);return o!==void 0?o:this._listAllPages("resources/list",e,t,s=>s.resources)}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:"resources/templates/list",params:e},t);let o=await this._serveFromCache("resources/templates/list",void 0,t);return o!==void 0?o:this._listAllPages("resources/templates/list",e,t,s=>s.resourceTemplates)}async _listAllPages(e,t,o,s,n){let i=o?.cacheMode==="bypass",a=this._cache.captureGeneration(e),c=await this.request({method:e,...t&&{params:{...t}}},o),u=c.nextCursor,h=c,d=1;for(;u!==void 0;){if(this._listMaxPages!==0&&d>=this._listMaxPages)throw new k(I.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});let f=await this.request({method:e,params:{...t,cursor:u}},o);if(f.nextCursor===u&&JSON.stringify(s(f))===JSON.stringify(s(h)))break;s(c).push(...s(f)),h=f,u=f.nextCursor,d++}return delete c.nextCursor,n?.(c),i||await this._cache.write(e,c,a,this._freshness(c)),c}_freshness(e,t){let o=e,s=typeof o.ttlMs=="number"?o.ttlMs:this._defaultCacheTtlMs,n=o.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,s),qh),scope:n,params:t}}async _serveFromCache(e,t,o){if(o?.cacheMode==="bypass"||o?.cacheMode==="refresh")return;let s=await this._cache.read(e,t).catch(n=>{this._reportStoreError(n)});if(s!==void 0){if(o?.signal?.aborted){let n=o.signal.reason;throw n instanceof k?n:new k(I.RequestTimeout,String(n))}return s.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:new Error(String(e)))}_compileOutputValidator(e){if(e.outputSchema)try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(t){return{ok:!1,compileError:t}}}async _resolveXMcpHeaderScan(e,t){let o=t??await this._cache.toolDefinition(e);return o===void 0?void 0:Ga(o.inputSchema)}async readResource(e,t){let o=await this._serveFromCache("resources/read",e.uri,t);if(o!==void 0)return o;let s=this._cache.captureGeneration("resources/read",e.uri),n=await this.request({method:"resources/read",params:e},t);if(t?.cacheMode!=="bypass"){let i=this._freshness(n,e.uri);i.expiresAt>this._cache.now()?await this._cache.write("resources/read",n,s,i):t?.cacheMode==="refresh"&&await this._cache.evictKey("resources/read",e.uri)}return n}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},t)}async listen(e,t){if(this.transport===void 0)throw new k(I.NotConnected,"Not connected");let o=this._negotiatedProtocolVersion;if(o===void 0||!tt(o))throw new k(I.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${o??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:o});if(t?.signal?.aborted){let M=t.signal.reason;throw M instanceof k?M:new k(I.RequestTimeout,String(M))}let s=new AbortController,n=`listen:${this._nextListenId++}`,i="opening",a,c,u,h,d=new Promise((M,W)=>{u=M,h=W}),f,S=new Promise(M=>{f=M}),R=M=>{if(i==="closed")return;let W=i==="opening";if(a!==void 0&&(clearTimeout(a),a=void 0),"ack"in M){i="open",u(M.ack);return}i="closed",c!==void 0&&t?.signal?.removeEventListener("abort",c),this._listenState.delete(n),s.abort(),f(M.cause),W&&h(M.error??new k(I.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},v=async()=>{s.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:n}}).catch(()=>{})},z=async()=>{i!=="closed"&&(R({cause:"local"}),await v())};this._listenState.set(n,{settle:R});let y=t?.timeout??Xn;if(a=setTimeout(()=>{R({cause:"remote",error:new k(I.RequestTimeout,"subscriptions/listen ack timed out",{timeout:y})}),v().catch(()=>{})},y),t?.signal){let M=t.signal;c=()=>{if(i==="closed")return;let W=M.reason;R({cause:"local",error:W instanceof Error?W:new Error(String(W??"Aborted"))}),v().catch(()=>{})},M.addEventListener("abort",c,{once:!0})}let V={jsonrpc:"2.0",id:n,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}},H=M=>{R({cause:"remote",error:M instanceof Error?M:new Error(String(M))})};try{this.transport.send(V,{requestSignal:s.signal,onRequestStreamEnd:()=>R({cause:"remote",error:new Error("subscriptions/listen: stream ended")})}).catch(H)}catch(M){H(M)}return{honoredFilter:await d,close:z,closed:S}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let o=Object.hasOwn(al,e.method)?al[e.method]:void 0;if(e.method==="notifications/resources/updated"){let s=e.params?.uri;typeof s=="string"&&this._cache.evictKey("resources/read",s)}else if(o!==void 0)for(let s of o)this._cache.evict(s);if(e.method==="notifications/subscriptions/acknowledged"){let s=e.params?._meta?.[Bo],n=typeof s=="string"?this._listenState.get(s):void 0;if(n!==void 0){let i=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);n.settle({ack:i.ok?i.value.params.notifications:{}});return}}if(e.method==="notifications/cancelled"){let s=e.params?.requestId,n=typeof s=="string"?this._listenState.get(s):void 0;if(n!==void 0){n.settle({cause:"remote",error:new Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,o=typeof t=="string"?this._listenState.get(t):void 0;if(o!==void 0){So(e)?o.settle({cause:"remote",error:K.fromError(e.error.code,e.error.message,e.error.data)}):o.settle({cause:"graceful",error:new k(I.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new k(I.ConnectionClosed,"Connection closed");for(let t of this._listenState.values())t.settle({cause:"remote",error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let o=this.getProtocolEra()==="modern"&&tl()!=="browser",s=async()=>{if(!o)return t;let u;try{u=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(d){this._reportStoreError(d)}if(!u?.valid||u.declarations.length===0)return t;let h=Tc(u.declarations,e.arguments);return Object.keys(h).length===0?t:{...t,headers:{...t?.headers,...h}}},n=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,u=>this._compileOutputValidator(u)).catch(u=>{this._reportStoreError(u)}):this._compileOutputValidator(t.toolDefinition),i=()=>{if(n===void 0||n.ok)return;let u=n.compileError,h=(u instanceof Error?u.message:String(u)).slice(0,200);throw new K(D.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${h}`)};i();let a;try{a=await this.request({method:"tools/call",params:e},await s())}catch(u){let h=u instanceof K&&u.code===po;if(!o||!h||t?.toolDefinition!==void 0)throw u;let d={signal:t?.signal,timeout:t?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,d).catch(f=>this._reportStoreError(f)),n=await this._cache.outputValidator(e.name,f=>this._compileOutputValidator(f)).catch(f=>{this._reportStoreError(f)}),i(),a=await this.request({method:"tools/call",params:e},await s())}let c=n!==void 0&&n.ok?n.validator:void 0;if(c){if(a.structuredContent===void 0&&!a.isError)throw new K(D.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(a.structuredContent!==void 0&&!a.isError)try{let u=c(a.structuredContent);if(!u.valid)throw new K(D.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)}catch(u){throw u instanceof K?u:new K(D.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)}}return a}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(e?.cursor!==void 0){let s=await this.request({method:"tools/list",params:e},t);return this._excludeInvalidXMcpHeaderTools(s),s}let o=await this._serveFromCache("tools/list",void 0,t);return o!==void 0?o:this._listAllPages("tools/list",e,t,s=>s.tools,s=>this._excludeInvalidXMcpHeaderTools(s))}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!=="modern"||!this.transport||ol(this.transport)==="stdio")return;let t=e.tools.filter(o=>{let s=Ga(o.inputSchema);return s.valid?!0:(console.warn(`[mcp-sdk] excluding tool '${o.name}' from tools/list: invalid x-mcp-header declaration \u2014 ${s.reason}`),!1)});t.length!==e.tools.length&&(e.tools=t)}_setupListChangedHandler(e,t,o,s){let n=Yn(ms,o);if(!n.success)throw new Error(`Invalid ${e} listChanged options: ${n.error.message}`);if(typeof o.onChanged!="function")throw new TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:a}=n.data,{onChanged:c}=o,u=async()=>{if(!i){c(null,null);return}try{c(null,await s())}catch(d){c(d instanceof Error?d:new Error(String(d)),null)}},h=()=>{if(a){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let f=setTimeout(u,a);this._listChangedDebounceTimers.set(e,f)}else u()};this.setNotificationHandler(t,h)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function em(e){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(e)}function tm(e){if(e.status!==401)return!1;let t=e.headers.get("www-authenticate")??"";return em(t)&&/use_dpop_nonce/i.test(t)}var om=(e,t)=>o=>{let s=typeof e=="function"?e:()=>e;return async(n,i)=>{let a=(i?.method??"GET").toUpperCase(),c=new URL(n.toString()),u=await s();if(!u)return o(n,i);let h=async()=>{let f=await t();if(!f)return o(n,i);let S=new Headers(i?.headers),R=await u.buildProof({htm:a,htu:c,accessToken:f});return S.set("Authorization",`DPoP ${f}`),S.set("DPoP",R),o(n,{...i,headers:S})},d=await h();return tm(d)&&d.headers.has("dpop-nonce")&&(u.observeNonce(d,c),await d.text?.().catch(()=>{}),d=await h()),u.observeNonce(d,c),d}},sm=e=>om(async()=>{try{return await e.dpop?.()}catch(t){throw Oe(t)}},async()=>{let t;try{t=await e.tokens()}catch(o){throw Oe(o)}return t?.token_type?.toLowerCase()==="dpop"?t.access_token:void 0});var ap=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return Pe(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Pe(this,e)}constructor(e,t,o){super(`SSE error: ${t}`),this.code=e,this.event=o,Nt(this,new.target)}};var rm=1,nm={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},am=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function il(e,t){if(typeof AbortSignal.any=="function")return AbortSignal.any([e,t]);let o=new AbortController;if(e.aborted)return o.abort(e.reason),o.signal;if(t.aborted)return o.abort(t.reason),o.signal;let s=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",i)};function n(){s(),o.abort(e.reason)}function i(){s(),o.abort(t.reason)}return e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",i,{once:!0}),o.signal}var bl=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_redirectPolicy;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,this._fetch=t?.fetch,th(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=sh(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation}),t.authProvider.dpop&&(this._fetch=sm(t.authProvider)(t.fetch??fetch))):this._authProvider=t?.authProvider,this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=Ac(t?.fetch,t?.requestInit),this._redirectPolicy==="follow"&&(this._fetchWithInit=Uc(this._fetchWithInit)),this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??nm,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??rm)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(o){throw Oe(o)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope==="throw")throw new Yc({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new Yc({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new Fe(I.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??"Forbidden",text:e.text});e.resourceMetadataUrl&&(this._resourceMetadataUrl=e.resourceMetadataUrl);let o=await this._oauthProvider.tokens(),s=ti(this._scope,o?.scope,e.scope);this._scope=s;let n=rh(s,o?.scope);return li(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:s,forceReauthorization:n,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(e){return this._redirectPolicy==="follow"?e:$s(e)}_unfollowedRedirect(e,t){let o=this._redirectPolicy==="follow"?void 0:Dc(e,t);return o&&`${o} (redirectPolicy: 'same-origin')`}async _commonHeaders(){let e=new Headers(this._requestInit?.headers||void 0),t;try{t=await this._authProvider?.token()}catch(o){throw Oe(o)}return t&&e.set("Authorization",`Bearer ${t}`),this._sessionId&&e.set("mcp-session-id",this._sessionId),this._protocolVersion&&e.set("mcp-protocol-version",this._protocolVersion),e}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!At(t))return;let o=t.params?._meta?.[Ye];if(typeof o!="string")return;e.set("mcp-protocol-version",o),e.set("mcp-method",t.method);let s=Ec(t.method,t.params);s?.value!==void 0&&e.set("mcp-name",Wa(s.value))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!At(e))return!1;let t=e.params?._meta?.[Ye];return typeof t=="string"&&tt(t)}async _startOrAuthSse(e,t=!1,o=0){let{resumptionToken:s,requestSignal:n}=e,i=()=>this._abortController?.signal.aborted===!0||n?.aborted===!0;try{let a=await this._commonHeaders(),c=[...a.get("accept")?.split(",").map(f=>f.trim().toLowerCase())??[],"text/event-stream"];a.set("accept",[...new Set(c)].join(", ")),s&&a.set("last-event-id",s);let u=this._abortController?.signal,h=n!==void 0&&u!==void 0?il(u,n):n??u,d=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:a,signal:h});if(!d.ok){if(d.status===401&&this._authProvider){if(d.headers.has("www-authenticate")){let{resourceMetadataUrl:S,scope:R}=xs(d);this._resourceMetadataUrl=S,this._scope=ti(this._scope,R)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:d,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(S){throw Oe(S)}return await d.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,o)}throw await d.text?.().catch(()=>{}),Oe(t?new Fe(I.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:d.statusText}):new Be)}if(d.status===403){let{resourceMetadataUrl:S,scope:R,error:v,errorDescription:z}=xs(d);if(v==="insufficient_scope"){let y=await d.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:R,resourceMetadataUrl:S,errorDescription:z,statusText:d.statusText,text:y},o)!=="AUTHORIZED")throw Oe(new Be);return this._startOrAuthSse(e,t,o+1)}}if(await d.text?.().catch(()=>{}),d.status===405){e.onRequestStreamEnd?.();return}let f=this._unfollowedRedirect(this._url,d)??d.statusText;throw new Fe(I.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${f}`,{status:d.status,statusText:d.statusText})}this._handleSseStream(d.body,e,!0)}catch(a){throw i()||this.onerror?.(a),a}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,o=this._reconnectionOptions.reconnectionDelayGrowFactor,s=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(o,e),s)}_scheduleReconnection(e,t=0){let o=this._reconnectionOptions.maxRetries;if(t>=o){this.onerror?.(new Error(`Maximum reconnection attempts (${o}) exceeded.`)),e.onRequestStreamEnd?.();return}let s=this._getNextReconnectionDelay(t),n=()=>{this._cancelReconnection=void 0,!(this._abortController?.signal.aborted||e.requestSignal?.aborted)&&this._startOrAuthSse(e).catch(i=>{if(!(this._abortController?.signal.aborted||e.requestSignal?.aborted)){this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`));try{this._scheduleReconnection(e,t+1)}catch(a){this.onerror?.(a instanceof Error?a:new Error(String(a)))}}})};if(this._reconnectionScheduler){let i=this._reconnectionScheduler(n,s,t);this._cancelReconnection=typeof i=="function"?i:void 0}else{let i=setTimeout(n,s);this._cancelReconnection=()=>clearTimeout(i)}}_handleSseStream(e,t,o){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:s,replayMessageId:n,requestSignal:i,onRequestStreamEnd:a}=t,c=()=>this._abortController?.signal.aborted===!0||i?.aborted===!0,u,h=!1,d=!1;(async()=>{try{let S=e.pipeThrough(new TextDecoderStream).pipeThrough(new Zn({onRetry:R=>{this._serverRetryMs=R}})).getReader();for(;;){let{value:R,done:v}=await S.read();if(v)break;if(R.id&&(u=R.id,h=!0,s?.(R.id)),!!R.data&&(!R.event||R.event==="message"))try{let z=lt.parse(JSON.parse(R.data));(fo(z)||So(z))&&(d=!0,n!==void 0&&(z.id=n)),this.onmessage?.(z)}catch(z){this.onerror?.(z)}}(o||h)&&!d&&this._abortController&&!c()?this._scheduleReconnection({resumptionToken:u,onresumptiontoken:s,replayMessageId:n,requestSignal:i,onRequestStreamEnd:a},0):c()||a?.()}catch(S){if(c())return;if(this.onerror?.(new Error(`SSE stream disconnected: ${S}`)),(o||h)&&!d&&this._abortController&&!c())try{this._scheduleReconnection({resumptionToken:u,onresumptiontoken:s,replayMessageId:n,requestSignal:i,onRequestStreamEnd:a},0)}catch(R){this.onerror?.(new Error(`Failed to reconnect: ${R instanceof Error?R.message:String(R)}`)),a?.()}else a?.()}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new Be("finishAuth requires an OAuthClientProvider");let{authorizationCode:o,iss:s}=await nh(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await li(this._oauthProvider,{serverUrl:this._url,authorizationCode:o,iss:s,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new Be("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,o,s=0){try{let{resumptionToken:n,onresumptiontoken:i}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:At(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch(y=>this.onerror?.(y));return}let a=await this._commonHeaders();this._applyBodyDerivedHeaders(a,e);let c=Array.isArray(e)?e.some(y=>Ba(y)):Ba(e);if(c&&a.delete("mcp-session-id"),t?.headers!==void 0)for(let[y,V]of Object.entries(t.headers))am.has(y.toLowerCase())||a.set(y,V);a.set("content-type","application/json");let u=[...a.get("accept")?.split(",").map(y=>y.trim().toLowerCase())??[],"application/json","text/event-stream"];a.set("accept",[...new Set(u)].join(", "));let h=this._abortController?.signal,d=t?.requestSignal!==void 0&&h!==void 0?il(h,t.requestSignal):t?.requestSignal??h,f={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:d},S=await this._redirects(this._fetch??fetch)(this._url,f);if(c&&S.ok&&(this._sessionId=S.headers.get("mcp-session-id")||void 0),!S.ok){if(S.status===401&&this._authProvider){if(S.headers.has("www-authenticate")){let{resourceMetadataUrl:H,scope:M}=xs(S);this._resourceMetadataUrl=H,this._scope=ti(this._scope,M)}if(this._authProvider.onUnauthorized&&!o){try{await this._authProvider.onUnauthorized({response:S,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(H){throw Oe(H)}return await S.text?.().catch(()=>{}),this._send(e,t,!0,s)}throw await S.text?.().catch(()=>{}),Oe(o?new Fe(I.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:S.statusText}):new Be)}let y=await S.text?.().catch(()=>null);if(S.status===403){let{resourceMetadataUrl:H,scope:M,error:W,errorDescription:T}=xs(S);if(W==="insufficient_scope"){if(await this._stepUpAuthorize({scope:M,resourceMetadataUrl:H,errorDescription:T,statusText:S.statusText,text:y},s)!=="AUTHORIZED")throw Oe(new Be);return this._send(e,t,o,s+1)}}if(S.status===400&&typeof y=="string"&&this._isModernEnvelopedRequest(e))try{let H=lt.parse(JSON.parse(y)),M=(Array.isArray(e)?e:[e]).filter(W=>At(W));if(So(H)&&M.some(W=>W.id===H.id)){this.onmessage?.(H);return}}catch{}let V=this._unfollowedRedirect(this._url,S)??y;throw new Fe(I.ClientHttpNotImplemented,`Error POSTing to endpoint: ${V}`,{status:S.status,statusText:S.statusText,text:y})}if(S.status===202){await S.text?.().catch(()=>{}),bc(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(y=>this.onerror?.(y));return}let R=(Array.isArray(e)?e:[e]).some(y=>"method"in y&&"id"in y&&y.id!==void 0),v=S.headers.get("content-type"),z=xc(v);if(R)if(z==="text/event-stream")this._handleSseStream(S.body,{onresumptiontoken:i,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(z==="application/json"){let y=await S.json(),V=Array.isArray(y)?y.map(H=>lt.parse(H)):[lt.parse(y)];for(let H of V)this.onmessage?.(H)}else throw await S.text?.().catch(()=>{}),new k(I.ClientHttpUnexpectedContent,`Unexpected content type: ${v}`,{contentType:v});else await S.text?.().catch(()=>{})}catch(n){throw t?.requestSignal?.aborted!==!0&&this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},o=await this._redirects(this._fetch??fetch)(this._url,t);if(await o.text?.().catch(()=>{}),!o.ok&&o.status!==405)throw new Fe(I.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,o)??o.statusText}`,{status:o.status,statusText:o.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};var vl=class{constructor(t){Object.assign(this,t)}destroy(){this.close()}async getTools(){let t=await this._getClient();try{let o=await this._getToolDefinitions(t),s=this.allowedTools;if(s){let i=new Set(o.map(({name:c})=>c)),a=s.filter(c=>!i.has(c));if(a.length>0)throw new Error(`MCP server did not advertise the following allowed tools: ${a.join(", ")}`)}let n=s?new Set(s):void 0;return o.filter(({name:i})=>!n||n.has(i)).map(i=>this._createTool(i))}finally{await this._closeConnection()}}async close(){this._toolDefinitions=void 0,await this._closeConnection()}_createTool(t){return new yi({description:t.description??t.title??t.name,func:async(o,s,n)=>await this._invoke(t.name,o,n),name:t.name,returnDirect:this.resultModes?.[t.name]==="terminal",schema:t.inputSchema})}async _invoke(t,o,s){let n=await this._getClient();try{let i=await n.callTool({arguments:o,name:t},s?.signal?{requestSignal:s.signal}:void 0);if("toolResult"in i)return JSON.stringify(i.toolResult);let a=i.content.map(c=>c.type==="text"?c.text:JSON.stringify(c)).join(`
15
+ `);if(i.isError)throw new Error(a);return a}finally{await this._closeConnection()}}async _listTools(t){let o=[],s;do{let n=await t.listTools(s?{cursor:s}:void 0);o.push(...n.tools),s=n.nextCursor}while(s);return o}async _getToolDefinitions(t){return this._toolDefinitions??=this._listTools(t).catch(o=>{throw this._toolDefinitions=void 0,o}),await this._toolDefinitions}async _getClient(){if(this._client)return this._client;this._connection??=this._connect();try{return await this._connection}catch(t){throw this._connection=void 0,t}}async _closeConnection(){let t=this._transport;this._client=void 0,this._connection=void 0,this._transport=void 0,t&&await t.close()}async _connect(){let t=new yl({name:"@arcgis/ai-components",version:"5.2"},{versionNegotiation:{mode:"auto"}}),o=new bl(new URL(this.serverUrl),{requestInit:{headers:this.headers}});this._transport=o;try{return await t.connect(o),this._client=t,t}catch(s){throw this._transport=void 0,await o.close(),s instanceof TypeError?new Error("Could not connect to the MCP server. Check the URL, network connection, and server's CORS settings. See the browser console for details.",{cause:s}):s}}};export{vl as MCPToolProvider};
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
+ import{Fa as c}from"../../A4ZVCRVF.js";import"../../N2GN5WOI.js";import"../../272R36XK.js";import"../../5PV2GUZW.js";function h(s){return s instanceof Error&&/^Failed to parse (?:input|arguments)/u.test(s.message)}var u=class{constructor(t){this._abortController=new AbortController,Object.assign(this,t)}destroy(){this._abortController.abort()}async getTools(){let t=this._abortController.signal;t.throwIfAborted();let o=typeof document>"u"?void 0:document.modelContext;if(typeof o?.getTools!="function"||typeof o.executeTool!="function")throw new Error("WebMCP tools are unavailable because WebMCP is unsupported or disabled on this page.");let n=await o.getTools();if(t.throwIfAborted(),this.allowedTools){let r=new Set(n.map(({name:e})=>e)),a=this.allowedTools.filter(e=>!r.has(e));if(a.length>0)throw new Error(`WebMCP did not expose the following allowed tools: ${a.join(", ")}`)}let i=this.allowedTools?new Set(this.allowedTools):void 0;return n.filter(({name:r})=>!i||i.has(r)).map(r=>this._createTool(r,o))}_createTool(t,o){return new c({name:t.name,description:t.description,func:async(n,i,r)=>{let a=r?.signal?AbortSignal.any([this._abortController.signal,r.signal]):this._abortController.signal;a.throwIfAborted();let e;try{e=await o.executeTool(t,JSON.stringify(n),{signal:a})}catch(l){if(!h(l)||!n||typeof n!="object")throw l;e=await o.executeTool(t,n,{signal:a})}return typeof e=="string"?e:JSON.stringify(e)??String(e)},returnDirect:this.resultModes?.[t.name]==="terminal",schema:this._parseInputSchema(t)})}_parseInputSchema(t){if(!t.inputSchema)return{properties:{},type:"object"};let o=t.inputSchema;if(typeof o=="string"&&(o=JSON.parse(o)),typeof o!="object"||o===null||Array.isArray(o))throw new TypeError(`WebMCP tool "${t.name}" has an invalid input schema.`);return o}};export{u as WebMCPToolProvider};