@zuplo/cli 7.6.9 → 7.7.0

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 (220) hide show
  1. package/node_modules/@inquirer/checkbox/package.json +3 -3
  2. package/node_modules/@inquirer/confirm/dist/index.js +1 -1
  3. package/node_modules/@inquirer/confirm/package.json +3 -3
  4. package/node_modules/@inquirer/core/dist/lib/create-prompt.js +66 -47
  5. package/node_modules/@inquirer/core/package.json +2 -2
  6. package/node_modules/@inquirer/editor/package.json +3 -3
  7. package/node_modules/@inquirer/expand/package.json +3 -3
  8. package/node_modules/@inquirer/input/package.json +3 -3
  9. package/node_modules/@inquirer/number/package.json +3 -3
  10. package/node_modules/@inquirer/password/package.json +3 -3
  11. package/node_modules/@inquirer/rawlist/package.json +3 -3
  12. package/node_modules/@inquirer/search/package.json +3 -3
  13. package/node_modules/@inquirer/select/package.json +3 -3
  14. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/index.d.ts +1 -2
  15. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jwe/compact/decrypt.d.ts +7 -11
  16. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jwe/compact/encrypt.d.ts +13 -16
  17. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jwe/flattened/decrypt.d.ts +7 -11
  18. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jwe/flattened/encrypt.d.ts +16 -19
  19. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jwe/general/decrypt.d.ts +10 -16
  20. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jwe/general/encrypt.d.ts +18 -21
  21. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jwk/embedded.d.ts +3 -1
  22. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jwk/thumbprint.d.ts +4 -6
  23. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jwks/local.d.ts +5 -4
  24. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jwks/remote.d.ts +20 -21
  25. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jws/compact/sign.d.ts +4 -4
  26. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jws/compact/verify.d.ts +8 -11
  27. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jws/flattened/sign.d.ts +5 -5
  28. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jws/flattened/verify.d.ts +8 -11
  29. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jws/general/sign.d.ts +10 -14
  30. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jws/general/verify.d.ts +11 -17
  31. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jwt/decrypt.d.ts +14 -11
  32. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jwt/encrypt.d.ts +24 -22
  33. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jwt/sign.d.ts +3 -7
  34. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jwt/unsecured.d.ts +2 -6
  35. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/jwt/verify.d.ts +13 -6
  36. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/key/export.d.ts +6 -6
  37. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/key/generate_key_pair.d.ts +9 -14
  38. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/key/generate_secret.d.ts +10 -10
  39. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/key/import.d.ts +19 -18
  40. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/types.d.ts +152 -247
  41. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/util/base64url.d.ts +7 -7
  42. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/util/decode_jwt.d.ts +6 -1
  43. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/util/decode_protected_header.d.ts +4 -3
  44. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/types/util/errors.d.ts +29 -40
  45. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwe/compact/decrypt.js +1 -2
  46. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwe/compact/encrypt.js +9 -26
  47. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js +3 -3
  48. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js +11 -30
  49. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwe/general/decrypt.js +6 -6
  50. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwe/general/encrypt.js +33 -57
  51. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwk/embedded.js +3 -4
  52. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwk/thumbprint.js +3 -6
  53. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwks/local.js +16 -10
  54. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwks/remote.js +2 -2
  55. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jws/compact/sign.js +2 -4
  56. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jws/compact/verify.js +2 -2
  57. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jws/flattened/sign.js +8 -15
  58. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jws/flattened/verify.js +4 -14
  59. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jws/general/sign.js +4 -11
  60. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jws/general/verify.js +5 -7
  61. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwt/decrypt.js +2 -3
  62. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwt/encrypt.js +11 -25
  63. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwt/sign.js +1 -1
  64. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwt/unsecured.js +1 -2
  65. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwt/verify.js +4 -4
  66. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/key/export.js +12 -16
  67. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/key/generate_key_pair.js +4 -13
  68. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/key/generate_secret.js +1 -1
  69. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/key/import.js +5 -9
  70. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/asn1.js +2 -4
  71. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/buffer_utils.js +35 -0
  72. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/content_encryption.js +21 -29
  73. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/deflate.js +9 -19
  74. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/jwe_algorithms.js +0 -4
  75. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/jwe_decrypt.js +21 -54
  76. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/jwe_encrypt.js +26 -59
  77. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/jws_sign.js +29 -43
  78. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/jws_verify.js +37 -45
  79. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/jwt_claims_set.js +1 -1
  80. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/key.js +119 -59
  81. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/key_management.js +45 -80
  82. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/{options.js → validate.js} +64 -3
  83. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/util/base64url.js +5 -19
  84. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/util/decode_jwt.js +1 -1
  85. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/util/decode_protected_header.js +1 -1
  86. package/node_modules/@modelcontextprotocol/client/node_modules/jose/package.json +1 -1
  87. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/index.d.ts +1 -2
  88. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jwe/compact/decrypt.d.ts +7 -11
  89. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jwe/compact/encrypt.d.ts +13 -16
  90. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jwe/flattened/decrypt.d.ts +7 -11
  91. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jwe/flattened/encrypt.d.ts +16 -19
  92. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jwe/general/decrypt.d.ts +10 -16
  93. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jwe/general/encrypt.d.ts +18 -21
  94. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jwk/embedded.d.ts +3 -1
  95. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jwk/thumbprint.d.ts +4 -6
  96. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jwks/local.d.ts +5 -4
  97. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jwks/remote.d.ts +20 -21
  98. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jws/compact/sign.d.ts +4 -4
  99. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jws/compact/verify.d.ts +8 -11
  100. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jws/flattened/sign.d.ts +5 -5
  101. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jws/flattened/verify.d.ts +8 -11
  102. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jws/general/sign.d.ts +10 -14
  103. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jws/general/verify.d.ts +11 -17
  104. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jwt/decrypt.d.ts +14 -11
  105. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jwt/encrypt.d.ts +24 -22
  106. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jwt/sign.d.ts +3 -7
  107. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jwt/unsecured.d.ts +2 -6
  108. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/jwt/verify.d.ts +13 -6
  109. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/key/export.d.ts +6 -6
  110. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/key/generate_key_pair.d.ts +9 -14
  111. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/key/generate_secret.d.ts +10 -10
  112. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/key/import.d.ts +19 -18
  113. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/types.d.ts +152 -247
  114. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/util/base64url.d.ts +7 -7
  115. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/util/decode_jwt.d.ts +6 -1
  116. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/util/decode_protected_header.d.ts +4 -3
  117. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/types/util/errors.d.ts +29 -40
  118. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwe/compact/decrypt.js +1 -2
  119. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwe/compact/encrypt.js +9 -26
  120. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js +3 -3
  121. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js +11 -30
  122. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwe/general/decrypt.js +6 -6
  123. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwe/general/encrypt.js +33 -57
  124. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwk/embedded.js +3 -4
  125. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwk/thumbprint.js +3 -6
  126. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwks/local.js +16 -10
  127. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwks/remote.js +2 -2
  128. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jws/compact/sign.js +2 -4
  129. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jws/compact/verify.js +2 -2
  130. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jws/flattened/sign.js +8 -15
  131. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jws/flattened/verify.js +4 -14
  132. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jws/general/sign.js +4 -11
  133. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jws/general/verify.js +5 -7
  134. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwt/decrypt.js +2 -3
  135. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwt/encrypt.js +11 -25
  136. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwt/sign.js +1 -1
  137. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwt/unsecured.js +1 -2
  138. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwt/verify.js +4 -4
  139. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/key/export.js +12 -16
  140. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/key/generate_key_pair.js +4 -13
  141. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/key/generate_secret.js +1 -1
  142. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/key/import.js +5 -9
  143. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/asn1.js +2 -4
  144. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/buffer_utils.js +35 -0
  145. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/content_encryption.js +21 -29
  146. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/deflate.js +9 -19
  147. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/jwe_algorithms.js +0 -4
  148. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/jwe_decrypt.js +21 -54
  149. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/jwe_encrypt.js +26 -59
  150. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/jws_sign.js +29 -43
  151. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/jws_verify.js +37 -45
  152. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/jwt_claims_set.js +1 -1
  153. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/key.js +119 -59
  154. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/key_management.js +45 -80
  155. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/{options.js → validate.js} +64 -3
  156. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/util/base64url.js +5 -19
  157. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/util/decode_jwt.js +1 -1
  158. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/util/decode_protected_header.js +1 -1
  159. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/package.json +1 -1
  160. package/node_modules/@posthog/core/dist/posthog-core.d.ts +14 -0
  161. package/node_modules/@posthog/core/dist/posthog-core.d.ts.map +1 -1
  162. package/node_modules/@posthog/core/dist/types.d.ts +1 -0
  163. package/node_modules/@posthog/core/dist/types.d.ts.map +1 -1
  164. package/node_modules/@posthog/core/dist/utils/index.d.ts +1 -0
  165. package/node_modules/@posthog/core/dist/utils/index.d.ts.map +1 -1
  166. package/node_modules/@posthog/core/dist/utils/index.js +26 -0
  167. package/node_modules/@posthog/core/dist/utils/index.mjs +1 -0
  168. package/node_modules/@posthog/core/dist/utils/webview-app-utils.d.ts +12 -0
  169. package/node_modules/@posthog/core/dist/utils/webview-app-utils.d.ts.map +1 -0
  170. package/node_modules/@posthog/core/dist/utils/webview-app-utils.js +132 -0
  171. package/node_modules/@posthog/core/dist/utils/webview-app-utils.mjs +94 -0
  172. package/node_modules/@posthog/core/package.json +2 -2
  173. package/node_modules/@posthog/core/src/featureFlagLocalEvaluation.ts +1 -1
  174. package/node_modules/@posthog/core/src/posthog-core.ts +14 -0
  175. package/node_modules/@posthog/core/src/types.ts +1 -0
  176. package/node_modules/@posthog/core/src/utils/index.ts +1 -0
  177. package/node_modules/@posthog/core/src/utils/otlp-any-value.spec.ts +1 -1
  178. package/node_modules/@posthog/core/src/utils/type-utils.ts +4 -4
  179. package/node_modules/@posthog/core/src/utils/webview-app-utils.spec.ts +118 -0
  180. package/node_modules/@posthog/core/src/utils/webview-app-utils.ts +49 -0
  181. package/node_modules/@posthog/types/dist/feature-flags.d.ts +1 -1
  182. package/node_modules/@posthog/types/dist/feature-flags.d.ts.map +1 -1
  183. package/node_modules/@posthog/types/dist/posthog-config.d.ts +7 -1
  184. package/node_modules/@posthog/types/dist/posthog-config.d.ts.map +1 -1
  185. package/node_modules/@posthog/types/package.json +1 -1
  186. package/node_modules/@posthog/types/src/feature-flags.ts +1 -1
  187. package/node_modules/@posthog/types/src/posthog-config.ts +7 -1
  188. package/node_modules/@posthog/types/src/tree-shakeable.ts +1 -1
  189. package/node_modules/@zuplo/core/package.json +1 -1
  190. package/node_modules/@zuplo/graphql/package.json +1 -1
  191. package/node_modules/@zuplo/openapi-tools/package.json +1 -1
  192. package/node_modules/@zuplo/otel/package.json +1 -1
  193. package/node_modules/@zuplo/runtime/out/esm/{chunk-Z3IKCP3N.js → chunk-R4PTES5B.js} +93 -93
  194. package/node_modules/@zuplo/runtime/out/esm/chunk-R4PTES5B.js.map +1 -0
  195. package/node_modules/@zuplo/runtime/out/esm/index.js +1 -1
  196. package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js +1 -1
  197. package/node_modules/@zuplo/runtime/package.json +1 -1
  198. package/package.json +11 -11
  199. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/base64.js +0 -20
  200. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/crypto_key.js +0 -27
  201. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/helpers.js +0 -45
  202. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/invalid_key_input.js +0 -12
  203. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/is_key_like.js +0 -19
  204. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/jwk_metadata.js +0 -19
  205. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/jwk_to_key.js +0 -10
  206. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/key_options.js +0 -8
  207. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/signing.js +0 -22
  208. package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/type_checks.js +0 -30
  209. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/base64.js +0 -20
  210. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/crypto_key.js +0 -27
  211. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/helpers.js +0 -45
  212. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/invalid_key_input.js +0 -12
  213. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/is_key_like.js +0 -19
  214. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/jwk_metadata.js +0 -19
  215. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/jwk_to_key.js +0 -10
  216. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/key_options.js +0 -8
  217. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/signing.js +0 -22
  218. package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/type_checks.js +0 -30
  219. package/node_modules/@zuplo/runtime/out/esm/chunk-Z3IKCP3N.js.map +0 -1
  220. /package/node_modules/@zuplo/runtime/out/esm/{chunk-Z3IKCP3N.js.LEGAL.txt → chunk-R4PTES5B.js.LEGAL.txt} +0 -0
@@ -22,7 +22,7 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{$ as ja,$a as Uc,$b as xd,$c as wu,$e as fr,$f as Vu,Aa as sc,Ab as id,Ac as Vd,Af as qu,Ag as $n,B as Io,Ba as ac,Bb as sd,Bc as Kd,Bf as zu,Bg as nl,Ca as cc,Cb as ad,Cc as Wd,Cf as Mu,Cg as Lo,Da as dc,Db as cd,Dc as Zd,Df as Mo,Dg as Dn,Ea as uc,Eb as dd,Ec as Yd,Ef as Mn,Eg as ol,Fa as lc,Fb as ud,Fc as Xd,Ff as Nu,Fg as il,Ga as pc,Gb as ld,Gc as Qd,Gf as _r,Gg as sl,Ha as mc,Hb as pd,Hc as eu,Hf as ju,Hg as al,Ia as hc,Ib as md,Ic as tu,If as Li,Ig as cl,Ja as xi,Jb as hd,Jc as ru,Jf as $u,Jg as dl,Ka as fc,Kb as fd,Kc as nu,Kf as Nn,Kg as ul,La as gc,Lb as gd,Lc as ou,Lf as No,Lg as ll,Ma as yc,Mb as yd,Mc as iu,Mf as Du,Mg as Ho,Na as Sc,Nb as Sd,Nc as su,Nf as Lu,Ng as pl,Oa as _c,Ob as _d,Oc as au,Of as Hu,Og as ml,Pa as wc,Pb as wd,Pc as cu,Pf as Bu,Pg as N,Qa as Rc,Qb as Rd,Qc as du,Qf as ye,Qg as J,R as Po,Ra as bc,Rb as bd,Rc as uu,Rf as de,Rg as me,S as ki,Sa as vc,Sb as Ui,Sc as lu,Sf as Fu,Sg as We,T as cr,Ta as Cc,Tb as vd,Tc as pu,Tf as Gu,Tg as X,U as Un,Ua as Ic,Ub as Cd,Uc as mu,Uf as $,Ug as Bo,V as dr,Va as Tc,Vb as Id,Vc as hu,Ve as ku,Vf as Ve,Vg as wg,W as ur,Wa as kc,Wb as Td,Wc as fu,We as be,Wf as wr,Wg as Rg,X as On,Xa as Pc,Xb as kd,Xc as gu,Xe as Pu,Xf as pe,Y as lr,Ya as Ac,Yb as Pd,Yc as yu,Ye as Au,Yf as te,Z as Ma,Za as Ec,Zb as Ad,Zc as Su,Ze as Y,Zf as Ju,_ as Na,_a as xc,_b as Ed,_c as _u,_e as Eu,_f as W,aa as $a,ab as Oc,ac as Ud,ad as Ru,af as xu,ag as lt,ba as Da,bb as qc,bc as Od,bd as pr,bf as gr,bg as Hi,ca as La,cb as zc,cc as qd,cd as mr,cf as I,cg as jo,da as Ha,db as Mc,dc as zd,dd as bu,df as yr,dg as Bi,ea as Ba,eb as Nc,ec as Md,ed as hr,ef as Sr,eg as $o,fa as Fa,fb as jc,fc as Nd,fd as at,ff as ct,fg as jn,ga as Ga,gb as $c,gc as jd,gd as Di,gf as dt,gg as Rr,ha as Ja,hb as Dc,hc as Oi,hd as Oo,hf as qo,hg as Ku,ia as Va,ib as Lc,ic as Ao,id as vu,if as Uu,ig as Ke,ja as Ka,jb as Hc,jc as Eo,jd as zn,jf as Oe,jg as Fi,ka as Wa,kb as Bc,kc as qi,kd as jt,kf as Ou,kg as Gi,l as $e,la as Za,lb as Fc,lc as zi,ld as Cu,lf as Je,lg as Wu,ma as Ya,mb as Gc,mc as Mi,md as Iu,mf as x,mg as Do,na as Nt,nb as Jc,nc as $d,nf as zo,ng as Ji,oa as Pi,ob as Vc,oc as Ni,of as le,og as Vi,pa as Ai,pb as Kc,pc as ji,pf as ut,pg as Zu,qa as qn,qb as Wc,qc as Dd,qf as ug,qg as ne,ra as Ei,rb as Zc,rc as Ld,rf as lg,rg as Yu,s as Mt,sa as Xa,sb as Yc,sc as $i,sd as Tu,sf as pg,sg as Xu,t as Ea,ta as Qa,tb as Xc,tc as xo,tf as mg,tg as Ki,ua as ec,ub as Qc,uc as Uo,uf as hg,ug as Qu,va as tc,vb as ed,vc as Hd,vf as fg,vg as el,wa as rc,wb as td,wc as Bd,wf as gg,wg as Wi,xa as nc,xb as rd,xc as Fd,xf as yg,xg as tl,ya as oc,yb as nd,yc as Gd,yf as Sg,yg as $t,z as Ua,za as ic,zb as od,zc as Jd,zf as _g,zg as rl}from"../chunk-Z3IKCP3N.js";import"../chunk-CUK3VROF.js";import{a as H}from"../chunk-S4EBLGSU.js";import{a as hl}from"../chunk-6SNZ4DOC.js";import{a as xa}from"../chunk-QGAJTUPE.js";import"../chunk-A3QGJZO7.js";import{A as g,B as z,C as Ti,D as ko,G as l,h as Ci,i as En,j as Oa,k as d,l as qa,m as za,n as b,o as E,p as To,r as q,s as _,t as m,u as M,v as P,w as Ii,x as xn,y as T,z as j}from"../chunk-K4TBJG47.js";import"../chunk-UKQQD2JN.js";import{W as Pe,X as v,Y as K,Z as Aa,_ as Co}from"../chunk-XF3IIUDX.js";import{a as n}from"../chunk-TYV53J3B.js";var bg=Object.create,Fo=Object.defineProperty,vg=Object.getOwnPropertyDescriptor,Cg=Object.getOwnPropertyNames,Ig=Object.getPrototypeOf,Tg=Object.prototype.hasOwnProperty,fl=n((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),gl=n((e,t)=>{let r={};for(var o in e)Fo(r,o,{get:e[o],enumerable:!0});return t&&Fo(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll"),kg=n((e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var i=Cg(t),s=0,c=i.length,a;s<c;s++)a=i[s],!Tg.call(e,a)&&a!==r&&Fo(e,a,{get:(u=>t[u]).bind(null,a),enumerable:!(o=vg(t,a))||o.enumerable});return e},"__copyProps"),yl=n((e,t,r)=>(r=e!=null?bg(Ig(e)):{},kg(t||!e||!e.__esModule?Fo(r,"default",{value:e,enumerable:!0}):r,e)),"__toESM");var Pg=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function Sl(e){return typeof e=="string"&&Pg.has(e.replace(/#$/,""))}n(Sl,"declares2019Dialect");var ts=Symbol.for("mcp.sdk.errorBrands");function Dt(e,t){let r=new Set,o=t;for(;typeof o=="function";){let i=o.mcpBrand;Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof i=="string"&&r.add(i),o=Object.getPrototypeOf(o)}r.size!==0&&Object.defineProperty(e,ts,{value:r,enumerable:!1,configurable:!0})}n(Dt,"stampErrorBrands");function ve(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,ts)){let r=t[ts];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}n(ve,"brandedHasInstance");var ue=(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})({}),mt=class Pl extends Error{static{n(this,"OAuthError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return ve(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 ve(this,t)}constructor(t,r,o){super(r),this.code=t,this.errorUri=o,this.name="OAuthError",Dt(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 Pl(t.error,t.error_description??t.error,t.error_uri)}},ie=(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})({}),re=class extends Error{static{n(this,"SdkError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return ve(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 ve(this,e)}constructor(e,t,r){super(t),this.code=e,this.data=r,this.name="SdkError",Dt(this,new.target)}},Dg=class extends re{static{n(this,"SdkHttpError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r){super(e,t,r),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function Al(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(Al,"resourceUrlFromServerUrl");function El({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return i.startsWith(s)}n(El,"checkResourceAllowed");var Lg="2026-07-28";function xl(e){return e>=Lg}n(xl,"isModernProtocolVersion");function Ul(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(r=>r.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}n(Ul,"appendTextFallbackForNonObject");var Ol=["task","inputRequests","requestState"];function Hg(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Ol.some(t=>t in e)?e:{...e,content:[]}}n(Hg,"normalizeContentlessToolResult");function Bg(){let e=Ti(()=>P([d(),b(),E(),To(),T(d(),e),_(e)])),t=T(d(),e),r=P([d(),b().int()]),o=d(),i=m({ttl:b().optional()}),s=m({taskId:d()}),c=M({progressToken:r.optional(),"io.modelcontextprotocol/related-task":s.optional()}),a=m({_meta:c.optional()}),u=a.extend({task:i.optional()}),p=m({method:d(),params:a.loose().optional()}),h=m({_meta:c.optional()}),f=m({method:d(),params:h.loose().optional()}),y=M({_meta:c.optional()}),S=P([d(),b().int()]),k=y.strict(),w=h.extend({requestId:S.optional(),reason:d().optional()}),C=f.extend({method:g("notifications/cancelled"),params:w}),U=m({src:d(),mimeType:d().optional(),sizes:_(d()).optional(),theme:j(["light","dark"]).optional()}),O=m({icons:_(U).optional()}),L=m({name:d(),title:d().optional()}),F=L.extend({...L.shape,...O.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),ee=xn(m({applyDefaults:E().optional()}),t),G=ko(ce=>ce&&typeof ce=="object"&&!Array.isArray(ce)&&Object.keys(ce).length===0?{form:{}}:ce,xn(m({form:ee.optional(),url:t.optional()}),t.optional())),V=M({list:t.optional(),cancel:t.optional(),requests:M({sampling:M({createMessage:t.optional()}).optional(),elicitation:M({create:t.optional()}).optional()}).optional()}),Be=M({list:t.optional(),cancel:t.optional(),requests:M({tools:M({call:t.optional()}).optional()}).optional()}),oe=m({experimental:T(d(),t).optional(),sampling:m({context:t.optional(),tools:t.optional()}).optional(),elicitation:G.optional(),roots:m({listChanged:E().optional()}).optional(),tasks:V.optional(),extensions:T(d(),t).optional()}),Me=a.extend({protocolVersion:d(),capabilities:oe,clientInfo:F}),D=p.extend({method:g("initialize"),params:Me}),Ee=m({experimental:T(d(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:m({listChanged:E().optional()}).optional(),resources:m({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:m({listChanged:E().optional()}).optional(),tasks:Be.optional(),extensions:T(d(),t).optional()}),Mr=y.extend({protocolVersion:d(),capabilities:Ee,serverInfo:F,instructions:d().optional()}),Gt=f.extend({method:g("notifications/initialized"),params:h.optional()}),tt=p.extend({method:g("ping"),params:a.optional()}),vt=m({progress:b(),total:z(b()),message:z(d())}),Ne=m({...h.shape,...vt.shape,progressToken:r}),rt=f.extend({method:g("notifications/progress"),params:Ne}),Jt=a.extend({cursor:o.optional()}),Fe=p.extend({params:Jt.optional()}),Ge=y.extend({nextCursor:o.optional()}),Vt=m({uri:d(),mimeType:z(d()),_meta:T(d(),q()).optional()}),Kt=Vt.extend({text:d()}),Ct=d().refine(ce=>{try{return atob(ce),!0}catch{return!1}},{message:"Invalid Base64 string"}),Wt=Vt.extend({blob:Ct}),je=j(["user","assistant"]),xe=m({audience:_(je).optional(),priority:b().min(0).max(1).optional(),lastModified:En.datetime({offset:!0}).optional()}),It=m({...L.shape,...O.shape,uri:d(),description:z(d()),mimeType:z(d()),size:z(b()),annotations:xe.optional(),_meta:z(M({}))}),Nr=m({...L.shape,...O.shape,uriTemplate:d(),description:z(d()),mimeType:z(d()),annotations:xe.optional(),_meta:z(M({}))}),jr=Fe.extend({method:g("resources/list")}),$r=Ge.extend({resources:_(It)}),nt=Fe.extend({method:g("resources/templates/list")}),Zt=Ge.extend({resourceTemplates:_(Nr)}),Tt=a.extend({uri:d()}),Dr=Tt,Lr=p.extend({method:g("resources/read"),params:Dr}),Hr=y.extend({contents:_(P([Kt,Wt]))}),Br=f.extend({method:g("notifications/resources/list_changed"),params:h.optional()}),Fr=Tt,Gr=p.extend({method:g("resources/subscribe"),params:Fr}),Jr=Tt,Vr=p.extend({method:g("resources/unsubscribe"),params:Jr}),Kr=h.extend({uri:d()}),Wr=f.extend({method:g("notifications/resources/updated"),params:Kr}),Zr=m({name:d(),description:z(d()),required:z(E())}),Yr=m({...L.shape,...O.shape,description:z(d()),arguments:z(_(Zr)),_meta:z(M({}))}),Xr=Fe.extend({method:g("prompts/list")}),Qr=Ge.extend({prompts:_(Yr)}),en=a.extend({name:d(),arguments:T(d(),d()).optional()}),tn=p.extend({method:g("prompts/get"),params:en}),kt=m({type:g("text"),text:d(),annotations:xe.optional(),_meta:T(d(),q()).optional()}),Pt=m({type:g("image"),data:Ct,mimeType:d(),annotations:xe.optional(),_meta:T(d(),q()).optional()}),At=m({type:g("audio"),data:Ct,mimeType:d(),annotations:xe.optional(),_meta:T(d(),q()).optional()}),rn=m({type:g("tool_use"),name:d(),id:d(),input:T(d(),q()),_meta:T(d(),q()).optional()}),ot=m({type:g("resource"),resource:P([Kt,Wt]),annotations:xe.optional(),_meta:T(d(),q()).optional()}),nn=It.extend({type:g("resource_link")}),ke=P([kt,Pt,At,nn,ot]),Yt=m({role:je,content:ke}),Xt=y.extend({description:d().optional(),messages:_(Yt)}),Et=f.extend({method:g("notifications/prompts/list_changed"),params:h.optional()}),on=m({title:d().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Qt=m({taskSupport:j(["required","optional","forbidden"]).optional()}),xt=m({...L.shape,...O.shape,description:d().optional(),inputSchema:m({type:g("object"),properties:T(d(),e).optional(),required:_(d()).optional()}).catchall(q()),outputSchema:m({type:g("object"),properties:T(d(),e).optional(),required:_(d()).optional()}).catchall(q()).optional(),annotations:on.optional(),execution:Qt.optional(),_meta:T(d(),q()).optional()}),er=Fe.extend({method:g("tools/list")}),tr=Ge.extend({tools:_(xt)}),rr=y.extend({content:_(ke),structuredContent:T(d(),q()).optional(),isError:E().optional()}),ae=u.extend({name:d(),arguments:T(d(),q()).optional()}),sn=p.extend({method:g("tools/call"),params:ae}),so=f.extend({method:g("notifications/tools/list_changed"),params:h.optional()}),nr=j(["debug","info","notice","warning","error","critical","alert","emergency"]),an=a.extend({level:nr}),cn=p.extend({method:g("logging/setLevel"),params:an}),dn=h.extend({level:nr,logger:d().optional(),data:q()}),un=f.extend({method:g("notifications/message"),params:dn}),ln=m({name:d().optional()}),pn=m({hints:_(ln).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),mn=m({mode:j(["auto","required","none"]).optional()}),ao=m({type:g("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:_(ke),structuredContent:m({}).loose().optional(),isError:E().optional(),_meta:T(d(),q()).optional()}),hn=Ii("type",[kt,Pt,At]),it=Ii("type",[kt,Pt,At,rn,ao]),fn=m({role:je,content:P([it,_(it)]),_meta:T(d(),q()).optional()}),gn=u.extend({messages:_(fn),modelPreferences:pn.optional(),systemPrompt:d().optional(),includeContext:j(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:_(d()).optional(),metadata:t.optional(),tools:_(xt).optional(),toolChoice:mn.optional()}),yn=p.extend({method:g("sampling/createMessage"),params:gn}),Sn=y.extend({model:d(),stopReason:z(j(["endTurn","stopSequence","maxTokens"]).or(d())),role:je,content:hn}),_n=y.extend({model:d(),stopReason:z(j(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:je,content:P([it,_(it)])}),wn=m({type:g("boolean"),title:d().optional(),description:d().optional(),default:E().optional()}),Rn=m({type:g("string"),title:d().optional(),description:d().optional(),minLength:b().optional(),maxLength:b().optional(),format:j(["email","uri","date","date-time"]).optional(),default:d().optional()}),bn=m({type:j(["number","integer"]),title:d().optional(),description:d().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),vn=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),default:d().optional()}),Cn=m({type:g("string"),title:d().optional(),description:d().optional(),oneOf:_(m({const:d(),title:d()})),default:d().optional()}),In=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),enumNames:_(d()).optional(),default:d().optional()}),Tn=P([vn,Cn]),Ut=m({type:g("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({type:g("string"),enum:_(d())}),default:_(d()).optional()}),Ot=m({type:g("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({anyOf:_(m({const:d(),title:d()}))}),default:_(d()).optional()}),co=P([Ut,Ot]),uo=P([In,Tn,co]),we=P([uo,wn,Rn,bn]),Re=u.extend({mode:g("form").optional(),message:d(),requestedSchema:m({type:g("object"),properties:T(d(),we),required:_(d()).optional()}).catchall(q())}),kn=u.extend({mode:g("url"),message:d(),elicitationId:d(),url:d().url()}),Ue=P([Re,kn]),lo=p.extend({method:g("elicitation/create"),params:Ue}),po=h.extend({elicitationId:d()}),mo=f.extend({method:g("notifications/elicitation/complete"),params:po}),ho=y.extend({action:j(["accept","decline","cancel"]),content:ko(ce=>ce===null?void 0:ce,T(d(),P([d(),b(),E(),_(d())])).optional())}),fo=m({type:g("ref/resource"),uri:d()}),go=m({type:g("ref/prompt"),name:d()}),yo=a.extend({ref:P([go,fo]),argument:m({name:d(),value:d()}),context:m({arguments:T(d(),d()).optional()}).optional()}),Pn=p.extend({method:g("completion/complete"),params:yo}),So=y.extend({completion:M({values:_(d()).max(100),total:z(b().int()),hasMore:z(E())})}),_o=m({uri:d().startsWith("file://"),name:d().optional(),_meta:T(d(),q()).optional()}),or=p.extend({method:g("roots/list"),params:a.optional()}),An=y.extend({roots:_(_o)}),wo=f.extend({method:g("notifications/roots/list_changed"),params:h.optional()}),Ro=M({ttl:b().optional(),pollInterval:b().optional()}),bo=j(["working","input_required","completed","failed","cancelled"]),st=m({taskId:d(),status:bo,ttl:P([b(),To()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:z(b()),statusMessage:z(d())}),fe=y.extend({task:st}),vo=h.merge(st),qt=f.extend({method:g("notifications/tasks/status"),params:vo}),ir=p.extend({method:g("tasks/get"),params:a.extend({taskId:d()})}),sr=y.merge(st),ar=p.extend({method:g("tasks/result"),params:a.extend({taskId:d()})}),vi=y.loose(),ge=Fe.extend({method:g("tasks/list")}),Z=Ge.extend({tasks:_(st)}),zt=p.extend({method:g("tasks/cancel"),params:a.extend({taskId:d()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:i,RelatedTaskMetadataSchema:s,RequestMetaSchema:c,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:u,RequestSchema:p,NotificationsParamsSchema:h,NotificationSchema:f,ResultSchema:y,RequestIdSchema:S,EmptyResultSchema:k,CancelledNotificationParamsSchema:w,CancelledNotificationSchema:C,IconSchema:U,IconsSchema:O,BaseMetadataSchema:L,ImplementationSchema:F,ClientTasksCapabilitySchema:V,ServerTasksCapabilitySchema:Be,ClientCapabilitiesSchema:oe,InitializeRequestParamsSchema:Me,InitializeRequestSchema:D,ServerCapabilitiesSchema:Ee,InitializeResultSchema:Mr,InitializedNotificationSchema:Gt,PingRequestSchema:tt,ProgressSchema:vt,ProgressNotificationParamsSchema:Ne,ProgressNotificationSchema:rt,PaginatedRequestParamsSchema:Jt,PaginatedRequestSchema:Fe,PaginatedResultSchema:Ge,ResourceContentsSchema:Vt,TextResourceContentsSchema:Kt,BlobResourceContentsSchema:Wt,RoleSchema:je,AnnotationsSchema:xe,ResourceSchema:It,ResourceTemplateSchema:Nr,ListResourcesRequestSchema:jr,ListResourcesResultSchema:$r,ListResourceTemplatesRequestSchema:nt,ListResourceTemplatesResultSchema:Zt,ResourceRequestParamsSchema:Tt,ReadResourceRequestParamsSchema:Dr,ReadResourceRequestSchema:Lr,ReadResourceResultSchema:Hr,ResourceListChangedNotificationSchema:Br,SubscribeRequestParamsSchema:Fr,SubscribeRequestSchema:Gr,UnsubscribeRequestParamsSchema:Jr,UnsubscribeRequestSchema:Vr,ResourceUpdatedNotificationParamsSchema:Kr,ResourceUpdatedNotificationSchema:Wr,PromptArgumentSchema:Zr,PromptSchema:Yr,ListPromptsRequestSchema:Xr,ListPromptsResultSchema:Qr,GetPromptRequestParamsSchema:en,GetPromptRequestSchema:tn,TextContentSchema:kt,ImageContentSchema:Pt,AudioContentSchema:At,ToolUseContentSchema:rn,EmbeddedResourceSchema:ot,ResourceLinkSchema:nn,ContentBlockSchema:ke,PromptMessageSchema:Yt,GetPromptResultSchema:Xt,PromptListChangedNotificationSchema:Et,ToolAnnotationsSchema:on,ToolExecutionSchema:Qt,ToolSchema:xt,ListToolsRequestSchema:er,ListToolsResultSchema:tr,CallToolResultSchema:rr,CallToolRequestParamsSchema:ae,CallToolRequestSchema:sn,ToolListChangedNotificationSchema:so,LoggingLevelSchema:nr,SetLevelRequestParamsSchema:an,SetLevelRequestSchema:cn,LoggingMessageNotificationParamsSchema:dn,LoggingMessageNotificationSchema:un,ModelHintSchema:ln,ModelPreferencesSchema:pn,ToolChoiceSchema:mn,ToolResultContentSchema:ao,SamplingContentSchema:hn,SamplingMessageContentBlockSchema:it,SamplingMessageSchema:fn,CreateMessageRequestParamsSchema:gn,CreateMessageRequestSchema:yn,CreateMessageResultSchema:Sn,CreateMessageResultWithToolsSchema:_n,BooleanSchemaSchema:wn,StringSchemaSchema:Rn,NumberSchemaSchema:bn,UntitledSingleSelectEnumSchemaSchema:vn,TitledSingleSelectEnumSchemaSchema:Cn,LegacyTitledEnumSchemaSchema:In,SingleSelectEnumSchemaSchema:Tn,UntitledMultiSelectEnumSchemaSchema:Ut,TitledMultiSelectEnumSchemaSchema:Ot,MultiSelectEnumSchemaSchema:co,EnumSchemaSchema:uo,PrimitiveSchemaDefinitionSchema:we,ElicitRequestFormParamsSchema:Re,ElicitRequestURLParamsSchema:kn,ElicitRequestParamsSchema:Ue,ElicitRequestSchema:lo,ElicitationCompleteNotificationParamsSchema:po,ElicitationCompleteNotificationSchema:mo,ElicitResultSchema:ho,ResourceTemplateReferenceSchema:fo,PromptReferenceSchema:go,CompleteRequestParamsSchema:yo,CompleteRequestSchema:Pn,CompleteResultSchema:So,RootSchema:_o,ListRootsRequestSchema:or,ListRootsResultSchema:An,RootsListChangedNotificationSchema:wo,TaskCreationParamsSchema:Ro,TaskStatusSchema:bo,TaskSchema:st,CreateTaskResultSchema:fe,TaskStatusNotificationParamsSchema:vo,TaskStatusNotificationSchema:qt,GetTaskRequestSchema:ir,GetTaskResultSchema:sr,GetTaskPayloadRequestSchema:ar,GetTaskPayloadResultSchema:vi,ListTasksRequestSchema:ge,ListTasksResultSchema:Z,CancelTaskRequestSchema:zt,CancelTaskResultSchema:y.merge(st),ClientRequestSchema:P([tt,D,Pn,cn,tn,Xr,jr,nt,Lr,Gr,Vr,sn,er,ir,ar,ge,zt]),ClientNotificationSchema:P([C,rt,Gt,wo,qt]),ClientResultSchema:P([k,Sn,_n,ho,An,sr,Z,fe]),ServerRequestSchema:P([tt,yn,lo,or,ir,ar,ge,zt]),ServerNotificationSchema:P([C,rt,un,Wr,Br,so,Et,qt,mo]),ServerResultSchema:P([k,Mr,So,Xt,Qr,$r,Zt,Hr,rr,tr,sr,Z,fe]),CallToolResultWireSchema:q().superRefine((ce,dg)=>{if(!(typeof ce!="object"||ce===null||Array.isArray(ce)||ce.content!==void 0)){for(let Pa of Ol)if(Pa in ce){dg.addIssue({code:"custom",message:`content is required when the body carries '${Pa}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(Hg).pipe(rr)}}n(Bg,"build$1");var Fg;function as(){return Fg??=Bg()}n(as,"buildSchemas2025");function ql(e){return e.type!=="object"}n(ql,"isNonObjectJsonSchemaRoot");var Gg=new Set(["const","enum","default","examples"]),Jg=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function _l(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}n(_l,"establishesNewBase");function Vg(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(_l(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=Sl(e.$schema)&&e.$recursiveAnchor!==!0,o=n((i,s)=>{if(Array.isArray(i))return i.map(u=>o(u,!1));if(i===null||typeof i!="object"||!s&&_l(i.$id))return i;let c={},a=!1;for(let[u,p]of Object.entries(i))s?c[u]=o(p,!1):(u==="$ref"||u==="$dynamicRef")&&typeof p=="string"?c[u]=p==="#"?"#/properties/result":p.startsWith("#/")?`#/properties/result${p.slice(1)}`:p:u==="$recursiveRef"&&p==="#"&&r?a=!0:Gg.has(u)?c[u]=p:Jg.has(u)?c[u]=o(p,!0):c[u]=o(p,!1);return a&&("$ref"in c?c.allOf=[...Array.isArray(c.allOf)?c.allOf:[],{$ref:"#/properties/result"}]:c.$ref="#/properties/result"),c},"rewriteRefs");return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}n(Vg,"wrapOutputSchemaForLegacy");var zl={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},Ml={"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},Kg={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},Go;function Wo(){if(Go)return Go;let e=as();return Go={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}},Go}n(Wo,"registryMaps");function Wg(){Wo()}n(Wg,"warmRegistryMaps2025");function Nl(e){return Object.prototype.hasOwnProperty.call(zl,e)}n(Nl,"hasRequestMethod2025");function jl(e){return Object.prototype.hasOwnProperty.call(Ml,e)}n(jl,"hasNotificationMethod2025");function Zg(e){return Object.prototype.hasOwnProperty.call(Kg,e)}n(Zg,"hasResultMethod");function Yg(e){return Zg(e)?Wo().resultSchemas[e]:void 0}n(Yg,"getResultSchema");function Xg(e){return Nl(e)?Wo().requestSchemas[e]:void 0}n(Xg,"getRequestSchema");function Qg(e){return jl(e)?Wo().notificationSchemas[e]:void 0}n(Qg,"getNotificationSchema");var aT=Object.keys(zl),cT=Object.keys(Ml);function rs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(rs,"isPlainObject$4");function Jo(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}n(Jo,"triState$1");var wl={ok:!1,reason:"not-in-era"};function Rl(e){return rs(e)&&rs(e.outputSchema)&&ql(e.outputSchema)}n(Rl,"toolNeedsLegacyWrap");var cs={era:"2025-11-25",hasRequestMethod:Nl,hasNotificationMethod:jl,validateRequest:n((e,t)=>Jo(Xg(e),t),"validateRequest"),validateResult:n((e,t)=>Jo(Yg(e),t),"validateResult"),validateNotification:n((e,t)=>Jo(Qg(e),t),"validateNotification"),hasInputRequestMethod:n(()=>!1,"hasInputRequestMethod"),validateInputRequest:n(()=>wl,"validateInputRequest"),validateInputResponse:n(()=>wl,"validateInputResponse"),samplingResultVariant:n(((e,t)=>{let r=as();return Jo(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:n(e=>{},"outboundEnvelope"),validateEnvelopeMeta:n(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let r=Ul(e),o=r.structuredContent;if(o===void 0)return r;let i=typeof o!="object"||o===null||Array.isArray(o),s=t!==void 0&&ql(t);return!i&&!s?r:{...r,structuredContent:{result:o}}},decodeResult(e,t){if(rs(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:r}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;return!Array.isArray(r)||!r.some(o=>Rl(o))?t:{...t,tools:r.map(o=>Rl(o)?{...o,outputSchema:Vg(o.outputSchema)}:o)}},encodeErrorCode:n(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:n(e=>{},"checkInboundEnvelope")};function ey(){let e=Ti(()=>P([d(),b(),E(),To(),T(d(),e),_(e)])),t=T(d(),e),r=P([d(),b().int()]),o=d(),i=P([d(),b().int()]),s=j(["user","assistant"]),c=j(["debug","info","notice","warning","error","critical","alert","emergency"]),a=d().refine(Z=>{try{return atob(Z),!0}catch{return!1}},{message:"Invalid Base64 string"}),u=m({ttl:b().optional()}),p=m({taskId:d()}),h=M({progressToken:r.optional(),"io.modelcontextprotocol/related-task":p.optional()}),f=m({_meta:h.optional()}),y=f.extend({task:u.optional()}),S=m({_meta:h.optional()}),k=m({method:d(),params:S.loose().optional()}),w=m({src:d(),mimeType:d().optional(),sizes:_(d()).optional(),theme:j(["light","dark"]).optional()}),C=m({icons:_(w).optional()}),U=m({name:d(),title:d().optional()}),O=U.extend({...U.shape,...C.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),L=xn(m({applyDefaults:E().optional()}),t),F=ko(Z=>Z&&typeof Z=="object"&&!Array.isArray(Z)&&Object.keys(Z).length===0?{form:{}}:Z,xn(m({form:L.optional(),url:t.optional()}),t.optional())),ee=M({list:t.optional(),cancel:t.optional(),requests:M({sampling:M({createMessage:t.optional()}).optional(),elicitation:M({create:t.optional()}).optional()}).optional()}),G=M({list:t.optional(),cancel:t.optional(),requests:M({tools:M({call:t.optional()}).optional()}).optional()}),V=m({experimental:T(d(),t).optional(),sampling:m({context:t.optional(),tools:t.optional()}).optional(),elicitation:F.optional(),roots:m({listChanged:E().optional()}).optional(),tasks:ee.optional(),extensions:T(d(),t).optional()}),Be=m({experimental:T(d(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:m({listChanged:E().optional()}).optional(),resources:m({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:m({listChanged:E().optional()}).optional(),tasks:G.optional(),extensions:T(d(),t).optional()}),oe=m({progress:b(),total:z(b()),message:z(d())}),Me=m({...S.shape,...oe.shape,progressToken:r}),D=k.extend({method:g("notifications/progress"),params:Me}),Ee=S.extend({level:c,logger:d().optional(),data:q()}),Mr=k.extend({method:g("notifications/message"),params:Ee}),Gt=m({uri:d(),mimeType:z(d()),_meta:T(d(),q()).optional()}),tt=Gt.extend({text:d()}),vt=Gt.extend({blob:a}),Ne=m({audience:_(s).optional(),priority:b().min(0).max(1).optional(),lastModified:En.datetime({offset:!0}).optional()}),rt=m({...U.shape,...C.shape,uri:d(),description:z(d()),mimeType:z(d()),size:z(b()),annotations:Ne.optional(),_meta:z(M({}))}),Jt=m({...U.shape,...C.shape,uriTemplate:d(),description:z(d()),mimeType:z(d()),annotations:Ne.optional(),_meta:z(M({}))}),Fe=k.extend({method:g("notifications/resources/list_changed"),params:S.optional()}),Ge=S.extend({uri:d()}),Vt=k.extend({method:g("notifications/resources/updated"),params:Ge}),Kt=m({name:d(),description:z(d()),required:z(E())}),Ct=m({...U.shape,...C.shape,description:z(d()),arguments:z(_(Kt)),_meta:z(M({}))}),Wt=k.extend({method:g("notifications/prompts/list_changed"),params:S.optional()}),je=m({type:g("text"),text:d(),annotations:Ne.optional(),_meta:T(d(),q()).optional()}),xe=m({type:g("image"),data:a,mimeType:d(),annotations:Ne.optional(),_meta:T(d(),q()).optional()}),It=m({type:g("audio"),data:a,mimeType:d(),annotations:Ne.optional(),_meta:T(d(),q()).optional()}),Nr=m({type:g("tool_use"),name:d(),id:d(),input:T(d(),q()),_meta:T(d(),q()).optional()}),jr=m({type:g("resource"),resource:P([tt,vt]),annotations:Ne.optional(),_meta:T(d(),q()).optional()}),$r=rt.extend({type:g("resource_link")}),nt=P([je,xe,It,$r,jr]),Zt=m({role:s,content:nt}),Tt=m({title:d().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Dr=k.extend({method:g("notifications/tools/list_changed"),params:S.optional()}),Lr=m({name:d().optional()}),Hr=m({hints:_(Lr).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),Br=m({mode:j(["auto","required","none"]).optional()}),Fr=m({type:g("boolean"),title:d().optional(),description:d().optional(),default:E().optional()}),Gr=m({type:g("string"),title:d().optional(),description:d().optional(),minLength:b().optional(),maxLength:b().optional(),format:j(["email","uri","date","date-time"]).optional(),default:d().optional()}),Jr=m({type:j(["number","integer"]),title:d().optional(),description:d().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),Vr=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),default:d().optional()}),Kr=m({type:g("string"),title:d().optional(),description:d().optional(),oneOf:_(m({const:d(),title:d()})),default:d().optional()}),Wr=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),enumNames:_(d()).optional(),default:d().optional()}),Zr=P([Vr,Kr]),Yr=m({type:g("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({type:g("string"),enum:_(d())}),default:_(d()).optional()}),Xr=m({type:g("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({anyOf:_(m({const:d(),title:d()}))}),default:_(d()).optional()}),Qr=P([Yr,Xr]),en=P([Wr,Zr,Qr]),tn=P([en,Fr,Gr,Jr]),kt=y.extend({mode:g("form").optional(),message:d(),requestedSchema:m({type:g("object"),properties:T(d(),tn),required:_(d()).optional()}).catchall(q())}),Pt=m({type:g("ref/resource"),uri:d()}),At=m({type:g("ref/prompt"),name:d()}),rn=m({uri:d().startsWith("file://"),name:d().optional(),_meta:T(d(),q()).optional()}),ot=V.shape,nn=m({experimental:ot.experimental,sampling:ot.sampling,elicitation:ot.elicitation,roots:ot.roots,extensions:ot.extensions}),ke=Be.shape,Yt=m({experimental:ke.experimental,logging:ke.logging,completions:ke.completions,prompts:ke.prompts,resources:ke.resources,tools:ke.tools,extensions:ke.extensions}),Xt=M({progressToken:r.optional(),[cr]:d(),[Un]:O.optional(),[ur]:nn,[On]:c.optional()}),Et=m({...U.shape,...C.shape,description:d().optional(),inputSchema:M({$schema:d().optional(),type:g("object")}),outputSchema:M({$schema:d().optional()}).optional(),annotations:Tt.optional(),_meta:T(d(),q()).optional()}),on=m({type:g("tool_result"),toolUseId:d(),content:_(nt),structuredContent:q().optional(),isError:E().optional(),_meta:T(d(),q()).optional()}),Qt=P([je,xe,It,Nr,on]),xt=m({role:s,content:P([Qt,_(Qt)]),_meta:T(d(),q()).optional()}),er=d(),tr=M({[dr]:O.optional().catch(void 0)}),rr=tr.optional();function ae(Z){return M({_meta:rr,resultType:er.default("complete"),...Z})}n(ae,"wireResult");let sn=ae({}),so=ae({nextCursor:o.optional()}),nr=ae({content:_(nt),structuredContent:q().optional(),isError:E().optional()}),an=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),tools:_(Et),nextCursor:o.optional()}),cn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),prompts:_(Ct),nextCursor:o.optional()}),dn=ae({description:d().optional(),messages:_(Zt)}),un=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),resources:_(rt),nextCursor:o.optional()}),ln=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),resourceTemplates:_(Jt),nextCursor:o.optional()}),pn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),contents:_(P([tt,vt]))}),mn=ae({completion:m({values:_(d()).max(100),total:b().int().optional(),hasMore:E().optional()}).loose()}),ao=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"])}),hn=ae({ttlMs:b().int().min(0).catch(0),cacheScope:j(["public","private"]).catch("private"),supportedVersions:_(d()),capabilities:Yt,instructions:d().optional()}),it=m({messages:_(xt),modelPreferences:Hr.optional(),systemPrompt:d().optional(),includeContext:j(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:_(d()).optional(),metadata:t.optional(),tools:_(Et).optional(),toolChoice:Br.optional()}),fn=m({method:g("sampling/createMessage"),params:it}),gn=m({method:g("roots/list"),params:m({_meta:T(d(),q()).optional()}).optional()}),yn=m({...xt.shape,model:d(),stopReason:d().optional()}),Sn=m({roots:_(rn)}),_n=m({action:j(["accept","decline","cancel"]),content:T(d(),P([d(),b(),E(),_(d())])).optional()}),wn=m({mode:g("url"),message:d(),url:d().url()}),Rn=P([kt,wn]),bn=m({method:g("elicitation/create"),params:Rn}),vn=P([fn,gn,bn]),Cn=P([yn,Sn,_n]),In=T(d(),vn),Tn=T(d(),Cn),Ut=ae({inputRequests:In.optional(),requestState:d().optional()}),Ot={inputResponses:Tn.optional(),requestState:d().optional()},co=m({_meta:Xt,...Ot}),uo=M({progressToken:r.optional()});function we(Z,zt){return m({method:g(Z),params:m({_meta:Xt,...zt})})}n(we,"wireRequest");function Re(Z,zt){return m({method:g(Z),params:m({_meta:uo.optional(),...zt}).optional()})}n(Re,"dispatchRequest");let kn={name:d(),arguments:T(d(),q()).optional(),...Ot},Ue={cursor:o.optional()},lo=we("tools/call",kn),po=we("tools/list",Ue),mo=we("prompts/list",Ue),ho=we("prompts/get",{name:d(),arguments:T(d(),d()).optional(),...Ot}),fo=we("resources/list",Ue),go=we("resources/templates/list",Ue),yo=we("resources/read",{uri:d(),...Ot}),Pn={ref:P([At,Pt]),argument:m({name:d(),value:d()}),context:m({arguments:T(d(),d()).optional()}).optional()},So=we("completion/complete",Pn),_o=we("server/discover",{}),or=m({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:_(d()).optional()}),An={notifications:or},wo=we("subscriptions/listen",An),Ro=tr.extend({"io.modelcontextprotocol/subscriptionId":i}),bo=M({_meta:Ro,resultType:er.default("complete")}),st={"tools/call":Re("tools/call",kn),"tools/list":Re("tools/list",Ue),"prompts/get":Re("prompts/get",{name:d(),arguments:T(d(),d()).optional()}),"prompts/list":Re("prompts/list",Ue),"resources/list":Re("resources/list",Ue),"resources/templates/list":Re("resources/templates/list",Ue),"resources/read":Re("resources/read",{uri:d()}),"completion/complete":Re("completion/complete",Pn),"server/discover":Re("server/discover",{}),"subscriptions/listen":Re("subscriptions/listen",An)};function fe(Z){return M({_meta:rr,...Z})}n(fe,"liftedResult");let vo={"tools/call":fe({content:_(nt),structuredContent:q().optional(),isError:E().optional()}),"tools/list":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),tools:_(Et),nextCursor:o.optional()}),"prompts/get":fe({description:d().optional(),messages:_(Zt)}),"prompts/list":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),prompts:_(Ct),nextCursor:o.optional()}),"resources/list":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),resources:_(rt),nextCursor:o.optional()}),"resources/templates/list":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),resourceTemplates:_(Jt),nextCursor:o.optional()}),"resources/read":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),contents:_(P([tt,vt]))}),"completion/complete":fe({completion:m({values:_(d()).max(100),total:b().int().optional(),hasMore:E().optional()}).loose()}),"server/discover":fe({ttlMs:b().int().min(0).catch(0),cacheScope:j(["public","private"]).catch("private"),supportedVersions:_(d()),capabilities:Yt,instructions:d().optional()}),"subscriptions/listen":fe({})},qt=M({"io.modelcontextprotocol/subscriptionId":i.optional()}),ir=m({method:g("notifications/subscriptions/acknowledged"),params:m({_meta:qt.optional(),notifications:or})}),sr=m({_meta:qt.optional(),requestId:i,reason:d().optional()}),ar=m({method:g("notifications/cancelled"),params:sr}),vi={"notifications/cancelled":ar,"notifications/progress":D,"notifications/message":Mr,"notifications/resources/updated":Vt,"notifications/resources/list_changed":Fe,"notifications/tools/list_changed":Dr,"notifications/prompts/list_changed":Wt,"notifications/subscriptions/acknowledged":ir},ge=n(Z=>m({jsonrpc:g("2.0"),id:P([d(),b().int()]),result:Z}).strict(),"wireResultResponse");return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:i,RoleSchema:s,LoggingLevelSchema:c,TaskMetadataSchema:u,RelatedTaskMetadataSchema:p,RequestMetaSchema:h,BaseRequestParamsSchema:f,TaskAugmentedRequestParamsSchema:y,NotificationsParamsSchema:S,NotificationSchema:k,IconSchema:w,IconsSchema:C,BaseMetadataSchema:U,ImplementationSchema:O,ClientTasksCapabilitySchema:ee,ServerTasksCapabilitySchema:G,ClientCapabilitiesSchema:V,ServerCapabilitiesSchema:Be,ProgressSchema:oe,ProgressNotificationParamsSchema:Me,ProgressNotificationSchema:D,LoggingMessageNotificationParamsSchema:Ee,LoggingMessageNotificationSchema:Mr,ResourceContentsSchema:Gt,TextResourceContentsSchema:tt,BlobResourceContentsSchema:vt,AnnotationsSchema:Ne,ResourceSchema:rt,ResourceTemplateSchema:Jt,ResourceListChangedNotificationSchema:Fe,ResourceUpdatedNotificationParamsSchema:Ge,ResourceUpdatedNotificationSchema:Vt,PromptArgumentSchema:Kt,PromptSchema:Ct,PromptListChangedNotificationSchema:Wt,TextContentSchema:je,ImageContentSchema:xe,AudioContentSchema:It,ToolUseContentSchema:Nr,EmbeddedResourceSchema:jr,ResourceLinkSchema:$r,ContentBlockSchema:nt,PromptMessageSchema:Zt,ToolAnnotationsSchema:Tt,ToolListChangedNotificationSchema:Dr,ModelHintSchema:Lr,ModelPreferencesSchema:Hr,ToolChoiceSchema:Br,BooleanSchemaSchema:Fr,StringSchemaSchema:Gr,NumberSchemaSchema:Jr,UntitledSingleSelectEnumSchemaSchema:Vr,TitledSingleSelectEnumSchemaSchema:Kr,LegacyTitledEnumSchemaSchema:Wr,SingleSelectEnumSchemaSchema:Zr,UntitledMultiSelectEnumSchemaSchema:Yr,TitledMultiSelectEnumSchemaSchema:Xr,MultiSelectEnumSchemaSchema:Qr,EnumSchemaSchema:en,PrimitiveSchemaDefinitionSchema:tn,ElicitRequestFormParamsSchema:kt,ResourceTemplateReferenceSchema:Pt,PromptReferenceSchema:At,RootSchema:rn,ClientCapabilities2026Schema:nn,ServerCapabilities2026Schema:Yt,RequestMetaEnvelopeSchema:Xt,ToolSchema:Et,ToolResultContentSchema:on,SamplingMessageContentBlockSchema:Qt,SamplingMessageSchema:xt,ResultTypeSchema:er,ResultMetaSchema:tr,ResultSchema:sn,PaginatedResultSchema:so,CallToolResultSchema:nr,ListToolsResultSchema:an,ListPromptsResultSchema:cn,GetPromptResultSchema:dn,ListResourcesResultSchema:un,ListResourceTemplatesResultSchema:ln,ReadResourceResultSchema:pn,CompleteResultSchema:mn,CacheableResultSchema:ao,DiscoverResultSchema:hn,CreateMessageRequestParamsSchema:it,CreateMessageRequestSchema:fn,ListRootsRequestSchema:gn,CreateMessageResultSchema:yn,ListRootsResultSchema:Sn,ElicitResultSchema:_n,ElicitRequestURLParamsSchema:wn,ElicitRequestParamsSchema:Rn,ElicitRequestSchema:bn,InputRequestSchema:vn,InputResponseSchema:Cn,InputRequestsSchema:In,InputResponsesSchema:Tn,InputRequiredResultSchema:Ut,InputResponseRequestParamsSchema:co,CallToolRequestSchema:lo,ListToolsRequestSchema:po,ListPromptsRequestSchema:mo,GetPromptRequestSchema:ho,ListResourcesRequestSchema:fo,ListResourceTemplatesRequestSchema:go,ReadResourceRequestSchema:yo,CompleteRequestSchema:So,DiscoverRequestSchema:_o,SubscriptionFilterSchema:or,SubscriptionsListenRequestSchema:wo,SubscriptionsListenResultMetaSchema:Ro,SubscriptionsListenResultSchema:bo,dispatchRequestSchemas:st,dispatchResultSchemas:vo,NotificationMetaSchema:qt,SubscriptionsAcknowledgedNotificationSchema:ir,CancelledNotificationParamsSchema:sr,CancelledNotificationSchema:ar,notificationSchemas2026:vi,JSONRPCResultResponseSchema:ge(sn),CallToolResultResponseSchema:ge(P([nr,Ut])),ListToolsResultResponseSchema:ge(an),ListPromptsResultResponseSchema:ge(cn),GetPromptResultResponseSchema:ge(P([dn,Ut])),ListResourcesResultResponseSchema:ge(un),ListResourceTemplatesResultResponseSchema:ge(ln),ReadResourceResultResponseSchema:ge(P([pn,Ut])),CompleteResultResponseSchema:ge(mn),DiscoverResultResponseSchema:ge(hn)}}n(ey,"build");var ty;function pt(){return ty??=ey()}n(pt,"buildSchemas2026");var ry=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function ny(e){return ry.includes(e)}n(ny,"isCacheableResultMethod");var ds=Symbol("modelcontextprotocol.resultCacheHintFallback");function oy(e){return e[ds]}n(oy,"cacheHintFallbackOf");function $l(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}n($l,"isValidCacheTtlMs");function Dl(e){return e==="public"||e==="private"}n(Dl,"isValidCacheScope");var A=(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})({}),se=class Ll extends Error{static{n(this,"ProtocolError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return ve(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 ve(this,t)}constructor(t,r,o){super(r),this.code=t,this.data=o,this.name="ProtocolError",Dt(this,new.target)}static fromError(t,r,o){if(t===A.UrlElicitationRequired&&o){let i=o;if(i.elicitations)return new Zo(i.elicitations,r)}if(t===A.UnsupportedProtocolVersion&&o){let i=o;if(Array.isArray(i.supported)&&typeof i.requested=="string")return new Bl({supported:i.supported,requested:i.requested},r)}if(t===A.InvalidParams||t===A.ResourceNotFound){let i=o;if(typeof i?.uri=="string"&&(t===A.ResourceNotFound||Object.keys(i).length===1))return new Hl(i.uri,r)}if(t===A.MissingRequiredClientCapability&&o){let i=o;if(i.requiredCapabilities!==null&&typeof i.requiredCapabilities=="object"&&!Array.isArray(i.requiredCapabilities))return new Fl({requiredCapabilities:i.requiredCapabilities},r)}return new Ll(t,r,o)}},Hl=class extends se{static{n(this,"ResourceNotFoundError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(A.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Zo=class extends se{static{n(this,"UrlElicitationRequiredError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(A.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Bl=class extends se{static{n(this,"UnsupportedProtocolVersionError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(A.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Fl=class extends se{static{n(this,"MissingRequiredClientCapabilityError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(A.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},iy=0,sy="private",ay=["tools/call","prompts/get","resources/read"];function cy(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||ay.includes(e))return t;throw new se(A.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}n(cy,"stampResultType");function dy(e,t){let r=oy(t);if(t.resultType!=="complete"||!ny(e))return r===void 0?t:hy(t);let o=t,i=$l(o.ttlMs)?o.ttlMs:py(r),s=Dl(o.cacheScope)?o.cacheScope:my(r),c={...o,ttlMs:i,cacheScope:s};return delete c[ds],c}n(dy,"fillCacheFields");function uy(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(uy,"isPlainObject$3");function ly(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[dr]:t}}:!uy(r)||r[dr]!==void 0?e:{...e,_meta:{...r,[dr]:t}}}n(ly,"stampServerInfoMeta");function py(e){return e!==void 0&&$l(e.ttlMs)?e.ttlMs:iy}n(py,"resolveTtlMs");function my(e){return e!==void 0&&Dl(e.cacheScope)?e.cacheScope:sy}n(my,"resolveCacheScope");function hy(e){let t={...e};return delete t[ds],t}n(hy,"stripCacheHintFallback");var fy=["elicitation/create","sampling/createMessage","roots/list"],Vo;function us(){if(Vo)return Vo;let e=pt();return Vo={request:{"elicitation/create":m({method:g("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":m({method:g("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":m({method:g("roots/list"),params:M({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Vo}n(us,"inputSchemaMaps");function gy(){us()}n(gy,"warmInputSchemaMaps2026");function Gl(e){return fy.includes(e)}n(Gl,"isInputRequestMethod2026");function Zi(e){return Gl(e)?us().request[e]:void 0}n(Zi,"getInputRequestSchema2026");function yy(e){return Gl(e)?us().response[e]:void 0}n(yy,"getInputResponseSchema2026");var ls={"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},Jl={"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 Vl(e){return Object.prototype.hasOwnProperty.call(ls,e)}n(Vl,"hasRequestMethod2026");function Kl(e){return Object.prototype.hasOwnProperty.call(Jl,e)}n(Kl,"hasNotificationMethod2026");function Sy(e){return Object.prototype.hasOwnProperty.call(ls,e)}n(Sy,"hasResultMethod2026");function _y(e){return Vl(e)?pt().dispatchRequestSchemas[e]:void 0}n(_y,"getRequestSchema2026");function wy(e){return Sy(e)?pt().dispatchResultSchemas[e]:void 0}n(wy,"getResultSchema2026");function Ry(e){return Kl(e)?pt().notificationSchemas2026[e]:void 0}n(Ry,"getNotificationSchema2026");var dT=Object.keys(ls),uT=Object.keys(Jl);function Bn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Bn,"isPlainObject$2");function Ln(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}n(Ln,"triState");var by={ok:!1,reason:"not-in-era"},vy=[cr,ur];function Cy(e,t){let r=t,o=!1,i=n(()=>(o||(r={...r},o=!0),r),"copy"),s=t.tools;e==="tools/list"&&Array.isArray(s)&&s.some(a=>Bn(a)&&"execution"in a)&&(i().tools=s.map(a=>{if(!Bn(a)||!("execution"in a))return a;let u={...a};return delete u.execution,u}));let c=t.capabilities;if(Bn(c)&&"tasks"in c){let a={...c};delete a.tasks,i().capabilities=a}return r}n(Cy,"enforceDeletedFields");var ps={era:"2026-07-28",hasRequestMethod:Vl,hasNotificationMethod:Kl,hasInputRequestMethod:n(e=>Zi(e)!==void 0,"hasInputRequestMethod"),validateRequest:n((e,t)=>Ln(_y(e),t),"validateRequest"),validateResult:n((e,t)=>Ln(wy(e),t),"validateResult"),validateNotification:n((e,t)=>Ln(Ry(e),t),"validateNotification"),validateInputRequest:n((e,t)=>Ln(Zi(e),t),"validateInputRequest"),validateInputResponse:n((e,t)=>Ln(yy(e),t),"validateInputResponse"),samplingResultVariant:n(()=>by,"samplingResultVariant"),outboundEnvelope(e){return{[cr]:e.protocolVersion,[Un]:e.clientInfo,[ur]:e.clientCapabilities,...e.logLevel!==void 0&&{[On]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of vy)o in e||t.push({key:o,problem:"missing"});let r=pt().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let o of r.error.issues){let i=o.path.map(String),s=i.length>0?i.join("."):"_meta";i.length===1&&t.some(c=>c.key===s&&c.problem==="missing")||t.push({key:s,problem:o.message})}return t},projectCallToolResult:n(e=>Ul(e),"projectCallToolResult"),inputRequestSchema:Zi,decodeResult(e,t){if(!Bn(t))return{kind:"invalid",error:new re(ie.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new re(ie.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 r!="string")return{kind:"invalid",error:new re(ie.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let c=t.inputRequests,a=Bn(c)?c:{},u=t.requestState;return Object.keys(a).length===0&&typeof u!="string"?{kind:"invalid",error:new re(ie.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:a,...typeof u=="string"&&{requestState:u}}}if(r!=="complete")return{kind:"invalid",error:new re(ie.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=Wl(),i=Object.hasOwn(o,e)?o[e]:void 0;if(i!==void 0){let c=i.safeParse(t);if(!c.success)return{kind:"invalid",error:new re(ie.InvalidResult,`Invalid result for ${e}: ${c.error}`,{method:e})}}let s={...t};return delete s.resultType,{kind:"complete",result:s}},encodeResult(e,t,r){return ly(dy(e,cy(e,Cy(e,t))),r)},encodeErrorCode:n(e=>e===-32002?-32602:e,"encodeErrorCode"),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=pt().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(r=>r.message).join("; ")}`}},Ko;function Wl(){if(Ko)return Ko;let e=pt();return Ko={"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},Ko}n(Wl,"getWireResultSchemas");function Iy(){Wl()}n(Iy,"warmWireResultSchemas2026");var ms="2026-07-28";function Gn(e){return e!==void 0&&xl(e)?ps:cs}n(Gn,"codecForVersion");function bl(e){return e.revision!==void 0?Gn(e.revision).era:e.era==="modern"?ps.era:cs.era}n(bl,"classifiedWireEra");function Yi(e){return Zl.some(t=>t.hasRequestMethod(e))}n(Yi,"isSpecRequestMethod");function Xi(e){return Zl.some(t=>t.hasNotificationMethod(e))}n(Xi,"isSpecNotificationMethod");var Zl=[cs,ps],Ty=gl({AnnotationsSchema:n(()=>Tc,"AnnotationsSchema"),AudioContentSchema:n(()=>id,"AudioContentSchema"),BaseMetadataSchema:n(()=>oc,"BaseMetadataSchema"),BaseRequestParamsSchema:n(()=>Fa,"BaseRequestParamsSchema"),BlobResourceContentsSchema:n(()=>Cc,"BlobResourceContentsSchema"),BooleanSchemaSchema:n(()=>Oi,"BooleanSchemaSchema"),CallToolRequestParamsSchema:n(()=>wd,"CallToolRequestParamsSchema"),CallToolRequestSchema:n(()=>Rd,"CallToolRequestSchema"),CallToolResultSchema:n(()=>Sd,"CallToolResultSchema"),CancelTaskRequestSchema:n(()=>hu,"CancelTaskRequestSchema"),CancelTaskResultSchema:n(()=>fu,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:n(()=>ec,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:n(()=>tc,"CancelledNotificationSchema"),ClientCapabilitiesSchema:n(()=>cc,"ClientCapabilitiesSchema"),ClientNotificationSchema:n(()=>yu,"ClientNotificationSchema"),ClientRequestSchema:n(()=>gu,"ClientRequestSchema"),ClientResultSchema:n(()=>Su,"ClientResultSchema"),ClientTasksCapabilitySchema:n(()=>sc,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:n(()=>_d,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:n(()=>Wd,"CompleteRequestParamsSchema"),CompleteRequestSchema:n(()=>Zd,"CompleteRequestSchema"),CompleteResultSchema:n(()=>Yd,"CompleteResultSchema"),ContentBlockSchema:n(()=>dd,"ContentBlockSchema"),CreateMessageRequestParamsSchema:n(()=>zd,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:n(()=>Md,"CreateMessageRequestSchema"),CreateMessageResultSchema:n(()=>Nd,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:n(()=>jd,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:n(()=>iu,"CreateTaskResultSchema"),CursorSchema:n(()=>Da,"CursorSchema"),DiscoverRequestSchema:n(()=>hc,"DiscoverRequestSchema"),DiscoverResultSchema:n(()=>xi,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:n(()=>xo,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:n(()=>Hd,"ElicitRequestParamsSchema"),ElicitRequestSchema:n(()=>Bd,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:n(()=>Uo,"ElicitRequestURLParamsSchema"),ElicitResultSchema:n(()=>Jd,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:n(()=>Fd,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:n(()=>Gd,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:n(()=>ad,"EmbeddedResourceSchema"),EmptyResultSchema:n(()=>Qa,"EmptyResultSchema"),EnumSchemaSchema:n(()=>Ld,"EnumSchemaSchema"),GetPromptRequestParamsSchema:n(()=>td,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:n(()=>rd,"GetPromptRequestSchema"),GetPromptResultSchema:n(()=>ld,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:n(()=>uu,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:n(()=>lu,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:n(()=>cu,"GetTaskRequestSchema"),GetTaskResultSchema:n(()=>du,"GetTaskResultSchema"),IconSchema:n(()=>rc,"IconSchema"),IconsSchema:n(()=>nc,"IconsSchema"),ImageContentSchema:n(()=>od,"ImageContentSchema"),ImplementationSchema:n(()=>ic,"ImplementationSchema"),InitializeRequestParamsSchema:n(()=>dc,"InitializeRequestParamsSchema"),InitializeRequestSchema:n(()=>uc,"InitializeRequestSchema"),InitializeResultSchema:n(()=>pc,"InitializeResultSchema"),InitializedNotificationSchema:n(()=>mc,"InitializedNotificationSchema"),JSONArraySchema:n(()=>ja,"JSONArraySchema"),JSONObjectSchema:n(()=>Na,"JSONObjectSchema"),JSONRPCErrorResponseSchema:n(()=>qn,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:n(()=>Ei,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:n(()=>Pi,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:n(()=>Nt,"JSONRPCRequestSchema"),JSONRPCResponseSchema:n(()=>Xa,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:n(()=>Ai,"JSONRPCResultResponseSchema"),JSONValueSchema:n(()=>Ma,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:n(()=>Mi,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:n(()=>Ui,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:n(()=>Qc,"ListPromptsRequestSchema"),ListPromptsResultSchema:n(()=>ed,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:n(()=>xc,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:n(()=>Uc,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:n(()=>Ac,"ListResourcesRequestSchema"),ListResourcesResultSchema:n(()=>Ec,"ListResourcesResultSchema"),ListRootsRequestSchema:n(()=>Qd,"ListRootsRequestSchema"),ListRootsResultSchema:n(()=>eu,"ListRootsResultSchema"),ListTasksRequestSchema:n(()=>pu,"ListTasksRequestSchema"),ListTasksResultSchema:n(()=>mu,"ListTasksResultSchema"),ListToolsRequestSchema:n(()=>gd,"ListToolsRequestSchema"),ListToolsResultSchema:n(()=>yd,"ListToolsResultSchema"),LoggingLevelSchema:n(()=>vd,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:n(()=>Td,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:n(()=>kd,"LoggingMessageNotificationSchema"),ModelHintSchema:n(()=>Pd,"ModelHintSchema"),ModelPreferencesSchema:n(()=>Ad,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:n(()=>Dd,"MultiSelectEnumSchemaSchema"),NotificationSchema:n(()=>Ka,"NotificationSchema"),NotificationsParamsSchema:n(()=>Va,"NotificationsParamsSchema"),NumberSchemaSchema:n(()=>Eo,"NumberSchemaSchema"),PaginatedRequestParamsSchema:n(()=>_c,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:n(()=>wc,"PaginatedRequestSchema"),PaginatedResultSchema:n(()=>Rc,"PaginatedResultSchema"),PingRequestSchema:n(()=>fc,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:n(()=>$i,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:n(()=>yc,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:n(()=>Sc,"ProgressNotificationSchema"),ProgressSchema:n(()=>gc,"ProgressSchema"),ProgressTokenSchema:n(()=>$a,"ProgressTokenSchema"),PromptArgumentSchema:n(()=>Yc,"PromptArgumentSchema"),PromptListChangedNotificationSchema:n(()=>pd,"PromptListChangedNotificationSchema"),PromptMessageSchema:n(()=>ud,"PromptMessageSchema"),PromptReferenceSchema:n(()=>Kd,"PromptReferenceSchema"),PromptSchema:n(()=>Xc,"PromptSchema"),ReadResourceRequestParamsSchema:n(()=>qc,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:n(()=>zc,"ReadResourceRequestSchema"),ReadResourceResultSchema:n(()=>Mc,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:n(()=>Ha,"RelatedTaskMetadataSchema"),RequestIdSchema:n(()=>Ya,"RequestIdSchema"),RequestMetaSchema:n(()=>Ba,"RequestMetaSchema"),RequestSchema:n(()=>Ja,"RequestSchema"),ResourceContentsSchema:n(()=>bc,"ResourceContentsSchema"),ResourceLinkSchema:n(()=>cd,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:n(()=>Nc,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:n(()=>Oc,"ResourceRequestParamsSchema"),ResourceSchema:n(()=>kc,"ResourceSchema"),ResourceTemplateReferenceSchema:n(()=>Vd,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:n(()=>Pc,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:n(()=>Wc,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:n(()=>Zc,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:n(()=>Wa,"ResultMetaObjectSchema"),ResultSchema:n(()=>Za,"ResultSchema"),RoleSchema:n(()=>Ic,"RoleSchema"),RootSchema:n(()=>Xd,"RootSchema"),RootsListChangedNotificationSchema:n(()=>tu,"RootsListChangedNotificationSchema"),SamplingContentSchema:n(()=>Ud,"SamplingContentSchema"),SamplingMessageContentBlockSchema:n(()=>Od,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:n(()=>qd,"SamplingMessageSchema"),ServerCapabilitiesSchema:n(()=>lc,"ServerCapabilitiesSchema"),ServerNotificationSchema:n(()=>wu,"ServerNotificationSchema"),ServerRequestSchema:n(()=>_u,"ServerRequestSchema"),ServerResultSchema:n(()=>Ru,"ServerResultSchema"),ServerTasksCapabilitySchema:n(()=>ac,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:n(()=>Cd,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:n(()=>Id,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:n(()=>$d,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:n(()=>Ao,"StringSchemaSchema"),SubscribeRequestParamsSchema:n(()=>jc,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:n(()=>$c,"SubscribeRequestSchema"),SubscriptionFilterSchema:n(()=>Hc,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:n(()=>Gc,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:n(()=>Jc,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:n(()=>Bc,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:n(()=>Fc,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:n(()=>Vc,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:n(()=>Kc,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:n(()=>Ga,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:n(()=>ru,"TaskCreationParamsSchema"),TaskMetadataSchema:n(()=>La,"TaskMetadataSchema"),TaskSchema:n(()=>ou,"TaskSchema"),TaskStatusNotificationParamsSchema:n(()=>su,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:n(()=>au,"TaskStatusNotificationSchema"),TaskStatusSchema:n(()=>nu,"TaskStatusSchema"),TextContentSchema:n(()=>nd,"TextContentSchema"),TextResourceContentsSchema:n(()=>vc,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:n(()=>ji,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:n(()=>zi,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:n(()=>md,"ToolAnnotationsSchema"),ToolChoiceSchema:n(()=>Ed,"ToolChoiceSchema"),ToolExecutionSchema:n(()=>hd,"ToolExecutionSchema"),ToolListChangedNotificationSchema:n(()=>bd,"ToolListChangedNotificationSchema"),ToolResultContentSchema:n(()=>xd,"ToolResultContentSchema"),ToolSchema:n(()=>fd,"ToolSchema"),ToolUseContentSchema:n(()=>sd,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:n(()=>Dc,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:n(()=>Lc,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:n(()=>Ni,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:n(()=>qi,"UntitledSingleSelectEnumSchemaSchema")});var Yl=n(e=>Nt.safeParse(e).success,"isJSONRPCRequest"),Xl=n(e=>Pi.safeParse(e).success,"isJSONRPCNotification"),ns=n(e=>Ai.safeParse(e).success,"isJSONRPCResultResponse"),Ql=n(e=>qn.safeParse(e).success,"isJSONRPCErrorResponse");var Fn=-32020,lT=[{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:[A.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:[Fn,A.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:[A.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:[A.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:[A.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:[Fn],conformance:["http-header-validation"],rationale:"SEP-2243 standard `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 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. 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:[A.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:[Fn],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."}],pT={[A.ParseError]:400,[A.InvalidRequest]:400,[A.MethodNotFound]:404,[A.UnsupportedProtocolVersion]:400,[A.MissingRequiredClientCapability]:400,[Fn]:400};function hs(e,t){return Oa(e,t)}n(hs,"parseSchema");function Hn(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}n(Hn,"shapeKeys");function os(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}n(os,"isStandardSchema");var vl=!1,is="draft-2020-12";function ky(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:is});else if(r.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().");vl||(vl=!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.")),o=Ci(e,{target:is,io:t})}else throw new Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return o.type!==void 0?o:ep(o)?{type:"object",...o}:o;if(o.type!==void 0&&o.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(o.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...o}}n(ky,"standardSchemaToJsonSchema");function ep(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every(o=>o!==null&&typeof o=="object"&&(o.type==="object"||ep(o)))}return!1}n(ep,"isProvablyObjectShapedRoot");function Py(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}n(Py,"formatIssue");async function Qi(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(o=>Py(o)).join(", ")}:{success:!0,data:r.value}}n(Qi,"validateStandardSchema");function Ay(e){let t=Ci(e,{target:is,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}n(Ay,"zodEmittedPattern");var Ey=/\\\.\\d\{(\d+)\}/;function xy(e){let t=Ey.exec(e),r=[void 0,-1,0];return t&&r.push(Number(t[1])),[!1,!0].flatMap(o=>[!1,!0].flatMap(i=>r.map(s=>En.datetime({local:o,offset:i,precision:s}))))}n(xy,"datetimeReferenceSchemas");function Uy(e,t){let r;switch(e){case"email":r=[qa()];break;case"uri":r=[za()];break;case"date":r=[En.date()];break;case"date-time":r=xy(t);break}return new Set(r.map(o=>Ay(o)).filter(o=>o!==void 0))}n(Uy,"referencePatternsForFormat");function Oy(e,t,r){return r!=="zod"?!0:Uy(e,t).has(t)}n(Oy,"isLibraryFormatPattern");function Jn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(Jn,"isJsonObject");function qy(e){try{return ky(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new se(A.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}n(qy,"convertStandardElicitationSchema");var zy=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function fs(e){return zy.has(e)||e.startsWith("x-")}n(fs,"isAnnotationOnlyJsonSchemaKeyword");var My=new Set(["$schema",...Object.keys(xo.shape.requestedSchema.shape)]),Cl={string:Hn([Ao,qi,zi,Mi]),number:Hn([Eo]),integer:Hn([Eo]),boolean:Hn([Oi]),array:Hn([Ni,ji])},Ny=new Set(Ao.shape.format.unwrap().options);function jy(e,t,r,o){if(!Jn(e))return e;let i=typeof e.type=="string"&&Object.hasOwn(Cl,e.type)?Cl[e.type]:void 0;if(i===void 0)return e;let s={};for(let[c,a]of Object.entries(e))i.has(c)||fs(c)?s[c]=a:c==="pattern"&&e.type==="string"&&typeof e.format=="string"?Ny.has(e.format)?(typeof a!="string"||!Oy(e.format,a,r))&&o.push(`${t}.${c}`):s[c]=a:o.push(`${t}.${c}`);return s}n(jy,"walkProperty");function $y(e,t){let r={},o=[];for(let[i,s]of Object.entries(e))i==="properties"&&Jn(s)?r[i]=Object.fromEntries(Object.entries(s).map(([c,a])=>[c,jy(a,`properties.${c}`,t,o)])):My.has(i)?r[i]=s:fs(i)||o.push(i);if(o.length>0)throw new se(A.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}n($y,"walkRequestedSchema");function Dy(e,t){if(!Jn(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!hs($i,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}n(Dy,"describeUnsupportedProperties");function ss(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,i)=>ss(o,t[i],`${r}[${i}]`)):!Jn(e)||!Jn(t)?[]:Object.entries(e).flatMap(([o,i])=>{let s=r?`${r}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?ss(i,t[o],s):fs(o)?[]:[s]})}n(ss,"findDroppedConstraintPaths");function Ly(e){if(!os(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=$y(qy(e.requestedSchema),t),o=hs(xo.shape.requestedSchema,r);if(!o.success)throw new se(A.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${Dy(r,o.error.message)}`);let i=ss(r,o.data);if(i.length>0)throw new se(A.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${i.join(", ")}`);let s=(o.data.required??[]).filter(c=>!Object.prototype.hasOwnProperty.call(o.data.properties,c));if(s.length>0)throw new se(A.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${s.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}n(Ly,"normalizeElicitInputParams");function Hy(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState=="string";if(!t&&!r)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}}}n(Hy,"buildInputRequired");var mT=Object.assign(Hy,{elicit(e){try{return{method:"elicitation/create",params:Ly(e)}}catch(t){throw t instanceof se?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 By=["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"],Fy={IdJagTokenExchangeResponseSchema:Di,OAuthClientInformationFullSchema:jt,OAuthClientInformationSchema:zn,OAuthClientMetadataSchema:vu,OAuthClientRegistrationErrorSchema:Cu,OAuthErrorResponseSchema:Oo,OAuthMetadataSchema:mr,OAuthProtectedResourceMetadataSchema:pr,OAuthTokenRevocationRequestSchema:Iu,OAuthTokensSchema:at,OpenIdProviderDiscoveryMetadataSchema:hr,OpenIdProviderMetadataSchema:bu},tp={},rp={};function np(e,t){let r=e.slice(0,-6);tp[r]=t,rp[r]=o=>t.safeParse(o).success}n(np,"register");for(let e of By)np(e,Ty[e]);for(let[e,t]of Object.entries(Fy))np(e,t);var Gy=Object.freeze(tp),Jy=Object.freeze(rp);function Vy(e){switch(e){case"initialize":case"notifications/initialized":return Gn(void 0);case"server/discover":return Gn(ms);default:return}}n(Vy,"bootstrapOutboundCodec");var op=6e4,Ky=[cr,Un,ur,On],Wy=["inputResponses","requestState"];function Il(e,t){let r=e.params;if(!es(r))return{message:e,lifted:{}};let o=r._meta,i=es(o)?Ky.filter(u=>u in o):[],s=t==="request"?Wy.filter(u=>u in r):[];if(i.length===0&&s.length===0)return{message:e,lifted:{}};let c={},a={...r};if(i.length>0&&es(o)){let u={},p={...o};for(let h of i)u[h]=o[h],delete p[h];c.envelope=u,Object.keys(p).length>0?a._meta=p:delete a._meta}for(let u of s)u==="inputResponses"&&(c.inputResponses=a[u]),u==="requestState"&&(c.requestState=a[u]),delete a[u];return{message:{...e,params:a},lifted:c}}n(Il,"liftWireOnlyMaterial");function Tl(e,t){let r=e.validateResult(t,void 0);if(!(!r.ok&&r.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(o){let i=e.validateResult(t,o);return i.ok?{value:i.value}:{issues:[{message:i.reason==="invalid"?i.message:`not-in-era: ${t}`}]}}}}}n(Tl,"codecResultValidator");function ip(e){return()=>e}n(ip,"requestStateAccessor");var Zy=ip(void 0),Yy,Xy=class{static{n(this,"Protocol")}_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{Yy=n((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??ki,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 r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new re(ie.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&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,o,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new re(ie.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});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 r=this.transport?.onerror;this._transport.onerror=i=>{r?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),ns(i)||Ql(i)?this._onresponse(i):Yl(i)?this._onrequest(i,s):Xl(i)?this._onnotification(i,s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},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 o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new re(ie.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let o of e.values())o(r);for(let o of t.values())o.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=Il(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let c=bl(t.classification);if(c!==o.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${c} but this instance serves ${o.era}`));return}}if(Xi(r.method)&&!o.hasNotificationMethod(r.method))return;let i=this._notificationHandlers.get(r.method),s=this.fallbackNotificationHandler;i===void 0&&s===void 0||Promise.resolve().then(()=>i===void 0?s(r):i(r,o)).catch(c=>this._onerror(new Error(`Uncaught error in notification handler: ${c}`)))}_onrequest(e,t){let{message:r,lifted:o}=Il(e,"request"),i=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 s=this._transport,c=n((w,C,U)=>{let O={jsonrpc:"2.0",id:r.id,error:{code:w,message:C,...U!==void 0&&{data:U}}};s?.send(O).catch(L=>this._onerror(new Error(`Failed to send an error response: ${L}`)))},"sendErrorResponse");if(t?.classification!==void 0){let w=bl(t.classification);if(w!==i.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${w} but this instance serves ${i.era}`));let C=t.classification.revision??w;c(A.UnsupportedProtocolVersion,`Unsupported protocol version: ${C}`,{supported:this._supportedProtocolVersions,requested:C});return}}if(Yi(r.method)&&!i.hasRequestMethod(r.method)){c(A.MethodNotFound,"Method not found");return}let a=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(a===void 0){c(A.MethodNotFound,"Method not found");return}let u=i.checkInboundEnvelope(o);if(u!==void 0){c(A.InvalidParams,u);return}let p=n((w,C)=>this._notificationViaCodec(this._resolveOutboundCodec(w.method),w,{...C,relatedRequestId:r.id}),"sendNotification"),h=n((w,C,U)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(w.method),w,C,{...U,relatedRequestId:r.id}),"sendRequest"),f=new AbortController;this._requestHandlerAbortControllers.set(r.id,f);let y=o.inputResponses===void 0?void 0:Qy(o.inputResponses),S={sessionId:s?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...y!==void 0&&{inputResponses:y.accepted},...y!==void 0&&y.droppedKeys.length>0&&{droppedInputResponseKeys:y.droppedKeys},requestState:o.requestState===void 0?Zy:ip(o.requestState),signal:f.signal,send:n(((w,C,U)=>{let O=this._resolveOutboundCodec(w.method);if(this._assertOutboundRequestInEra(O,w.method),os(C))return h(w,C,U);let L=Tl(O,w.method);if(L===void 0)throw new TypeError(`'${w.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return h(w,L,C)}),"send"),notify:p},http:t?.authInfo?{authInfo:t.authInfo}:void 0},k=this.buildContext(S,t);Promise.resolve().then(()=>a(r,k)).then(async w=>{if(f.signal.aborted)return;let C;try{C=i.encodeResult(r.method,w,this._outboundServerInfo())}catch(O){this._onerror(new Error(`Failed to encode result for ${r.method}: ${O}`)),c(A.InternalError,"Internal error");return}let U={result:C,jsonrpc:"2.0",id:r.id};await s?.send(U)},async w=>{if(f.signal.aborted)return;let C=Number.isSafeInteger(w.code)?w.code:A.InternalError,U={jsonrpc:"2.0",id:r.id,error:{code:i.encodeErrorCode(C),message:w.message??"Internal error",...w.data!==void 0&&{data:w.data}}};await s?.send(U)}).catch(w=>this._onerror(new Error(`Failed to send response: ${w}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===f&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,o=Number(t),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),c=this._timeoutInfo.get(o);if(c&&s&&c.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(a);return}i(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===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),ns(e)?r(e):r(se.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let o=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(o,e.method),os(t))return this._requestWithSchemaViaCodec(o,e,t,r);let i=Tl(o,e.method);if(i===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(o,e,i,t)}_negotiatedWireCodec(){return Gn(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Vy(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Yi(t)&&!e.hasRequestMethod(t))throw new re(ie.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let o=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r)}_requestWithSchemaViaCodec(e,t,r,o){let{relatedRequestId:i,resumptionToken:s,onresumptiontoken:c,headers:a}=o??{},u=Date.now(),p,h;return new Promise((f,y)=>{let S=n(G=>{y(G)},"earlyReject");if(!this._transport){S(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(G){S(G);return}if(o?.signal?.aborted){let G=o.signal.reason;throw G instanceof re?G:new re(ie.RequestTimeout,String(G))}let k=e.era===ms&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,w=this._requestMessageId++;h=w;let C={...t,jsonrpc:"2.0",id:w};o?.onprogress&&(this._progressHandlers.set(w,o.onprogress),C.params={...t.params,_meta:{...t.params?._meta,progressToken:w}});let U=this._envelopeOutbound(C),O=!1,L=n(G=>{O||(this._progressHandlers.delete(w),k===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(G)}}),{relatedRequestId:i,resumptionToken:s,onresumptiontoken:c}).catch(V=>this._onerror(new Error(`Failed to send cancellation: ${V}`))):k.abort(),y(G instanceof re?G:new re(ie.RequestTimeout,String(G))))},"cancel");this._responseHandlers.set(w,G=>{if(o?.signal?.aborted)return;if(O=!0,G instanceof Error)return y(G);let V;try{V=e.decodeResult(t.method,G.result)}catch(oe){return y(oe instanceof Error?oe:new Error(String(oe)))}if(V.kind==="invalid")return y(V.error);if(V.kind==="input_required"){if(o?.allowInputRequired===!0)return f(eS(V));let oe={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:u,retry:n((Me,D)=>this._requestWithSchemaViaCodec(e,Me===void 0?{method:t.method}:{method:t.method,params:Me},r,D),"retry")};return f(this._resolveNonCompleteResult(V,oe))}let Be=V.result;Qi(r,Be).then(oe=>{oe.success?f(oe.data):y(new re(ie.InvalidResult,`Invalid result for ${t.method}: ${oe.error}`))},y)}),p=n(()=>L(o?.signal?.reason),"onAbort"),o?.signal?.addEventListener("abort",p,{once:!0});let F=o?.timeout??op,ee=n(()=>L(new re(ie.RequestTimeout,"Request timed out",{timeout:F})),"timeoutHandler");this._setupTimeout(w,F,o?.maxTotalTimeout,ee,o?.resetTimeoutOnProgress??!1),this._transport.send(U,{relatedRequestId:i,resumptionToken:s,onresumptiontoken:c,headers:a,requestSignal:k?.signal}).catch(G=>{this._progressHandlers.delete(w),y(G)})}).finally(()=>{p&&o?.signal?.removeEventListener("abort",p),h!==void 0&&(this._responseHandlers.delete(h),this._cleanupTimeout(h))})}async notification(e,t){return this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new re(ie.NotConnected,"Not connected");if(Xi(t.method)&&!e.hasNotificationMethod(t.method))throw new re(ie.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 o=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId){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(o,r).catch(i=>this._onerror(i))});return}await this._transport.send(o,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let o;if(typeof t=="function"){if(!Yi(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=n((i,s)=>{let c=this._negotiatedWireCodec(),a=c.validateRequest(e,i);if(!a.ok&&a.reason==="not-in-era"&&(a=c.validateInputRequest(e,i)),!a.ok)throw a.reason==="not-in-era"?new se(A.InternalError,`No wire schema for ${e} in the resolved era`):new Error(a.message);return Promise.resolve(t(a.value,s))},"stored")}else if(r)o=n(async(i,s)=>{let c=await Qi(t.params,{...i.params});if(!c.success)throw new se(A.InvalidParams,`Invalid params for ${e}: ${c.error}`);return r(c.data,s)},"stored");else throw new TypeError("setRequestHandler: handler is required");this._requestHandlers.set(e,this._wrapHandler(e,o))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.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,r){if(typeof t=="function"){if(!Xi(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,i)=>{let s=i.validateNotification(e,o);if(!s.ok)throw s.reason==="not-in-era"?new se(A.InternalError,`No wire schema for ${e} in the resolved era`):new Error(s.message);return Promise.resolve(t(s.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async o=>{let i=await Qi(t.params,{...o.params});if(!i.success)throw new se(A.InvalidParams,`Invalid params for notification ${e}: ${i.error}`);await r(i.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function es(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(es,"isPlainObject$1");function kl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(kl,"isPlainObject");function Qy(e){let t={},r=[];if(!kl(e))return{accepted:t,droppedKeys:r};for(let[o,i]of Object.entries(e)){if(!kl(i)||"method"in i||"result"in i){r.push(o);continue}t[o]=i}return{accepted:t,droppedKeys:r}}n(Qy,"partitionInputResponses");function eS(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}n(eS,"manualInputRequiredValue");var tS=fl((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=i;function i(a){if(!a)throw new TypeError("argument string is required");var u=typeof a=="object"?s(a):a;if(typeof u!="string")throw new TypeError("argument string is required to be a string");var p=u.indexOf(";"),h=p!==-1?u.slice(0,p).trim():u.trim();if(!o.test(h))throw new TypeError("invalid media type");var f=new c(h.toLowerCase());if(p!==-1){var y,S,k;for(t.lastIndex=p;S=t.exec(u);){if(S.index!==p)throw new TypeError("invalid parameter format");p+=S[0].length,y=S[1].toLowerCase(),k=S[2],k.charCodeAt(0)===34&&(k=k.slice(1,-1),k.indexOf("\\")!==-1&&(k=k.replace(r,"$1"))),f.parameters[y]=k}if(p!==u.length)throw new TypeError("invalid parameter format")}return f}n(i,"parse");function s(a){var u;if(typeof a.getHeader=="function"?u=a.getHeader("content-type"):typeof a.headers=="object"&&(u=a.headers&&a.headers["content-type"]),typeof u!="string")throw new TypeError("content-type header is missing from object");return u}n(s,"getcontenttype");function c(a){this.parameters=Object.create(null),this.type=a}n(c,"ContentType")})),hT=yl(tS(),1);var rS=10*1024*1024;function gs(){as(),pt(),Wg(),gy(),Iy()}n(gs,"preloadSchemas");var TT=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");var nS=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,oS=[0,31,28,31,30,31,30,31,31,30,31,30,31],iS=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,sS=/^(?=.{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,aS=/^(?:[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,cS=/^(?:(?:[^\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,dS=/^(?:(?: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,uS=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,lS=/^(?:\/(?:[^~/]|~0|~1)*)*$/,pS=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,mS=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,hS=n(e=>{if(e[0]==='"')return!1;let[t,r,...o]=e.split("@");return!t||!r||o.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},"EMAIL"),fS=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,gS=/^((([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,yS=n(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)),"DURATION");function De(e){return e.test.bind(e)}n(De,"bind");var kT={date:sp,time:ap.bind(void 0,!1),"date-time":wS,duration:yS,uri:vS,"uri-reference":De(aS),"uri-template":De(cS),url:De(dS),email:hS,hostname:De(sS),ipv4:De(fS),ipv6:De(gS),regex:IS,uuid:De(uS),"json-pointer":De(lS),"json-pointer-uri-fragment":De(pS),"relative-json-pointer":De(mS)};function SS(e){return e%4===0&&(e%100!==0||e%400===0)}n(SS,"isLeapYear");function sp(e){let t=e.match(nS);if(!t)return!1;let r=+t[1],o=+t[2],i=+t[3];return o>=1&&o<=12&&i>=1&&i<=(o==2&&SS(r)?29:oS[o])}n(sp,"date");function ap(e,t){let r=t.match(iS);if(!r)return!1;let o=+r[1],i=+r[2],s=+r[3],c=!!r[5];return(o<=23&&i<=59&&s<=59||o==23&&i==59&&s==60)&&(!e||c)}n(ap,"time");var _S=/t|\s/i;function wS(e){let t=e.split(_S);return t.length==2&&sp(t[0])&&ap(!0,t[1])}n(wS,"date_time");var RS=/\/|:/,bS=/^(?:[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 vS(e){return RS.test(e)&&bS.test(e)}n(vS,"uri");var CS=/[^\\]\\Z/;function IS(e){if(CS.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}n(IS,"regex");gs();var cp=!1;var ys;ys=globalThis.crypto;async function kS(e){return(await ys).getRandomValues(new Uint8Array(e))}n(kS,"getRandomValues");async function PS(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await kS(e-o.length);for(let s of i)s<r&&(o+=t[s%t.length])}return o}n(PS,"random");async function AS(e){return await PS(e)}n(AS,"generateVerifier");async function ES(e){let t=await(await ys).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(ES,"generateChallenge");async function Ss(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await AS(e),r=await ES(t);return{code_verifier:t,code_challenge:r}}n(Ss,"pkceChallenge");var Vn=class extends Error{static{n(this,"OAuthClientFlowError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return ve(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 ve(this,e)}constructor(e){super(e),this.name=new.target.name,Dt(this,new.target)}},vs=class extends Vn{static{n(this,"IssuerMismatchError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 \xA73.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`),this.kind=e,this.expected=t,this.received=r}},xS=class extends Vn{static{n(this,"RegistrationRejectedError")}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}},pp=class extends Vn{static{n(this,"InsecureTokenEndpointError")}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 / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},_s=class extends Vn{static{n(this,"AuthorizationServerMismatchError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server changed between redirect and callback (redirected to ${JSON.stringify(e)}, callback resolved ${JSON.stringify(t)}); refusing to send authorization_code/code_verifier to a different token endpoint`),this.recordedIssuer=e,this.currentIssuer=t}},hk=class extends Vn{static{n(this,"InsufficientScopeError")}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 dp(e,t,r){if(e!==void 0)return e.issuer===void 0?(r?.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):mp(e.issuer,t)?e:void 0}n(dp,"discardIfIssuerMismatch");function mp(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}n(mp,"issuersMatch");var fk=class extends Error{static{n(this,"UnauthorizedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return ve(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 ve(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",Dt(this,new.target)}};function hp(e){return e?.authorization_response_iss_parameter_supported===!0}n(hp,"isIssParameterSupported");function fp({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new vs("authorization_response",t,void 0);return}if(e!==t)throw new vs("authorization_response",t,e)}}n(fp,"validateAuthorizationResponseIssuer");function US(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(US,"isClientAuthMethod");var ws="code",Rs="S256";function OS(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&US(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}n(OS,"selectClientAuthMethod");function qS(e,t,r,o){let{client_id:i,client_secret:s}=t;switch(e){case"client_secret_basic":zS(i,s,r);return;case"client_secret_post":MS(i,s,o);return;case"none":NS(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(qS,"applyClientAuthentication");function zS(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}n(zS,"applyBasicAuth");function MS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(MS,"applyPostAuth");function NS(e,t){t.set("client_id",e)}n(NS,"applyPublicAuth");function gp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}n(gp,"isLoopbackHost");function jS(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!gp(t.hostname))throw new pp(t.href);return t}n(jS,"assertSecureTokenEndpoint");function $S(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||gp(r.hostname))return"native"}return"web"}n($S,"deriveApplicationType");function DS(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??$S(t.redirect_uris)}}n(DS,"resolveClientMetadata");async function up(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Oo.parse(JSON.parse(r));return mt.fromResponse(o)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new mt(ue.ServerError,i)}}n(up,"parseErrorResponse");async function Cs(e,t){try{return await bs(e,t)}catch(r){if(r instanceof mt){if(r.code===ue.InvalidClient||r.code===ue.UnauthorizedClient)return await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await bs(e,t);if(r.code===ue.InvalidGrant)return await e.invalidateCredentials?.("tokens"),await bs(e,t)}throw r}}n(Cs,"auth");function LS(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:o,clientMetadata:i}=e,s=t||r?.scopes_supported?.join(" ")||i.scope;return s&&o?.scopes_supported?.includes("offline_access")&&!s.split(" ").includes("offline_access")&&i.grant_types?.includes("refresh_token")&&(s=`${s} offline_access`),s}n(LS,"determineScope");async function bs(e,{serverUrl:t,authorizationCode:r,iss:o,scope:i,resourceMetadataUrl:s,fetchFn:c,skipIssuerMetadataValidation:a,forceReauthorization:u}){let p=DS(e),h=await e.discoveryState?.(),f,y,S,k,w=s;if(!w&&h?.resourceMetadataUrl&&(w=new URL(h.resourceMetadataUrl)),h?.authorizationServerUrl){if(y=h.authorizationServerUrl,f=h.resourceMetadata,S=h.authorizationServerMetadata??await wp(y,{fetchFn:c,skipIssuerValidation:a}),!f)try{f=await Sp(t,{resourceMetadataUrl:w},c)}catch(D){if(D instanceof TypeError)throw D}(S!==h.authorizationServerMetadata||f!==h.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(y),resourceMetadataUrl:w?.toString(),resourceMetadata:f,authorizationServerMetadata:S})}else{let D=await VS(t,{resourceMetadataUrl:w,fetchFn:c,skipIssuerMetadataValidation:a});y=D.authorizationServerUrl,S=D.authorizationServerMetadata,f=D.resourceMetadata,k={authorizationServerUrl:String(y),resourceMetadataUrl:w?.toString(),resourceMetadata:f,authorizationServerMetadata:S}}let C=S?.issuer??String(y),U={issuer:C};if(await e.saveAuthorizationServerUrl?.(C),r!==void 0){let D=h?.authorizationServerMetadata?.issuer??h?.authorizationServerUrl;if(D===void 0){if(e.saveDiscoveryState!==void 0)throw new _s("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",C);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(!mp(D,C))throw new _s(D,C)}k&&await e.saveDiscoveryState?.(k);let O=await HS(t,e,f);O&&await e.saveResourceUrl?.(String(O));let L=LS({requestedScope:i,resourceMetadata:f,authServerMetadata:S,clientMetadata:e.clientMetadata}),F=await Promise.resolve(e.clientInformation(U)),ee=dp(F,C,{canPersistStamp:e.saveClientInformation!==void 0});if(ee===void 0&&F?.issuer&&e.saveClientInformation===void 0)throw new _s(F.issuer,C);if(ee&&ee.issuer===void 0&&(ee={...ee,issuer:C},await e.saveClientInformation?.(ee,U)),!ee){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let D=S?.client_id_metadata_document_supported===!0,Ee=e.clientMetadataUrl;if(Ee&&!Is(Ee))throw new mt(ue.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${Ee}`);if(D&&Ee)ee={client_id:Ee,issuer:C},await e.saveClientInformation?.(ee,U);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");ee={...await XS(y,{metadata:S,clientMetadata:p,scope:L,fetchFn:c}),issuer:C},await e.saveClientInformation(ee,U)}}let G=!e.redirectUrl;if(r!==void 0||G){r!==void 0&&fp({iss:o,expectedIssuer:S?.issuer,issParameterSupported:hp(S)});let D=await YS(e,y,{metadata:S,resource:O,authorizationCode:r,iss:o,scope:L,fetchFn:c});return await e.saveTokens({...D,issuer:C},U),"AUTHORIZED"}let V=dp(await e.tokens(U),C);if(V&&V.issuer===void 0&&(V={...V,issuer:C},await e.saveTokens(V,U)),V?.refresh_token&&!u)try{let D=await ZS(y,{metadata:S,clientInformation:ee,refreshToken:V.refresh_token,resource:O,addClientAuthentication:e.addClientAuthentication,fetchFn:c});return await e.saveTokens({...D,issuer:C},U),"AUTHORIZED"}catch(D){if(D instanceof pp||!(!(D instanceof mt)||D.code===ue.ServerError))throw D}let Be=e.state?await e.state():void 0,{authorizationUrl:oe,codeVerifier:Me}=await KS(y,{metadata:S,clientInformation:ee,state:Be,redirectUrl:e.redirectUrl,scope:L,resource:O});return await e.saveCodeVerifier(Me),await e.redirectToAuthorization(oe),"REDIRECT"}n(bs,"authInternal");function Is(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(Is,"isHttpsUrl");async function HS(e,t,r){let o=Al(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!El({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}n(HS,"selectResourceURL");function yp(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r?.toLowerCase()!=="bearer"||!o)return{};let i=Yo(e,"resource_metadata")||void 0,s;if(i)try{s=new URL(i)}catch{}let c=Yo(e,"scope")||void 0,a=Yo(e,"error")||void 0,u=Yo(e,"error_description")||void 0;return{resourceMetadataUrl:s,scope:c,error:a,errorDescription:u}}n(yp,"extractWWWAuthenticateParams");function Yo(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),i=r.match(o);if(i){let s=i[1]||i[2];if(s)return s}return null}n(Yo,"extractFieldFromWwwAuth");async function Sp(e,t,r=fetch){let o=await GS(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.text?.().catch(()=>{}),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.text?.().catch(()=>{}),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return pr.parse(await o.json())}n(Sp,"discoverOAuthProtectedResourceMetadata");async function _p(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(!(o instanceof TypeError)||!cp)throw o;if(t)try{return await r(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}n(_p,"fetchWithCorsRetry");function BS(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(BS,"buildWellKnownPath");async function lp(e,t,r=fetch){return await _p(e,{"MCP-Protocol-Version":t},r)}n(lp,"tryMetadataDiscovery");function FS(e,t){return e?t==="/"?!1:e.status>=400&&e.status<500||e.status===502:!0}n(FS,"shouldAttemptFallback");async function GS(e,t,r,o){let i=new URL(e),s=o?.protocolVersion??Po,c;if(o?.metadataUrl)c=new URL(o.metadataUrl);else{let u=BS(t,i.pathname);c=new URL(u,o?.metadataServerUrl??i),c.search=i.search}let a=await lp(c,s,r);return!o?.metadataUrl&&FS(a,i.pathname)&&(a=await lp(new URL(`/.well-known/${t}`,i),s,r)),a}n(GS,"discoverMetadataWithFallback");function JS(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let i=t.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:"oidc"},{url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}n(JS,"buildDiscoveryUrls");async function wp(e,{fetchFn:t=fetch,protocolVersion:r=Po,skipIssuerValidation:o=!1}={}){let i={"MCP-Protocol-Version":r,Accept:"application/json"},s=JS(e);for(let{url:c,type:a}of s){let u=await _p(c,i,t);if(!u)continue;if(!u.ok){if(await u.text?.().catch(()=>{}),u.status>=400&&u.status<500||u.status===502)continue;throw new Error(`HTTP ${u.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${c}`)}let p=a==="oauth"?mr.parse(await u.json()):hr.parse(await u.json());if(!o){let h=typeof e=="string"?e:e.href;if(!(p.issuer===h||h.endsWith("/")&&p.issuer===h.slice(0,-1)))throw new vs("metadata",h,p.issuer)}return p}}n(wp,"discoverAuthorizationServerMetadata");async function VS(e,t){let r,o;try{r=await Sp(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch(s){if(s instanceof TypeError)throw s}o||(o=String(new URL("/",e)));let i=await wp(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(VS,"discoverOAuthServerInfo");async function KS(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:i,state:s,resource:c}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(ws))throw new Error(`Incompatible auth server: does not support response type ${ws}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Rs))throw new Error(`Incompatible auth server: does not support code challenge method ${Rs}`)}else a=new URL("/authorize",e);let u=await Ss(),p=u.code_verifier,h=u.code_challenge;return a.searchParams.set("response_type",ws),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",h),a.searchParams.set("code_challenge_method",Rs),a.searchParams.set("redirect_uri",String(o)),s&&a.searchParams.set("state",s),i&&a.searchParams.set("scope",i),i?.split(" ").includes("offline_access")&&a.searchParams.append("prompt","consent"),c&&a.searchParams.set("resource",c.href),{authorizationUrl:a,codeVerifier:p}}n(KS,"startAuthorization");function WS(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(WS,"prepareAuthorizationCodeRequest");async function Rp(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:i,resource:s,fetchFn:c}){let a=jS(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});s&&r.set("resource",s.href),i?await i(u,r,a,t):o&&qS(OS(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let p=await(c??fetch)(a,{method:"POST",headers:u,body:r});if(!p.ok)throw await up(p);let h=await p.json();try{return at.parse(h)}catch(f){throw typeof h=="object"&&h!==null&&"error"in h?await up(JSON.stringify(h)):f}}n(Rp,"executeTokenRequest");async function ZS(e,{metadata:t,clientInformation:r,refreshToken:o,resource:i,addClientAuthentication:s,fetchFn:c}){return{refresh_token:o,...await Rp(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:s,resource:i,fetchFn:c})}}n(ZS,"refreshAuthorization");async function YS(e,t,{metadata:r,resource:o,authorizationCode:i,iss:s,scope:c,fetchFn:a}={}){i!==void 0&&fp({iss:s,expectedIssuer:r?.issuer,issParameterSupported:hp(r)});let u=c??e.clientMetadata.scope,p;if(e.prepareTokenRequest&&(p=await e.prepareTokenRequest(u)),!p){if(!i)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");p=WS(i,await e.codeVerifier(),e.redirectUrl)}let h=await e.clientInformation({issuer:r?.issuer??String(t)});return Rp(t,{metadata:r,tokenRequestParams:p,clientInformation:h??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:a})}n(YS,"fetchToken");async function XS(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:i}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);let c={...r,...o===void 0?{}:{scope:o}},a=await(i??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!a.ok)throw new xS({status:a.status,body:await a.text(),submittedMetadata:c});return jt.parse(await a.json())}n(XS,"registerClient");var gk=class extends Error{static{n(this,"SseError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return ve(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 ve(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,Dt(this,new.target)}};function QS(e){let t=Nt.safeParse(e);return t.success?t.data.id:void 0}n(QS,"parseJsonRpcRequestId");function bp(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return QS(t)}catch{return}}n(bp,"readJsonRpcRequestIdFromBody");function Xo(e){return qn.parse({jsonrpc:lr,...e.id===void 0?{}:{id:e.id},error:{code:e.error.code,message:e.error.message,...e.error.data===void 0?{}:{data:e.error.data}}})}n(Xo,"jsonRpcErrorResponse");function vp(e){return new Zo([Uo.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(vp,"urlElicitationRequiredError");var ei=l.record(l.string(),l.unknown()),e_=l.record(l.string(),l.unknown()),ft=l.array(l.string().min(1)).min(1).optional(),t_=l.object({name:l.string().min(1),description:l.string().min(1).optional(),annotations:e_.optional(),_meta:ei.optional(),roles:ft,groups:ft,public:l.boolean().optional()}).strict(),r_=l.object({name:l.string().min(1),description:l.string().min(1).optional(),_meta:ei.optional(),roles:ft,groups:ft,public:l.boolean().optional()}).strict(),n_=l.object({uri:l.string().min(1),name:l.string().min(1).optional(),description:l.string().min(1).optional(),mimeType:l.string().min(1).optional(),_meta:ei.optional(),roles:ft,groups:ft,public:l.boolean().optional()}).strict(),o_=l.object({uriTemplate:l.string().min(1),name:l.string().min(1).optional(),description:l.string().min(1).optional(),mimeType:l.string().min(1).optional(),_meta:ei.optional(),roles:ft,groups:ft,public:l.boolean().optional()}).strict(),i_=l.array(l.union([l.string(),t_])),s_=l.array(l.union([l.string(),r_])),a_=l.array(l.union([l.string(),n_])),c_=l.array(l.union([l.string(),o_])),d_=l.object({module:l.unknown(),export:l.string().min(1)}).strict(),u_=l.object({mode:l.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:l.string().min(1).optional(),groupClaim:l.string().min(1).optional(),identifier:d_.optional()}).strict(),l_=l.object({tools:i_.optional(),prompts:s_.optional(),resources:a_.optional(),resourceTemplates:c_.optional(),accessControl:u_.optional()}).strict(),ht=[{option:"tools",listMethod:"tools/list",resultProperty:"tools",itemProperty:"name",directMethods:["tools/call"]},{option:"prompts",listMethod:"prompts/list",resultProperty:"prompts",itemProperty:"name",directMethods:["prompts/get"]},{option:"resources",listMethod:"resources/list",resultProperty:"resources",itemProperty:"uri",directMethods:["resources/read"]},{option:"resourceTemplates",listMethod:"resources/templates/list",resultProperty:"resourceTemplates",itemProperty:"uriTemplate",directMethods:[]}];function p_(e,t){return Pu(l_,e,`MCP capability filter policy "${t}"`)}n(p_,"parseMcpCapabilityFilterOptions");function Se(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Se,"isRecord");function Kn(e){return typeof e.method=="string"?e.method:void 0}n(Kn,"messageMethod");function Cp(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}n(Cp,"correlationKey");function Ip(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}n(Ip,"asStringArray");function Tp(e,t){if(!Se(e))return[];let r=t in e?e[t]:t.split(".").reduce((o,i)=>Se(o)?o[i]:void 0,e);return Array.isArray(r)?r.filter(o=>typeof o=="string"):typeof r=="string"?r.split(/\s+/).filter(o=>o.length>0):[]}n(Tp,"readClaimValues");function Ps(e,t){if(typeof e=="string")return{key:e,public:!1};if(!Se(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:Ip(e.roles),groups:Ip(e.groups),public:e.public===!0}}n(Ps,"normalizeEntry");function m_(e,t,r){if(e.public)return!0;let o=e.roles??[],i=e.groups??[];return o.length===0&&i.length===0?!1:o.some(s=>t.has(s))||i.some(s=>r.has(s))}n(m_,"isCallerAllowed");function Qo(e,t,r,o){if(e===void 0)return;let i=[];for(let s of e){let c=Ps(s,t);c!==void 0&&m_(c,r,o)&&i.push(c.key)}return i}n(Qo,"allowedKeys");var Ap=n((e,t,r)=>{let o=r.accessControl?.roleClaim??"roles",i=r.accessControl?.groupClaim??"groups",s=new Set(Tp(e.user?.data,o)),c=new Set(Tp(e.user?.data,i));return{tools:Qo(r.tools,"name",s,c),prompts:Qo(r.prompts,"name",s,c),resources:Qo(r.resources,"uri",s,c),resourceTemplates:Qo(r.resourceTemplates,"uriTemplate",s,c)}},"claimsCapabilityResolver");function h_(e,t){let r=[];for(let o of ht){let i=e[o.option];if(i!==void 0)for(let s of i){let c=Ps(s,o.itemProperty);if(c===void 0)continue;let a=(c.roles?.length??0)>0||(c.groups?.length??0)>0;c.public&&a&&r.push(`${o.option} "${c.key}"`)}}if(r.length>0)throw new K(`MCP capability filter policy "${t}" - with accessControl.mode "rolesAndGroups", a capability cannot set both "public": true and roles/groups ("public" opens it to everyone, roles/groups restrict it). Remove one of the two on: ${r.join(", ")}`)}n(h_,"assertNoConflictingMarkup");function f_(e,t){let r=[];for(let o of ht){let i=e[o.option];if(i!==void 0)for(let s of i){let c=Ps(s,o.itemProperty);c!==void 0&&((c.roles?.length??0)>0||(c.groups?.length??0)>0||c.public)&&r.push(`${o.option} "${c.key}"`)}}if(r.length>0)throw new K(`MCP capability filter policy "${t}" - accessControl.mode is "allPublic" (the default) but these capabilities set roles/groups/public; set accessControl.mode to "rolesAndGroups" or remove the markup: ${r.join(", ")}`)}n(f_,"assertNoMarkup");function g_(e,t){let r=e.identifier;if(r===void 0)throw new K(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);if(r.module===null||typeof r.module!="object")throw new K(`MCP capability filter policy "${t}" - accessControl.identifier.module must reference a module, e.g. $import(./modules/mcp-access-control)`);if(!r.export)throw new K(`MCP capability filter policy "${t}" - accessControl.identifier.export must be specified`);let o=r.module[r.export];if(typeof o!="function")throw new K(`MCP capability filter policy "${t}" - accessControl.identifier must resolve to a valid function`);let i=o;return async(s,c,a)=>{let u=await i(s,c,a);if(u==null)throw new v(`MCP capability filter policy "${t}" - accessControl resolver returned no value; return an AllowedCapabilities object (use empty arrays to deny)`);if(typeof u!="object"||Array.isArray(u))throw new v(`MCP capability filter policy "${t}" - accessControl resolver must return an AllowedCapabilities object`);return u}}n(g_,"buildCustomResolver");function y_(e,t){let r=e.accessControl,o=r?.mode??"allPublic";if(o==="function"){if(r===void 0)throw new K(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);return g_(r,t)}if(o==="rolesAndGroups")return h_(e,t),Ap;f_(e,t)}n(y_,"buildCapabilityResolver");function S_(e){let t={};for(let r of ht){let o=e[r.option];if(o===void 0)continue;let i=new Map;for(let s of o){let c=v_(s,r.itemProperty);c!==void 0&&i.set(c.key,c)}t[r.option]=i}return t}n(S_,"buildProjectionMaps");function Ts(e){return e===void 0?void 0:ht.find(t=>t.listMethod===e)}n(Ts,"findListRule");function __(e){return e===void 0?void 0:ht.find(t=>t.directMethods.includes(e))}n(__,"findDirectRule");function w_(e){switch(e.method){case"tools/call":return{option:"tools",target:e.params.name};case"prompts/get":return{option:"prompts",target:e.params.name};case"resources/read":return{option:"resources",target:e.params.uri};default:return}}n(w_,"directCapabilityAccess");function R_(e){let t=__(Kn(e));if(t===void 0||!Se(e.raw))return;let r=e.raw.params;if(!Se(r))return;let o=r[t.itemProperty==="uri"?"uri":"name"];return typeof o=="string"?{option:t.option,target:o}:void 0}n(R_,"rawDirectCapabilityAccess");function b_(e){return Response.json(Xo({...e==null?{}:{id:e},error:{code:A.MethodNotFound,message:"Method not found"}}))}n(b_,"methodNotFoundResponse");function v_(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!Se(e))return;let r=e[t];if(typeof r!="string")return;let o={...e};return delete o.roles,delete o.groups,delete o.public,{key:r,overlay:o}}n(v_,"buildProjection");function kp(e){let t=e.base[e.property],r=e.overlay[e.property];return Se(r)?Se(t)?{...t,...r}:r:t}n(kp,"mergeRecordProperty");function C_(e,t){let r={...e,...t.overlay},o=kp({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let i=kp({base:e,overlay:t.overlay,property:"_meta"});return i!==void 0&&(r._meta=i),r}n(C_,"applyProjection");function Pp(e,t,r,o){if(!Se(e))return e;let i=e.result;if(!Se(i))return e;let s=i[t.resultProperty];return!Array.isArray(s)||!s.every(c=>Se(c)&&typeof c[t.itemProperty]=="string")?e:{...e,result:{...i,[t.resultProperty]:s.flatMap(c=>{if(!Se(c))return[];let a=c[t.itemProperty];if(typeof a!="string")return[];if(o!==void 0&&!o.has(a))return[];let u=r.get(a);return u===void 0?[]:[C_(c,u)]})}}}n(Pp,"filterAndProjectItems");function I_(e){let{envelope:t,responseBody:r,projectionMaps:o,allowedSets:i}=e;if(Array.isArray(r)){if(t.shape!=="batch")return r;let u=new Map;for(let p of t.messages){let h=Ts(Kn(p)),f=h===void 0?void 0:Cp(p.id);h!==void 0&&f!==void 0&&u.set(f,h)}return u.size===0?r:r.map(p=>{if(!Se(p)||"error"in p)return p;let h=Cp(p.id),f=h===void 0?void 0:u.get(h),y=f===void 0?void 0:o[f.option];return f===void 0||y===void 0?p:Pp(p,f,y,i?.[f.option])})}if(t.shape!=="single"||!Se(r)||"error"in r)return r;let s=t.messages[0],c=Ts(s===void 0?void 0:Kn(s)),a=c===void 0?void 0:o[c.option];return c===void 0||a===void 0?r:Pp(r,c,a,i?.[c.option])}n(I_,"filterResponseBody");function T_(e){return e.headers.get("content-type")?.includes("json")??!1}n(T_,"isJsonResponse");var ks=class extends Io{static{n(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#t;constructor(t,r){let o=p_(t,r);super(o,r),this.#r=r,this.#e=S_(o),this.#t=y_(o,r)}async handler(t,r){let o=await hl(t);if(o===null)return t;let i=this.#t!==void 0&&this.#n(o)?await this.#i(t,r):void 0;for(let c of o.messages){let a=c.type==="request"?w_(c):R_(c);if(a===void 0)continue;let u=this.#e[a.option];if(u===void 0)continue;let p=i?.[a.option];if(!u.has(a.target)||p!==void 0&&!p.has(a.target))return b_(c.type==="request"?c.id:c.id??void 0)}if(!this.#o(o))return t;let s=this.#e;return r.addResponseSendingHook(async c=>{if(!T_(c))return c;let a;try{a=await c.clone().json()}catch{return c}let u=I_({envelope:o,responseBody:a,projectionMaps:s,allowedSets:i});if(u===a)return c;let p=new Headers(c.headers);return p.delete("content-length"),new Response(JSON.stringify(u),{status:c.status,statusText:c.statusText,headers:p})}),t}#n(t){return t.messages.some(r=>{let o=Kn(r);return o===void 0?!1:ht.some(i=>this.#e[i.option]===void 0?!1:i.listMethod===o||i.directMethods.includes(o))})}#o(t){return t.messages.some(r=>{let o=Ts(Kn(r));return o!==void 0&&this.#e[o.option]!==void 0})}async#i(t,r){let o=this.#t;if(o===void 0)return{};let i;try{i=await o(t,r,this.options)}catch(c){r.log.error(`MCP capability filter policy "${this.#r}" - access-control resolver threw; denying configured capabilities`,c);let a={};for(let u of ht)this.#e[u.option]!==void 0&&(a[u.option]=new Set);return a}let s={};for(let c of ht){let a=this.#e[c.option];if(a===void 0)continue;let u=i[c.option];if(u===void 0)continue;let p=new Set;if(Array.isArray(u))for(let h of u)typeof h=="string"&&a.has(h)&&p.add(h);s[c.option]=p}return s}};var As="zuplo.com",k_=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),P_=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Ep(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(Ep,"s2FaviconHref");function A_(e){return`https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&drop_404_icon=true&fallback_opts=TYPE,SIZE,URL&url=http://${e}&size=128`}n(A_,"strictFaviconHref");var ti=Ep(As);function Es(e){let t=e.toLowerCase();return t===As||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Ep(As):A_(e)}n(Es,"resolveIconHref");function E_(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(E_,"hostnameFromHost");function x_(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(x_,"isLocalOrAddressHost");function U_(e){let t=E_(e).toLowerCase().replace(/\.$/,"");if(x_(t)||P_.some(s=>t===s.slice(1)||t.endsWith(s)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let o=r.slice(-2).join("."),i=k_.has(o)?3:2;return r.slice(-i).join(".")}n(U_,"inferFaviconDomain");function xs(e){return{src:Es(U_(e)),mimeType:"image/png",sizes:["128x128"]}}n(xs,"resolveMcpFaviconIcon");function ri(e){try{return xs(new URL(e).host)}catch{return}}n(ri,"resolveMcpFaviconIconFromUrl");function gt(e){let t=ye().connectionsById.get(e);if(!t)throw new K(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,description:t.description,serverInfo:t.serverInfo,transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}n(gt,"getUpstreamServerConfig");function ni(e){let t=ye().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new K(`Unknown auth profile "${String(e.authProfileId)}" for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares a matching auth mode for that upstream connection.`);return t.authConfig}n(ni,"getUpstreamAuthConfig");function br(e,t){let r=ni({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new K(`Upstream server "${e}" does not use upstream OAuth. Select authMode "shared-oauth" or "user-oauth" before starting an upstream OAuth connection flow.`);return r.oauth}n(br,"requireUpstreamOAuthConfig");function xp(e,t){let r=ni({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new K(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}n(xp,"requireUpstreamIdJagConfig");function Up(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let r=n(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",r,{once:!0}),()=>t.removeEventListener("abort",r)}n(Up,"mergeAbortSignals");async function O_(e){try{await e.cancel()}catch{}}n(O_,"cancelReader");async function oi(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],i=0,s=await r.read();for(;!s.done;){let u=s.value;if(i+=u.byteLength,i>t.maxBytes)throw await O_(r),t.createLimitError();o.push(u),s=await r.read()}let c=new Uint8Array(i),a=0;for(let u of o)c.set(u,a),a+=u.byteLength;return c}n(oi,"readBoundedByteStream");var q_=2,z_=1024*1024,M_=1e4,N_=new Set([301,302,303,307,308]),j_=["authorization","proxy-authorization","cookie","cookie2"];function Us(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Us,"readRequestUrl");function vr(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(vr,"readRequestMethod");function $_(e,t,r){let o=e.headers.get("content-length");if(!o)return;let i=Number.parseInt(o,10);if(Number.isFinite(i)&&i>t)throw new v({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[I]:r}})}n($_,"assertContentLengthWithinLimit");async function D_(e,t,r){return $_(e,t,r),oi(e.body,{maxBytes:t,createLimitError:n(()=>new v({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[I]:r}}),"createLimitError")})}n(D_,"readBoundedResponseBody");function L_(e,t){let r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}n(L_,"responseFromBufferedBody");function H_(e,t){if(!N_.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(H_,"resolveRedirectUrl");function Op(e,t){try{return t.validateUrl(e)}catch(r){throw new v({message:"Outbound URL was not allowed.",extensionMembers:{[I]:t.problemCode}},{cause:r})}}n(Op,"validateOutboundUrl");function B_(e,t){throw e instanceof v&&qo(e.extensionMembers?.[I])?e:new v({message:"Outbound fetch failed.",extensionMembers:{[I]:t}},{cause:e})}n(B_,"normalizeFetchError");function Wn(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[o,i]of Object.entries(t.extra))i!==void 0&&(r[o]=i);t.error!==void 0&&pe(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(Wn,"logOutboundFailure");async function F_(e,t,r,o,i,s,c){let a=vr(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";Wn(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:i,method:a,host:te(s),error:u,extra:{abortReason:c()}}),B_(u,i)}}n(F_,"fetchWithNormalizedError");function G_(e){if(e.redirects>=e.maxRedirects)throw new v({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[I]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new v({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[I]:e.problemCode}})}n(G_,"assertRedirectAllowed");function J_(e,t){let r=new Headers(e);for(let o of j_)r.delete(o);for(let o of t)r.delete(o);return r}n(J_,"stripCrossOriginHeaders");function V_(e,t,r,o,i){let s={...e,method:t,redirect:"manual",signal:r};return o&&(s.headers=J_(e.headers,i)),s}n(V_,"buildRedirectInit");function K_(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(K_,"buildInitialRequestInit");function W_(e){let t=vr(e.currentInput,e.currentInit);G_({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=Op(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),o=new URL(e.currentUrl),i=r.origin!==o.origin,s=r.toString();return{currentInput:s,currentUrl:s,currentInit:V_(e.currentInit,t,e.signal,i,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(W_,"followRedirect");async function Os(e,t,r){let o=r.problemCode??"invalid_request",i=r.maxRedirects??q_,s=r.maxResponseBytes??z_,c=r.timeoutMs??M_,a=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,h=new AbortController,f=Up(h,t.signal),y=!1,S=setTimeout(()=>{y=!0,h.abort()},c),k=e,w=K_(e,t,h.signal),C;try{C=Op(Us(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(O){throw Wn(p,{event:"outbound_url_blocked",problemCode:o,method:vr(e,t),host:te(Us(e)),error:O}),clearTimeout(S),f?.(),O}let U=0;try{for(;;){let O=await F_(p,a,k,w,o,C,()=>y?`timeout_after_${c}ms`:void 0),L=H_(O,C);if(L!==void 0)try{let F=W_({currentInput:k,currentInit:w,currentUrl:C,redirectUrl:L,redirects:U,maxRedirects:i,problemCode:o,validateUrl:r.validateUrl,signal:h.signal,additionalCrossOriginStrippedHeaders:u});k=F.currentInput,w=F.currentInit,C=F.currentUrl,U=F.redirects;continue}catch(F){throw Wn(p,{event:"outbound_redirect_blocked",problemCode:o,method:vr(k,w),host:te(C),error:F,extra:{redirects:U,maxRedirects:i,redirectTargetHost:te(L)}}),F}try{return L_(O,await D_(O,s,o))}catch(F){throw Wn(p,{event:"outbound_response_size_exceeded",problemCode:o,method:vr(k,w),host:te(C),error:F,extra:{maxResponseBytes:s,status:O.status}}),F}}}finally{clearTimeout(S),f?.()}}n(Os,"runSafeOutboundExchange");async function Zn(e,t,r){let o=await Os(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(i){throw Wn(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:vr(e,t),host:te(Us(e)),error:i,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new v({message:"Outbound JSON response could not be parsed.",extensionMembers:{[I]:r.problemCode??"invalid_request"}},{cause:i})}}n(Zn,"runSafeOutboundJsonExchange");function qp(e,t={},r={}){return Os(e,t,{...r,validateUrl:$n})}n(qp,"fetchConfiguredOutbound");function zp(e,t={},r={}){return Zn(e,t,{...r,validateUrl:$n})}n(zp,"fetchConfiguredOutboundJson");function ii(e,t={},r={}){return Zn(e,t,{...r,validateUrl:nl})}n(ii,"fetchIdentityProviderJson");function Mp(e,t={},r={}){return Zn(e,t,{...r,validateUrl:Lo})}n(Mp,"fetchCimdClientMetadataJson");function Np(e,t={},r={}){return Zn(e,t,{...r,validateUrl:Dn})}n(Np,"fetchCimdClientJwksJson");import{errors as Bp,jwtVerify as Fp,SignJWT as Gp}from"jose";var _e="zuplo-mcp-gateway",Ce=_e,Ie="HS256";import{base64url as Z_}from"jose";var Y_=new TextEncoder,X_="MCP gateway could not initialize secure key material.",Q_=32,jp=new Map,$p=new Map,ew;function tw(){return ew??Aa.instance.authPrivateKey}n(tw,"readAuthPrivateKey");function Dp(e){return new Pe(X_,e===void 0?void 0:{cause:e})}n(Dp,"createGeneratedKeyMaterialError");function Lp(e,t){let r=Z_.decode(t);if(r.byteLength!==Q_)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(Lp,"decodeJwkKeyField");function rw(e){let t=tw();if(!t)throw Dp();try{let r=JSON.parse(t);if(r.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.d!="string"||typeof r.x!="string")throw new Error("Generated deployment auth key is not an Ed25519 JWK.");let o=Lp("d",r.d);Lp("x",r.x);let i=Y_.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),s=new Uint8Array(i.byteLength+o.byteLength);return s.set(i),s.set(o,i.byteLength),s}catch(r){throw Dp(r)}}n(rw,"decodeGeneratedKeyMaterial");function nw(e){let t=jp.get(e);return t||(t=rw(e),jp.set(e,t)),t}n(nw,"getMasterKeyMaterial");async function Le(e){let t=$p.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(nw(e.keyMaterialPurpose));return $p.set(e.purpose,r),r}n(Le,"readCachedDerivedKey");var ow="SHA-256",iw=32,sw="zuplo-mcp-gateway:",aw=new TextEncoder,Hp=new WeakMap;async function yt(e,t){let r=Hp.get(e);r||(r=new Map,Hp.set(e,r));let o=r.get(t);if(o)return o;let i=await cw(e,t);return r.set(t,i),i}n(yt,"deriveGatewaySigningKey");async function cw(e,t){let r=me(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=aw.encode(`${sw}${t}`),s=await crypto.subtle.deriveBits({name:"HKDF",hash:ow,salt:new Uint8Array,info:me(i)},o,iw*8);return new Uint8Array(s)}n(cw,"hkdfExpand");var Jp=900,dw=900,uw=$u.extend({id:cl}),lw=uw.extend({exp:l.number().int().positive(),iat:l.number().int().positive().optional()}),Vp=Li.extend({id:dl,purpose:l.literal("browser_connect")}),pw=Li.extend({purpose:l.literal("browser_connect")}),mw=Vp.extend({exp:l.number().int().positive(),iat:l.number().int().positive().optional()}),Kp=Jp*1e3;async function Wp(){return Le({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>yt(e,"oauth-state"),"derive")})}n(Wp,"getOAuthStateKey");async function Zp(){return Le({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>yt(e,"browser-connect"),"derive")})}n(Zp,"getBrowserConnectKey");async function Yp(e){let t=Math.floor(Date.now()/1e3)+Jp;return new Gp(e).setProtectedHeader({alg:Ie,typ:"JWT"}).setIssuer(_e).setAudience(Ce).setIssuedAt().setExpirationTime(t).sign(await Wp())}n(Yp,"signOAuthState");async function si(e){try{let{payload:t}=await Fp(e,await Wp(),{algorithms:[Ie],issuer:_e,audience:Ce});return lw.parse(t)}catch(t){throw t instanceof Bp.JWTExpired?new v({message:"OAuth state has expired",extensionMembers:{[I]:"oauth_state_expired"}},{cause:t}):new v({message:"OAuth state could not be verified",extensionMembers:{[I]:"oauth_state_invalid"}},{cause:t})}}n(si,"verifyOAuthState");async function Xp(e){let t=Math.floor(Date.now()/1e3)+dw,r=pw.parse(e),o=Vp.parse({...r,id:ml()});return new Gp(o).setProtectedHeader({alg:Ie,typ:"JWT"}).setIssuer(_e).setAudience(Ce).setIssuedAt().setExpirationTime(t).sign(await Zp())}n(Xp,"signBrowserConnectTicket");async function Qp(e){try{let{payload:t}=await Fp(e,await Zp(),{algorithms:[Ie],issuer:_e,audience:Ce});return mw.parse(t)}catch(t){throw t instanceof Bp.JWTExpired?new v({message:"Browser connect ticket has expired",extensionMembers:{[I]:"oauth_state_expired"}},{cause:t}):new v({message:"Browser connect ticket could not be verified",extensionMembers:{[I]:"oauth_state_invalid"}},{cause:t})}}n(Qp,"verifyBrowserConnectTicket");async function em(e){if((await N().consumeBrowserConnectTicket({id:e.id,expiresAt:$(new Date(e.exp*1e3)),now:$(new Date)})).kind==="consumed")throw new v({message:"Browser connect ticket has already been used",extensionMembers:{[I]:"oauth_state_reused"}})}n(em,"consumeBrowserConnectTicket");function hw(e,t,r=!1){return r?`${e} authorization must be renewed before this ${t} can be used.`:`${e} authorization is required before this ${t} can be used.`}n(hw,"buildConnectRequiredMessage");async function fw(e){let t=Y(e.requestUrl,e.requestHeaders),r=new URL(e.path,t);return e.redirect&&r.searchParams.set("redirect","true"),r.searchParams.set("operationId",e.operationId),r.searchParams.set("browserTicket",await Xp({...Nn(e),purpose:"browser_connect"})),r.toString()}n(fw,"buildGatewayBrowserTicketUrl");function gw(e){return de().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(gw,"buildGatewayConnectPath");async function qs(e){return fw({...e,path:gw(e.upstreamServerId),redirect:!0})}n(qs,"buildGatewayConnectUrl");async function ai(e){let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await qs(t),message:hw(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(ai,"buildRedirectConnectRequiredResponse");function tm(e){return yw({...e,message:e.requiresReconsent?`An administrator must reconnect ${e.upstreamDisplayName} before this tool can be used.`:`An administrator must connect ${e.upstreamDisplayName} before this tool can be used.`})}n(tm,"buildAdminConnectRequiredResponse");function yw(e){return{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},message:e.message,nextAction:"admin_setup_required"}}n(yw,"buildAdminSetupRequiredResponse");var rm=12;async function nm(e){let t=await crypto.subtle.digest("SHA-256",me(new TextEncoder().encode(e)));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}n(nm,"sha256Hex");async function Lt(e){if(e)return(await nm(e)).slice(0,rm)}n(Lt,"fingerprintSecret");async function Cr(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await nm(t)).slice(0,rm)}n(Cr,"fingerprintConnectionIdentity");var Sw=6e4;function Ir(e,t){return e===void 0?!0:e.status!==t.status||e.encryptedAccessToken!==t.encryptedAccessToken||e.encryptedRefreshToken!==t.encryptedRefreshToken||e.expiresAt!==t.expiresAt||e.scopes.length!==t.scopes.length||e.scopes.some((r,o)=>t.scopes[o]!==r)}n(Ir,"credentialGenerationChanged");function he(e){if(!e)return"no_connection";if(e.status!=="active")return"inactive";if(!e.encryptedAccessToken)return"no_access_token";if(e.expiresAt){let t=new Date(e.expiresAt).getTime();if(t<=Date.now())return"expired";if(t<=Date.now()+Sw)return"near_expiry"}return"usable"}n(he,"describeAccessTokenState");var om=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function _w(e,t){return e&&e.length>0?e.join(t):void 0}n(_w,"joinOAuthScopes");function ww(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of om)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(ww,"sanitizeAuthorizationServerMetadata");function im(e){let t=ww(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(im,"sanitizeOAuthDiscoveryState");function sm(e){let t=new URL(e);for(let r of om){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(sm,"dedupeSingletonAuthorizationRequestParams");function ci(e){let t=new URL(e);return be(t)&&ku(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(ci,"normalizeLoopbackOAuthRedirectUri");function am(e){return _w(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(am,"readProtectedResourceMetadataScope");function Rw(e){return`Zuplo MCP Gateway - ${e}`}n(Rw,"buildGatewayOAuthClientName");function bw(e,t){return e&&e.length>0?e.join(t):void 0}n(bw,"joinOAuthScopeList");function vw(e){if(e.clientRegistration.mode!=="auto")return bw(e.scopes,e.scopeDelimiter)}n(vw,"readPublicClientMetadataScope");function zs(e){return new URL(de().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(zs,"buildOAuthClientMetadataDocumentUrl");function Ms(e){let t=gt(e.upstreamServerId);return{client_name:Rw(t.displayName),client_uri:new URL("/",e.origin).toString(),redirect_uris:[e.redirectUri],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",...e.scope===void 0?{}:{scope:e.scope},token_endpoint_auth_method:"none"}}n(Ms,"buildGatewayOAuthClientMetadata");function cm(e,t,r){let o=br(t,r),i=vw(o);return{client_id:zs({origin:e,upstreamServerId:t}),...Ms({origin:e,upstreamServerId:t,redirectUri:ci(new URL(o.redirectPath,e)).toString(),scope:i})}}n(cm,"buildOAuthClientMetadataDocument");import{base64url as St}from"jose";var Cw="SHA-256",Tr="AES-GCM",Iw=12,js="zuplo-secret",$s=1,dm="generated:auth_private_key:token-encryption",Tw=l.object({version:l.literal($s),keyId:l.literal(dm),algorithm:l.literal(Tr),iv:l.string().min(1),ciphertext:l.string().min(1)}).strict();async function Ns(){return Le({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(Cw,me(e));return crypto.subtle.importKey("raw",t,{name:Tr},!1,["encrypt","decrypt"])},"derive")})}n(Ns,"getEncryptionKey");function um(e){return me(new TextEncoder().encode(`${js}:v${e.version}:${e.keyId}`))}n(um,"getAssociatedData");function kw(e){return`${js}:v${e.version}:${St.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(kw,"encodeEnvelope");function Pw(e){let t=`${js}:v${$s}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(St.decode(r));return Tw.parse(JSON.parse(o))}n(Pw,"decodeEnvelope");async function Ze(e){let t=await Ns(),r=crypto.getRandomValues(new Uint8Array(Iw)),o={version:$s,keyId:dm},i=await crypto.subtle.encrypt({name:Tr,iv:r,additionalData:um(o)},t,new TextEncoder().encode(e));return kw({...o,algorithm:Tr,iv:St.encode(r),ciphertext:St.encode(new Uint8Array(i))})}n(Ze,"encryptSecret");async function Ye(e){let t=Pw(e);if(t){let c=await Ns(),a=await crypto.subtle.decrypt({name:Tr,iv:me(St.decode(t.iv)),additionalData:um(t)},c,me(St.decode(t.ciphertext)));return new TextDecoder().decode(a)}let[r,o]=e.split(".");if(!r||!o)throw new Pe("Encrypted payload is malformed");let i=await Ns(),s=await crypto.subtle.decrypt({name:Tr,iv:me(St.decode(r))},i,me(St.decode(o)));return new TextDecoder().decode(s)}n(Ye,"decryptSecret");var lm={issuer:l.string().min(1).optional()},Aw=l.union([jt.extend(lm),zn.extend(lm)]),pm=l.object({authorizationServerUrl:l.url(),resourceMetadataUrl:l.url().optional(),resourceMetadata:pr.optional(),authorizationServerMetadata:l.union([mr,hr]).optional()}).passthrough(),Ew="Bearer",xw="__zuplo_refresh_only_upstream_access_token__";function Ds(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Ds,"splitScopes");function Ls(e,t){let r=new Set(e);return t.every(o=>r.has(o))}n(Ls,"scopesCover");function Uw(e){return gr.parse(e)}n(Uw,"parsePkceCodeVerifier");function Ow(e){if(typeof e.expires_in=="number")return $(new Date(Date.now()+e.expires_in*1e3))}n(Ow,"readTokenExpiry");async function mm(e){if(e!==void 0)return Ze(JSON.stringify(e))}n(mm,"encryptJson");async function hm(e,t){if(!e)return;let r=await Ye(e);try{return t.parse(JSON.parse(r))}catch(o){throw new v({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[I]:"oauth_state_invalid"}},{cause:o})}}n(hm,"decryptJson");function qw(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(qw,"clientInformationAllowsRedirectUri");function zw(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(zw,"clientInformationMatchesCurrentClientMetadataUrl");function Mw(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(Mw,"isUrlBasedClientInformation");function Nw(e,t){return t===void 0?e:{...e,scope:t}}n(Nw,"applyOAuthClientMetadataScope");function jw(e,t){return am({state:e,delimiter:t})}n(jw,"readResourceMetadataScope");function $w(e,t){return e&&e.length>0?e.join(t):void 0}n($w,"joinOAuthScopeList");function Dw(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new K(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return jt.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(Dw,"buildManualOAuthClientInformation");function Lw(e,t){let r=zs({origin:new URL(t).origin,upstreamServerId:e});return Is(r)?r:void 0}n(Lw,"buildClientMetadataUrl");function Hw(e){for(let t of e)if(t!==void 0)return t}n(Hw,"firstDefined");function Bw(e){let t=br(e.target.upstreamServerId,e.target.authProfileId),r=$w(t.scopes,t.scopeDelimiter),o=Ms({origin:new URL(e.redirectUri).origin,upstreamServerId:e.target.upstreamServerId,redirectUri:e.redirectUri,scope:r});if(t.clientRegistration.mode==="manual")return{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,configuredClientInformation:Dw({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let i=Lw(e.target.upstreamServerId,e.redirectUri);return i===void 0?{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,clientMetadataUrl:i}}n(Bw,"buildInitialOAuthClientSetup");function Fw(e,t){if(t===void 0)return Hw([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(Fw,"readEncryptedClientInformation");function Gw(e){return e.pendingState?.encryptedDiscoveryState}n(Gw,"readEncryptedDiscoveryState");function Hs(e,t){return t===void 0?e:{...e,issuer:t}}n(Hs,"applyIssuerStamp");var _t=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredScope;scopeDelimiter;promptOverride;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;credentialState;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;tokensLoaded=!1;tokenPersistenceOutcome;connectionFingerprintValue;usedRefreshTokenFingerprintValue;constructor(t){let r=Bw({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.clientMetadataValue=r.clientMetadata,this.configuredScope=r.configuredScope,this.scopeDelimiter=r.scopeDelimiter,this.promptOverride=r.promptOverride,this.configuredClientInformation=r.configuredClientInformation,r.clientMetadataUrl!==void 0&&(this.clientMetadataUrl=r.clientMetadataUrl),this.credentialState={sourceConnection:t.connection,currentConnection:t.connection},this.pendingState=t.pendingState?{...t.pendingState}:void 0,this.encryptedClientInformation=Fw(t,this.configuredClientInformation),this.encryptedDiscoveryState=Gw(t)}get authorizationUrl(){return this.authorizationUrlValue}get configuredAuthorizationScope(){return this.configuredScope}get usedRefreshTokenFingerprint(){return this.usedRefreshTokenFingerprintValue}get currentConnection(){return this.credentialState.currentConnection}get tokenWriteWasPersisted(){return this.tokenPersistenceOutcome==="persisted"}connectionSatisfiesRequestedScope(t,r){let o=Ds(this.configuredScope??r??this.readEffectiveScope());return Ls(t.scopes,o)}readUsablePeerAdoption(t){let r=this.credentialState.peerAdoption?.connection;return r!==void 0&&he(r)==="usable"&&this.connectionSatisfiesRequestedScope(r,t)?r:void 0}async adoptConnectionForDirectResolution(t,r){this.adoptPeerConnection(t,r),this.tokensLoaded=!1,this.credentialState.sdkTokenMemo=void 0;let o=W();o&&o.info({event:"upstream_oauth_peer_credential_adopted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:t.id,adoptionReason:r,sourceUpdatedAt:this.credentialState.sourceConnection?.updatedAt,resultingUpdatedAt:t.updatedAt,sourceScopeCount:this.credentialState.sourceConnection?.scopes.length,resultingScopeCount:t.scopes.length,accessTokenGenerationFingerprint:await this.storedSecretFingerprint(t.encryptedAccessToken),refreshTokenGenerationFingerprint:await this.storedSecretFingerprint(t.encryptedRefreshToken)},"Adopted a concurrent upstream OAuth credential")}adoptPeerConnection(t,r){this.credentialState.currentConnection=t,this.credentialState.peerAdoption={connection:t,reason:r}}async connectionFingerprint(){return this.connectionFingerprintValue===void 0&&(this.connectionFingerprintValue=await Cr({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}async storedSecretFingerprint(t){if(t!==void 0)try{return await Lt(await Ye(t))}catch{return}}async conditionalUpsertCredential(t,r){try{return await N().conditionalUpsertUpstreamConnection(t,r)}catch(o){let i=W();if(i){let s=Object.assign(new Error("Upstream OAuth conditional storage write failed",{cause:o}),{event:"upstream_oauth_conditional_write_failed",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),sourceUpdatedAt:"expectedUpdatedAt"in r?r.expectedUpdatedAt:void 0,expectAbsent:"expectAbsent"in r,scopeCount:t.scopes.length});i.error(s,"Upstream OAuth conditional storage write failed")}throw o}}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return Nw(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return Yp({id:t.id,...Nn({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId})})}async clientInformation(t){return this.configuredClientInformation?Hs(this.configuredClientInformation,t?.issuer):this.loadPersistedClientInformation(t)}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,W()?.info({event:"upstream_oauth_client_registered",upstreamServerId:this.target.upstreamServerId,clientId:"client_id"in t?t.client_id:void 0,redirectUriCount:"redirect_uris"in t?t.redirect_uris.length:void 0},"Upstream OAuth client registered for the gateway"),!Mw({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await mm(t),await this.syncPendingState(!1)))}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=im(pm.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await mm(r),await this.syncPendingState(!1),W()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:te(r.authorizationServerUrl),resourceMetadataHost:te(r.resourceMetadataUrl),resource:r.resourceMetadata?.resource,scopesSupportedCount:r.resourceMetadata?.scopes_supported?.length,hasResourceMetadata:r.resourceMetadata!==void 0},"Upstream OAuth discovery resolved authorization server and resource"),this.inferredScope=jw(r,this.scopeDelimiter);let o=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&o!==void 0){let i=Ds(this.configuredScope).filter(s=>!o.includes(s));i.length>0&&W()?.debug({event:"upstream_oauth_configured_scopes_not_advertised",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,unadvertisedScopes:i,scopesSupported:o},"Configured upstream OAuth scopes include values the resource metadata does not advertise")}}async tokens(t){let r=await this.loadStoredTokens();if(r!==void 0)return Hs(r,t?.issuer)}async saveTokens(t){let r=at.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=this.credentialState.sourceConnection,s=!r.refresh_token&&!!i?.encryptedRefreshToken,c=r.refresh_token?await Ze(r.refresh_token):i?.encryptedRefreshToken;this.credentialState.sdkTokenMemo=r.refresh_token||!i?.encryptedRefreshToken?r:at.parse({...r,refresh_token:await Ye(i.encryptedRefreshToken)}),this.tokensLoaded=!0;let a={id:i?.id??Ho(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await Ze(r.access_token),encryptedRefreshToken:c,scopes:Ds(r.scope??this.readEffectiveScope()),expiresAt:Ow(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)},u=i?{expectedUpdatedAt:i.updatedAt}:{expectAbsent:!0},p=await this.conditionalUpsertCredential(a,u),h=!1;if(p.kind==="precondition_failed"&&p.connection!==void 0&&(he(p.connection)!=="usable"||!Ls(p.connection.scopes,a.scopes)||!Ir(i,p.connection))){h=!0;let y=p.connection,S={id:y.id,ownerMode:y.ownerMode,subjectId:y.subjectId,upstreamServerId:y.upstreamServerId,authProfileId:y.authProfileId,status:"active",encryptedAccessToken:a.encryptedAccessToken,encryptedRefreshToken:r.refresh_token===void 0?y.encryptedRefreshToken:a.encryptedRefreshToken,scopes:a.scopes,expiresAt:a.expiresAt,metadata:y.metadata};W()?.info({event:"upstream_oauth_bounded_rebase_attempted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:y.id,sourceUpdatedAt:i?.updatedAt,winnerUpdatedAt:y.updatedAt,sourceScopeCount:i?.scopes.length,winnerScopeCount:y.scopes.length,resultingScopeCount:S.scopes.length},"Retrying an upstream OAuth token write against the CAS winner"),p=await this.conditionalUpsertCredential(S,{expectedUpdatedAt:y.updatedAt})}if(p.kind!=="persisted"&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),this.tokenPersistenceOutcome=p.kind,p.kind==="persisted"?(this.credentialState.currentConnection=p.connection,this.credentialState.peerAdoption=void 0):p.kind==="precondition_failed"&&p.connection!==void 0?(this.credentialState.currentConnection=p.connection,Ir(i,p.connection)&&he(p.connection)==="usable"&&Ls(p.connection.scopes,a.scopes)?this.adoptPeerConnection(p.connection,"cas_loss"):this.credentialState.peerAdoption=void 0):(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0),h){let y=p.kind==="persisted"?"succeeded":p.kind==="precondition_failed"?"lost":"exhausted";W()?.info({event:`upstream_oauth_bounded_rebase_${y}`,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.credentialState.currentConnection?.id,sourceUpdatedAt:i?.updatedAt,resultingUpdatedAt:this.credentialState.currentConnection?.updatedAt,sourceScopeCount:i?.scopes.length,resultingScopeCount:this.credentialState.currentConnection?.scopes.length},`Upstream OAuth bounded rebase ${y}`)}let f=p.kind==="persisted"?p.connection:void 0;W()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:f?.id??this.credentialState.currentConnection?.id,hasRefreshToken:!!c,sourceScopeCount:i?.scopes.length,priorStatus:i?.status,priorUpdatedAt:i?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await Lt(r.refresh_token),reusedSnapshotRefreshToken:s,scopeCount:a.scopes.length,expiresAt:a.expiresAt,outcome:p.kind,rebaseAttempted:h,resultingUpdatedAt:f?.updatedAt??this.credentialState.currentConnection?.updatedAt,resultingScopeCount:f?.scopes.length??this.credentialState.currentConnection?.scopes.length},f?"Upstream OAuth tokens persisted; upstream connection is active":"Upstream OAuth token persistence yielded to concurrent storage state")}async redirectToAuthorization(t){let r=sm(t);this.promptOverride===!1?r.searchParams.delete("prompt"):this.promptOverride!==void 0&&r.searchParams.set("prompt",this.promptOverride),this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:Uw(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new v({message:"OAuth code verifier is missing",extensionMembers:{[I]:"oauth_state_invalid"}});return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",o=t==="all"||t==="client",i=t==="all"||t==="discovery",s=t==="all"||t==="verifier";o&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),i&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=void 0,this.challengeScope=void 0,this.inferredScope=void 0),r&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),await this.syncPendingState(s),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:pl(),...Nn({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,operationId:this.target.operationId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:$(new Date(Date.now()+Kp)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await N().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(t){if(this.clientInformationLoaded)return this.cachedClientInformation;let r;try{r=await hm(this.encryptedClientInformation,Aw)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(r&&(!qw(r,this.redirectUriValue)||!zw({clientInformation:r,clientMetadataUrl:this.clientMetadataUrl}))){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}return r===void 0&&this.pendingState?.codeVerifier!==void 0&&this.clientMetadataUrl!==void 0&&(r=Hs(zn.parse({client_id:this.clientMetadataUrl}),t?.issuer)),this.cachedClientInformation=r,this.clientInformationLoaded=!0,this.cachedClientInformation}async readCachedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;this.discoveryStateLoaded=!0;try{this.cachedDiscoveryState=await hm(this.encryptedDiscoveryState,pm)}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0}return this.cachedDiscoveryState}readEffectiveScope(){return this.configuredScope??this.challengeScope??this.inferredScope}async loadStoredTokens(){if(this.tokensLoaded)return this.credentialState.sdkTokenMemo;this.tokensLoaded=!0;let t=this.credentialState.currentConnection;if(!t||t.status!=="active"){W()?.debug({event:"upstream_oauth_tokens_not_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:t?.id,status:t?.status??"not_connected"},"Upstream OAuth tokens not loaded; connection is not active");return}let r=t.encryptedAccessToken?await Ye(t.encryptedAccessToken):void 0,o=t.encryptedRefreshToken?await Ye(t.encryptedRefreshToken):void 0;if(!r&&!o)return;let i=W();this.usedRefreshTokenFingerprintValue=i?await Lt(o):void 0,i?.debug({event:"upstream_oauth_tokens_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:t.id,hasAccessToken:!!r,hasRefreshToken:!!o,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,expiresAt:t.expiresAt},"Upstream OAuth tokens loaded from stored connection");let s=at.parse({access_token:r??xw,token_type:Ew,refresh_token:o,scope:t.scopes.length>0?t.scopes.join(" "):void 0});return this.credentialState.sdkTokenMemo=s,s}async persistCredentialInvalidation(t){let r=this.credentialState.sourceConnection;if(!r)return;let o=r.status,i=r.updatedAt,s={id:r.id,ownerMode:r.ownerMode,subjectId:r.subjectId,upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,status:r.status,encryptedAccessToken:r.encryptedAccessToken,encryptedRefreshToken:r.encryptedRefreshToken,scopes:[...r.scopes],expiresAt:r.expiresAt,metadata:r.metadata?{...r.metadata}:void 0};t&&(s.status="reconsent_required",s.encryptedAccessToken=void 0,s.encryptedRefreshToken=void 0,s.scopes=[],s.expiresAt=void 0),s.metadata=this.readStoredOAuthPersistence(r.metadata?.connectedBySubjectId);let c=await this.conditionalUpsertCredential(s,{expectedUpdatedAt:r.updatedAt});c.kind==="persisted"?(this.credentialState.currentConnection=c.connection,this.credentialState.peerAdoption=void 0):c.kind==="missing"?(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0):c.connection!==void 0&&(this.credentialState.currentConnection=c.connection,Ir(r,c.connection)&&he(c.connection)==="usable"&&this.connectionSatisfiesRequestedScope(c.connection)?this.adoptPeerConnection(c.connection,"cas_loss"):this.credentialState.peerAdoption=void 0);let a=W();if(a){let u=c.kind==="missing"?void 0:c.connection,p={event:"upstream_oauth_credentials_invalidated",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:u?.id,clearedTokens:t,priorStatus:o,newStatus:u?.status,priorUpdatedAt:i,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,outcome:c.kind};c.kind==="precondition_failed"?a.warn({...p,event:"upstream_oauth_invalidation_precondition_lost"},"Upstream OAuth credential invalidation yielded to concurrent storage state"):t?a.warn(p,"Upstream OAuth credentials invalidated; connection now requires reconsent"):a.debug(p,"Upstream OAuth credential metadata rewritten")}}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var Jw=3e4,Vw=256*1024,Kw=2,Ww="does not support dynamic client registration",Zw=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],Yw=["HTTP 403 Forbidden","Access Denied","permission to access"],Xw=new Set([ue.AccessDenied,ue.InvalidClient,ue.InvalidGrant,ue.InvalidRequest,ue.InvalidScope,ue.InvalidTarget,ue.UnauthorizedClient,ue.UnsupportedGrantType]);function Qw(e){return e instanceof Error&&e.message.includes(Ww)}n(Qw,"isDynamicClientRegistrationUnsupported");function eR(e){return e instanceof Error&&Zw.some(t=>e.message.includes(t))}n(eR,"isProtectedResourceMetadataUnavailable");function tR(e){return e instanceof Error&&Yw.some(t=>e.message.includes(t))}n(tR,"isUpstreamProviderAccessDenied");function rR(e){return e instanceof mt&&Xw.has(e.code)}n(rR,"isStoredConnectionReconsentError");function nR(e){if(e.error instanceof v&&e.error.extensionMembers?.[I]!==void 0)return e.error;if(Qw(e.error))return new v({message:`The authorization server for ${e.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register an OAuth client for the gateway manually before retrying.`,extensionMembers:{[I]:"upstream_client_registration_required"}},{cause:e.error});if(eR(e.error))return new v({message:`The upstream MCP server "${e.upstreamServerId}" does not publish OAuth protected resource metadata at "${e.resourceMetadataUrl}". Configure protectedResourceMetadataUrl to a working metadata document, use a provider-supported legacy client, or contact the provider to approve/allowlist this gateway OAuth client before retrying.`,extensionMembers:{[I]:"upstream_oauth_discovery_unavailable"}},{cause:e.error});if(tR(e.error))return new v({message:`The upstream provider denied access while connecting ${e.upstreamServerId}. Confirm the provider allows this gateway and its OAuth client, then retry.`,extensionMembers:{[I]:"upstream_provider_access_denied"}},{cause:e.error})}n(nR,"mapUpstreamOAuthSetupError");function oR(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(oR,"readOAuthFetchRequest");function iR(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(iR,"responseLooksJson");function sR(e,t){let r=e.headers.get("content-type")??"",o=t.trimStart().toLowerCase();return r.includes("html")||o.startsWith("<!doctype html")||o.startsWith("<html")}n(sR,"responseLooksHtml");function aR(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new v({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[I]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[ct]:e.response.status,[yr]:r,[dt]:e.request.url.toString(),[Sr]:e.body}})}n(aR,"throwUpstreamHtmlError");function cR(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return{};let r=t;return{error:typeof r.error=="string"?r.error:void 0,errorDescription:typeof r.error_description=="string"?r.error_description:void 0}}catch{return{}}}n(cR,"readUpstreamOAuthErrorBody");function dR(e){let{error:t,errorDescription:r}=cR(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.request.method??"GET",host:te(e.request.url),path:e.request.url.pathname,status:e.response.status,oauthError:t,oauthErrorDescription:r?.slice(0,256)},"Upstream OAuth HTTP request returned an error response")}n(dR,"logUpstreamOAuthHttpError");function gm(e){return async(t,r)=>{let o=oR(t),i=W(),s=Date.now(),c=await qp(t,r,{maxRedirects:Kw,maxResponseBytes:Vw,problemCode:"upstream_token_exchange_failed",timeoutMs:Jw}),a=await c.clone().text();if(i?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:o.method??"GET",host:te(o.url),path:o.url.pathname,status:c.status,durationMs:Date.now()-s,responseChars:a.length},"Upstream OAuth HTTP request completed"),c.ok||dR({log:i,upstreamServerId:e,request:o,response:c,body:a}),!c.ok&&sR(c,a)&&aR({upstreamServerId:e,request:o,response:c,body:a}),!iR(c,a))return c;try{JSON.parse(a)}catch(u){throw new v({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[I]:"upstream_token_exchange_failed"}},{cause:u})}return c}}n(gm,"createUpstreamOAuthFetch");function ym(e){W()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:te(e.serverUrl),resourceMetadataHost:te(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}n(ym,"logUpstreamOAuthFlowStarted");function Sm(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=te(e.serverUrl);r!==void 0&&(t.serverHost=r);let o=e.error instanceof v?e.error.extensionMembers?.[I]:void 0;typeof o=="string"&&(t.code=o),pe(t,"error",e.error),W()?.warn(t,"Upstream OAuth flow failed before a connection was established")}n(Sm,"logUpstreamOAuthFlowFailed");function _m(e,t){return e.configuredAuthorizationScope??t.requestedScope}n(_m,"readAuthorizationRequestScope");async function wm(e,t){e.applyChallengeScope(t.requestedScope),ym({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:gm(t.upstreamServerId)},o=_m(e,t);return o!==void 0&&(r.scope=o),await Cs(e,r)}catch(r){Sm({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=nR({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(wm,"runUpstreamOAuth");async function uR(e,t){e.applyChallengeScope(t.requestedScope),ym({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:gm(t.upstreamServerId)};t.iss!==void 0&&(r.iss=t.iss);let o=_m(e,t);o!==void 0&&(r.scope=o);try{return await Cs(e,r)}catch(i){throw Sm({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:i}),i}}n(uR,"exchangeUpstreamAuthorizationCode");async function fm(e){let t=e.provider.readUsablePeerAdoption(e.requestedScope);if(t!==void 0)return await e.provider.adoptConnectionForDirectResolution(t,"cas_loss"),!0;let[r]=await N().batchGetUpstreamConnections([{owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}]);return r===void 0||he(r)!=="usable"||!Ir(e.connection,r)||!e.provider.connectionSatisfiesRequestedScope(r,e.requestedScope)?!1:(await e.provider.adoptConnectionForDirectResolution(r,"boundary_reread"),!0)}n(fm,"adoptPeerCredentialAtResolutionBoundary");async function Rm(e,t){let r=await wm(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new v({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}}):new v({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}})}n(Rm,"requireUpstreamAuthorizationRedirect");async function bm(e){let t=he(e.connection),r=!!e.forceRefresh,o=!r&&t==="usable"&&e.connection!==void 0&&e.provider.connectionSatisfiesRequestedScope(e.connection,e.requestedScope),i=W(),s=i?await Cr({owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}):void 0;if(i?.debug({event:"upstream_oauth_refresh_decision",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,ownerMode:e.target.owner.mode,connectionFingerprint:s,connectionId:e.connection?.id,accessTokenState:t,forceRefresh:r,willRefresh:!o,expiresAt:e.connection?.expiresAt,connectionUpdatedAt:e.connection?.updatedAt},o?"Reusing stored upstream access token":"Refreshing upstream credential"),o)return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let c;try{c=await wm(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(a){if(e.connection===void 0||!rR(a))throw a;return i?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:a.code,connectionFingerprint:s,connectionId:e.connection.id,rejectedRefreshTokenFingerprint:e.provider.usedRefreshTokenFingerprint,connectionUpdatedAt:e.connection.updatedAt,connectionExpiresAt:e.connection.expiresAt},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),await fm({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope})?{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}:{kind:"connect_required",payload:await Bs({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}if(c==="AUTHORIZED"){let a=e.provider.readUsablePeerAdoption(e.requestedScope);return a!==void 0&&await e.provider.adoptConnectionForDirectResolution(a,"cas_loss"),!e.provider.tokenWriteWasPersisted&&a===void 0?{kind:"connect_required",payload:await Bs({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:void 0,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}:{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}}if(c!=="REDIRECT")throw new v({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${c}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new v({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}});return await fm({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope})?{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}:{kind:"connect_required",payload:await Bs({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}n(bm,"authorizeUpstreamOAuthSession");async function lR(e){let t=await si(e.stateToken),r=await N().consumeUpstreamOAuthState({id:t.id,now:$(new Date)}),o=pR(r);return mR({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),hR(o),o}n(lR,"consumeStoredCallbackState");function pR(e){switch(e.kind){case"consumed":throw new v({message:"OAuth state has already been used",extensionMembers:{[I]:"oauth_state_reused"}});case"missing":throw new v({message:"OAuth state is missing or expired",extensionMembers:{[I]:"oauth_state_expired"}});case"available":return e.record}}n(pR,"readConsumedCallbackState");function mR(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.operationId===e.signedState.operationId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw new v({message:"OAuth callback did not match the initiating request",extensionMembers:{[I]:"oauth_callback_mismatch"}})}n(mR,"assertStoredCallbackStateMatches");function hR(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new v({message:"OAuth state has expired",extensionMembers:{[I]:"oauth_state_expired"}})}n(hR,"assertStoredCallbackStateFresh");async function Bs(e){if(e.owner.mode==="shared"){let r={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,requiresReconsent:!!e.connection};return e.connection!==void 0&&(r.connectionId=e.connection.id),tm(r)}let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,subject:"tool",requiresReconsent:!!e.connection,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return e.connection!==void 0&&(t.connectionId=e.connection.id),ai(t)}n(Bs,"buildOAuthConnectRequiredResponse");async function vm(e){let t=await lR({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=No(t),[o]=await N().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),i={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};o!==void 0&&(i.connection=o);let s=new _t(i),c=await uR(s,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,...e.iss===void 0?{}:{iss:e.iss},resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(c==="AUTHORIZED"){let a=s.readUsablePeerAdoption();if(a!==void 0&&await s.adoptConnectionForDirectResolution(a,"cas_loss"),!s.tokenWriteWasPersisted&&a===void 0)throw new v({message:`OAuth callback storage changed while connecting ${e.upstreamServerId}. Restart the connection flow and try again.`,extensionMembers:{[I]:"upstream_token_exchange_failed"}});return t}throw c!=="REDIRECT"?new v({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${c}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}}):new v({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}})}n(vm,"finishUpstreamOAuthCallback");import{importPKCS8 as fR,SignJWT as gR}from"jose";var Im=1e4,Tm=64*1024,km=2,yR=300,qe=l.string().min(1),SR=l.object({access_token:qe,issued_token_type:l.literal(Bi),token_type:l.string().optional(),expires_in:l.number().int().positive().optional(),scope:qe.optional()}).passthrough(),_R=l.object({id_token:qe,token_type:qe.optional(),expires_in:l.number().int().positive().optional(),refresh_token:qe.optional(),scope:qe.optional()}).passthrough(),wR=l.object({access_token:qe,token_type:qe,expires_in:l.number().int().positive().optional(),scope:qe.optional(),resource:qe.optional(),refresh_token:qe.optional()}).passthrough();function Cm(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(Cm,"formEncodeClientCredential");function RR(e){return e.replaceAll("\\n",`
25
+ import{$ as ja,$a as Uc,$b as xd,$c as wu,$e as fr,$f as Vu,Aa as sc,Ab as id,Ac as Vd,Af as qu,Ag as $n,B as Io,Ba as ac,Bb as sd,Bc as Kd,Bf as zu,Bg as nl,Ca as cc,Cb as ad,Cc as Wd,Cf as Mu,Cg as Lo,Da as dc,Db as cd,Dc as Zd,Df as Mo,Dg as Dn,Ea as uc,Eb as dd,Ec as Yd,Ef as Mn,Eg as ol,Fa as lc,Fb as ud,Fc as Xd,Ff as Nu,Fg as il,Ga as pc,Gb as ld,Gc as Qd,Gf as _r,Gg as sl,Ha as mc,Hb as pd,Hc as eu,Hf as ju,Hg as al,Ia as hc,Ib as md,Ic as tu,If as Li,Ig as cl,Ja as xi,Jb as hd,Jc as ru,Jf as $u,Jg as dl,Ka as fc,Kb as fd,Kc as nu,Kf as Nn,Kg as ul,La as gc,Lb as gd,Lc as ou,Lf as No,Lg as ll,Ma as yc,Mb as yd,Mc as iu,Mf as Du,Mg as Ho,Na as Sc,Nb as Sd,Nc as su,Nf as Lu,Ng as pl,Oa as _c,Ob as _d,Oc as au,Of as Hu,Og as ml,Pa as wc,Pb as wd,Pc as cu,Pf as Bu,Pg as N,Qa as Rc,Qb as Rd,Qc as du,Qf as ye,Qg as J,R as Po,Ra as bc,Rb as bd,Rc as uu,Rf as de,Rg as me,S as ki,Sa as vc,Sb as Ui,Sc as lu,Sf as Fu,Sg as We,T as cr,Ta as Cc,Tb as vd,Tc as pu,Tf as Gu,Tg as X,U as Un,Ua as Ic,Ub as Cd,Uc as mu,Uf as $,Ug as Bo,V as dr,Va as Tc,Vb as Id,Vc as hu,Ve as ku,Vf as Ve,Vg as wg,W as ur,Wa as kc,Wb as Td,Wc as fu,We as be,Wf as wr,Wg as Rg,X as On,Xa as Pc,Xb as kd,Xc as gu,Xe as Pu,Xf as pe,Y as lr,Ya as Ac,Yb as Pd,Yc as yu,Ye as Au,Yf as te,Z as Ma,Za as Ec,Zb as Ad,Zc as Su,Ze as Y,Zf as Ju,_ as Na,_a as xc,_b as Ed,_c as _u,_e as Eu,_f as W,aa as $a,ab as Oc,ac as Ud,ad as Ru,af as xu,ag as lt,ba as Da,bb as qc,bc as Od,bd as pr,bf as gr,bg as Hi,ca as La,cb as zc,cc as qd,cd as mr,cf as I,cg as jo,da as Ha,db as Mc,dc as zd,dd as bu,df as yr,dg as Bi,ea as Ba,eb as Nc,ec as Md,ed as hr,ef as Sr,eg as $o,fa as Fa,fb as jc,fc as Nd,fd as at,ff as ct,fg as jn,ga as Ga,gb as $c,gc as jd,gd as Di,gf as dt,gg as Rr,ha as Ja,hb as Dc,hc as Oi,hd as Oo,hf as qo,hg as Ku,ia as Va,ib as Lc,ic as Ao,id as vu,if as Uu,ig as Ke,ja as Ka,jb as Hc,jc as Eo,jd as zn,jf as Oe,jg as Fi,ka as Wa,kb as Bc,kc as qi,kd as jt,kf as Ou,kg as Gi,l as $e,la as Za,lb as Fc,lc as zi,ld as Cu,lf as Je,lg as Wu,ma as Ya,mb as Gc,mc as Mi,md as Iu,mf as x,mg as Do,na as Nt,nb as Jc,nc as $d,nf as zo,ng as Ji,oa as Pi,ob as Vc,oc as Ni,of as le,og as Vi,pa as Ai,pb as Kc,pc as ji,pf as ut,pg as Zu,qa as qn,qb as Wc,qc as Dd,qf as ug,qg as ne,ra as Ei,rb as Zc,rc as Ld,rf as lg,rg as Yu,s as Mt,sa as Xa,sb as Yc,sc as $i,sd as Tu,sf as pg,sg as Xu,t as Ea,ta as Qa,tb as Xc,tc as xo,tf as mg,tg as Ki,ua as ec,ub as Qc,uc as Uo,uf as hg,ug as Qu,va as tc,vb as ed,vc as Hd,vf as fg,vg as el,wa as rc,wb as td,wc as Bd,wf as gg,wg as Wi,xa as nc,xb as rd,xc as Fd,xf as yg,xg as tl,ya as oc,yb as nd,yc as Gd,yf as Sg,yg as $t,z as Ua,za as ic,zb as od,zc as Jd,zf as _g,zg as rl}from"../chunk-R4PTES5B.js";import"../chunk-CUK3VROF.js";import{a as H}from"../chunk-S4EBLGSU.js";import{a as hl}from"../chunk-6SNZ4DOC.js";import{a as xa}from"../chunk-QGAJTUPE.js";import"../chunk-A3QGJZO7.js";import{A as g,B as z,C as Ti,D as ko,G as l,h as Ci,i as En,j as Oa,k as d,l as qa,m as za,n as b,o as E,p as To,r as q,s as _,t as m,u as M,v as P,w as Ii,x as xn,y as T,z as j}from"../chunk-K4TBJG47.js";import"../chunk-UKQQD2JN.js";import{W as Pe,X as v,Y as K,Z as Aa,_ as Co}from"../chunk-XF3IIUDX.js";import{a as n}from"../chunk-TYV53J3B.js";var bg=Object.create,Fo=Object.defineProperty,vg=Object.getOwnPropertyDescriptor,Cg=Object.getOwnPropertyNames,Ig=Object.getPrototypeOf,Tg=Object.prototype.hasOwnProperty,fl=n((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),gl=n((e,t)=>{let r={};for(var o in e)Fo(r,o,{get:e[o],enumerable:!0});return t&&Fo(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll"),kg=n((e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var i=Cg(t),s=0,c=i.length,a;s<c;s++)a=i[s],!Tg.call(e,a)&&a!==r&&Fo(e,a,{get:(u=>t[u]).bind(null,a),enumerable:!(o=vg(t,a))||o.enumerable});return e},"__copyProps"),yl=n((e,t,r)=>(r=e!=null?bg(Ig(e)):{},kg(t||!e||!e.__esModule?Fo(r,"default",{value:e,enumerable:!0}):r,e)),"__toESM");var Pg=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function Sl(e){return typeof e=="string"&&Pg.has(e.replace(/#$/,""))}n(Sl,"declares2019Dialect");var ts=Symbol.for("mcp.sdk.errorBrands");function Dt(e,t){let r=new Set,o=t;for(;typeof o=="function";){let i=o.mcpBrand;Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof i=="string"&&r.add(i),o=Object.getPrototypeOf(o)}r.size!==0&&Object.defineProperty(e,ts,{value:r,enumerable:!1,configurable:!0})}n(Dt,"stampErrorBrands");function ve(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,ts)){let r=t[ts];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}n(ve,"brandedHasInstance");var ue=(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})({}),mt=class Pl extends Error{static{n(this,"OAuthError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return ve(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 ve(this,t)}constructor(t,r,o){super(r),this.code=t,this.errorUri=o,this.name="OAuthError",Dt(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 Pl(t.error,t.error_description??t.error,t.error_uri)}},ie=(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})({}),re=class extends Error{static{n(this,"SdkError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return ve(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 ve(this,e)}constructor(e,t,r){super(t),this.code=e,this.data=r,this.name="SdkError",Dt(this,new.target)}},Dg=class extends re{static{n(this,"SdkHttpError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r){super(e,t,r),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function Al(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(Al,"resourceUrlFromServerUrl");function El({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return i.startsWith(s)}n(El,"checkResourceAllowed");var Lg="2026-07-28";function xl(e){return e>=Lg}n(xl,"isModernProtocolVersion");function Ul(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(r=>r.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}n(Ul,"appendTextFallbackForNonObject");var Ol=["task","inputRequests","requestState"];function Hg(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Ol.some(t=>t in e)?e:{...e,content:[]}}n(Hg,"normalizeContentlessToolResult");function Bg(){let e=Ti(()=>P([d(),b(),E(),To(),T(d(),e),_(e)])),t=T(d(),e),r=P([d(),b().int()]),o=d(),i=m({ttl:b().optional()}),s=m({taskId:d()}),c=M({progressToken:r.optional(),"io.modelcontextprotocol/related-task":s.optional()}),a=m({_meta:c.optional()}),u=a.extend({task:i.optional()}),p=m({method:d(),params:a.loose().optional()}),h=m({_meta:c.optional()}),f=m({method:d(),params:h.loose().optional()}),y=M({_meta:c.optional()}),S=P([d(),b().int()]),k=y.strict(),w=h.extend({requestId:S.optional(),reason:d().optional()}),C=f.extend({method:g("notifications/cancelled"),params:w}),U=m({src:d(),mimeType:d().optional(),sizes:_(d()).optional(),theme:j(["light","dark"]).optional()}),O=m({icons:_(U).optional()}),L=m({name:d(),title:d().optional()}),F=L.extend({...L.shape,...O.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),ee=xn(m({applyDefaults:E().optional()}),t),G=ko(ce=>ce&&typeof ce=="object"&&!Array.isArray(ce)&&Object.keys(ce).length===0?{form:{}}:ce,xn(m({form:ee.optional(),url:t.optional()}),t.optional())),V=M({list:t.optional(),cancel:t.optional(),requests:M({sampling:M({createMessage:t.optional()}).optional(),elicitation:M({create:t.optional()}).optional()}).optional()}),Be=M({list:t.optional(),cancel:t.optional(),requests:M({tools:M({call:t.optional()}).optional()}).optional()}),oe=m({experimental:T(d(),t).optional(),sampling:m({context:t.optional(),tools:t.optional()}).optional(),elicitation:G.optional(),roots:m({listChanged:E().optional()}).optional(),tasks:V.optional(),extensions:T(d(),t).optional()}),Me=a.extend({protocolVersion:d(),capabilities:oe,clientInfo:F}),D=p.extend({method:g("initialize"),params:Me}),Ee=m({experimental:T(d(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:m({listChanged:E().optional()}).optional(),resources:m({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:m({listChanged:E().optional()}).optional(),tasks:Be.optional(),extensions:T(d(),t).optional()}),Mr=y.extend({protocolVersion:d(),capabilities:Ee,serverInfo:F,instructions:d().optional()}),Gt=f.extend({method:g("notifications/initialized"),params:h.optional()}),tt=p.extend({method:g("ping"),params:a.optional()}),vt=m({progress:b(),total:z(b()),message:z(d())}),Ne=m({...h.shape,...vt.shape,progressToken:r}),rt=f.extend({method:g("notifications/progress"),params:Ne}),Jt=a.extend({cursor:o.optional()}),Fe=p.extend({params:Jt.optional()}),Ge=y.extend({nextCursor:o.optional()}),Vt=m({uri:d(),mimeType:z(d()),_meta:T(d(),q()).optional()}),Kt=Vt.extend({text:d()}),Ct=d().refine(ce=>{try{return atob(ce),!0}catch{return!1}},{message:"Invalid Base64 string"}),Wt=Vt.extend({blob:Ct}),je=j(["user","assistant"]),xe=m({audience:_(je).optional(),priority:b().min(0).max(1).optional(),lastModified:En.datetime({offset:!0}).optional()}),It=m({...L.shape,...O.shape,uri:d(),description:z(d()),mimeType:z(d()),size:z(b()),annotations:xe.optional(),_meta:z(M({}))}),Nr=m({...L.shape,...O.shape,uriTemplate:d(),description:z(d()),mimeType:z(d()),annotations:xe.optional(),_meta:z(M({}))}),jr=Fe.extend({method:g("resources/list")}),$r=Ge.extend({resources:_(It)}),nt=Fe.extend({method:g("resources/templates/list")}),Zt=Ge.extend({resourceTemplates:_(Nr)}),Tt=a.extend({uri:d()}),Dr=Tt,Lr=p.extend({method:g("resources/read"),params:Dr}),Hr=y.extend({contents:_(P([Kt,Wt]))}),Br=f.extend({method:g("notifications/resources/list_changed"),params:h.optional()}),Fr=Tt,Gr=p.extend({method:g("resources/subscribe"),params:Fr}),Jr=Tt,Vr=p.extend({method:g("resources/unsubscribe"),params:Jr}),Kr=h.extend({uri:d()}),Wr=f.extend({method:g("notifications/resources/updated"),params:Kr}),Zr=m({name:d(),description:z(d()),required:z(E())}),Yr=m({...L.shape,...O.shape,description:z(d()),arguments:z(_(Zr)),_meta:z(M({}))}),Xr=Fe.extend({method:g("prompts/list")}),Qr=Ge.extend({prompts:_(Yr)}),en=a.extend({name:d(),arguments:T(d(),d()).optional()}),tn=p.extend({method:g("prompts/get"),params:en}),kt=m({type:g("text"),text:d(),annotations:xe.optional(),_meta:T(d(),q()).optional()}),Pt=m({type:g("image"),data:Ct,mimeType:d(),annotations:xe.optional(),_meta:T(d(),q()).optional()}),At=m({type:g("audio"),data:Ct,mimeType:d(),annotations:xe.optional(),_meta:T(d(),q()).optional()}),rn=m({type:g("tool_use"),name:d(),id:d(),input:T(d(),q()),_meta:T(d(),q()).optional()}),ot=m({type:g("resource"),resource:P([Kt,Wt]),annotations:xe.optional(),_meta:T(d(),q()).optional()}),nn=It.extend({type:g("resource_link")}),ke=P([kt,Pt,At,nn,ot]),Yt=m({role:je,content:ke}),Xt=y.extend({description:d().optional(),messages:_(Yt)}),Et=f.extend({method:g("notifications/prompts/list_changed"),params:h.optional()}),on=m({title:d().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Qt=m({taskSupport:j(["required","optional","forbidden"]).optional()}),xt=m({...L.shape,...O.shape,description:d().optional(),inputSchema:m({type:g("object"),properties:T(d(),e).optional(),required:_(d()).optional()}).catchall(q()),outputSchema:m({type:g("object"),properties:T(d(),e).optional(),required:_(d()).optional()}).catchall(q()).optional(),annotations:on.optional(),execution:Qt.optional(),_meta:T(d(),q()).optional()}),er=Fe.extend({method:g("tools/list")}),tr=Ge.extend({tools:_(xt)}),rr=y.extend({content:_(ke),structuredContent:T(d(),q()).optional(),isError:E().optional()}),ae=u.extend({name:d(),arguments:T(d(),q()).optional()}),sn=p.extend({method:g("tools/call"),params:ae}),so=f.extend({method:g("notifications/tools/list_changed"),params:h.optional()}),nr=j(["debug","info","notice","warning","error","critical","alert","emergency"]),an=a.extend({level:nr}),cn=p.extend({method:g("logging/setLevel"),params:an}),dn=h.extend({level:nr,logger:d().optional(),data:q()}),un=f.extend({method:g("notifications/message"),params:dn}),ln=m({name:d().optional()}),pn=m({hints:_(ln).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),mn=m({mode:j(["auto","required","none"]).optional()}),ao=m({type:g("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:_(ke),structuredContent:m({}).loose().optional(),isError:E().optional(),_meta:T(d(),q()).optional()}),hn=Ii("type",[kt,Pt,At]),it=Ii("type",[kt,Pt,At,rn,ao]),fn=m({role:je,content:P([it,_(it)]),_meta:T(d(),q()).optional()}),gn=u.extend({messages:_(fn),modelPreferences:pn.optional(),systemPrompt:d().optional(),includeContext:j(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:_(d()).optional(),metadata:t.optional(),tools:_(xt).optional(),toolChoice:mn.optional()}),yn=p.extend({method:g("sampling/createMessage"),params:gn}),Sn=y.extend({model:d(),stopReason:z(j(["endTurn","stopSequence","maxTokens"]).or(d())),role:je,content:hn}),_n=y.extend({model:d(),stopReason:z(j(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:je,content:P([it,_(it)])}),wn=m({type:g("boolean"),title:d().optional(),description:d().optional(),default:E().optional()}),Rn=m({type:g("string"),title:d().optional(),description:d().optional(),minLength:b().optional(),maxLength:b().optional(),format:j(["email","uri","date","date-time"]).optional(),default:d().optional()}),bn=m({type:j(["number","integer"]),title:d().optional(),description:d().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),vn=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),default:d().optional()}),Cn=m({type:g("string"),title:d().optional(),description:d().optional(),oneOf:_(m({const:d(),title:d()})),default:d().optional()}),In=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),enumNames:_(d()).optional(),default:d().optional()}),Tn=P([vn,Cn]),Ut=m({type:g("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({type:g("string"),enum:_(d())}),default:_(d()).optional()}),Ot=m({type:g("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({anyOf:_(m({const:d(),title:d()}))}),default:_(d()).optional()}),co=P([Ut,Ot]),uo=P([In,Tn,co]),we=P([uo,wn,Rn,bn]),Re=u.extend({mode:g("form").optional(),message:d(),requestedSchema:m({type:g("object"),properties:T(d(),we),required:_(d()).optional()}).catchall(q())}),kn=u.extend({mode:g("url"),message:d(),elicitationId:d(),url:d().url()}),Ue=P([Re,kn]),lo=p.extend({method:g("elicitation/create"),params:Ue}),po=h.extend({elicitationId:d()}),mo=f.extend({method:g("notifications/elicitation/complete"),params:po}),ho=y.extend({action:j(["accept","decline","cancel"]),content:ko(ce=>ce===null?void 0:ce,T(d(),P([d(),b(),E(),_(d())])).optional())}),fo=m({type:g("ref/resource"),uri:d()}),go=m({type:g("ref/prompt"),name:d()}),yo=a.extend({ref:P([go,fo]),argument:m({name:d(),value:d()}),context:m({arguments:T(d(),d()).optional()}).optional()}),Pn=p.extend({method:g("completion/complete"),params:yo}),So=y.extend({completion:M({values:_(d()).max(100),total:z(b().int()),hasMore:z(E())})}),_o=m({uri:d().startsWith("file://"),name:d().optional(),_meta:T(d(),q()).optional()}),or=p.extend({method:g("roots/list"),params:a.optional()}),An=y.extend({roots:_(_o)}),wo=f.extend({method:g("notifications/roots/list_changed"),params:h.optional()}),Ro=M({ttl:b().optional(),pollInterval:b().optional()}),bo=j(["working","input_required","completed","failed","cancelled"]),st=m({taskId:d(),status:bo,ttl:P([b(),To()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:z(b()),statusMessage:z(d())}),fe=y.extend({task:st}),vo=h.merge(st),qt=f.extend({method:g("notifications/tasks/status"),params:vo}),ir=p.extend({method:g("tasks/get"),params:a.extend({taskId:d()})}),sr=y.merge(st),ar=p.extend({method:g("tasks/result"),params:a.extend({taskId:d()})}),vi=y.loose(),ge=Fe.extend({method:g("tasks/list")}),Z=Ge.extend({tasks:_(st)}),zt=p.extend({method:g("tasks/cancel"),params:a.extend({taskId:d()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:i,RelatedTaskMetadataSchema:s,RequestMetaSchema:c,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:u,RequestSchema:p,NotificationsParamsSchema:h,NotificationSchema:f,ResultSchema:y,RequestIdSchema:S,EmptyResultSchema:k,CancelledNotificationParamsSchema:w,CancelledNotificationSchema:C,IconSchema:U,IconsSchema:O,BaseMetadataSchema:L,ImplementationSchema:F,ClientTasksCapabilitySchema:V,ServerTasksCapabilitySchema:Be,ClientCapabilitiesSchema:oe,InitializeRequestParamsSchema:Me,InitializeRequestSchema:D,ServerCapabilitiesSchema:Ee,InitializeResultSchema:Mr,InitializedNotificationSchema:Gt,PingRequestSchema:tt,ProgressSchema:vt,ProgressNotificationParamsSchema:Ne,ProgressNotificationSchema:rt,PaginatedRequestParamsSchema:Jt,PaginatedRequestSchema:Fe,PaginatedResultSchema:Ge,ResourceContentsSchema:Vt,TextResourceContentsSchema:Kt,BlobResourceContentsSchema:Wt,RoleSchema:je,AnnotationsSchema:xe,ResourceSchema:It,ResourceTemplateSchema:Nr,ListResourcesRequestSchema:jr,ListResourcesResultSchema:$r,ListResourceTemplatesRequestSchema:nt,ListResourceTemplatesResultSchema:Zt,ResourceRequestParamsSchema:Tt,ReadResourceRequestParamsSchema:Dr,ReadResourceRequestSchema:Lr,ReadResourceResultSchema:Hr,ResourceListChangedNotificationSchema:Br,SubscribeRequestParamsSchema:Fr,SubscribeRequestSchema:Gr,UnsubscribeRequestParamsSchema:Jr,UnsubscribeRequestSchema:Vr,ResourceUpdatedNotificationParamsSchema:Kr,ResourceUpdatedNotificationSchema:Wr,PromptArgumentSchema:Zr,PromptSchema:Yr,ListPromptsRequestSchema:Xr,ListPromptsResultSchema:Qr,GetPromptRequestParamsSchema:en,GetPromptRequestSchema:tn,TextContentSchema:kt,ImageContentSchema:Pt,AudioContentSchema:At,ToolUseContentSchema:rn,EmbeddedResourceSchema:ot,ResourceLinkSchema:nn,ContentBlockSchema:ke,PromptMessageSchema:Yt,GetPromptResultSchema:Xt,PromptListChangedNotificationSchema:Et,ToolAnnotationsSchema:on,ToolExecutionSchema:Qt,ToolSchema:xt,ListToolsRequestSchema:er,ListToolsResultSchema:tr,CallToolResultSchema:rr,CallToolRequestParamsSchema:ae,CallToolRequestSchema:sn,ToolListChangedNotificationSchema:so,LoggingLevelSchema:nr,SetLevelRequestParamsSchema:an,SetLevelRequestSchema:cn,LoggingMessageNotificationParamsSchema:dn,LoggingMessageNotificationSchema:un,ModelHintSchema:ln,ModelPreferencesSchema:pn,ToolChoiceSchema:mn,ToolResultContentSchema:ao,SamplingContentSchema:hn,SamplingMessageContentBlockSchema:it,SamplingMessageSchema:fn,CreateMessageRequestParamsSchema:gn,CreateMessageRequestSchema:yn,CreateMessageResultSchema:Sn,CreateMessageResultWithToolsSchema:_n,BooleanSchemaSchema:wn,StringSchemaSchema:Rn,NumberSchemaSchema:bn,UntitledSingleSelectEnumSchemaSchema:vn,TitledSingleSelectEnumSchemaSchema:Cn,LegacyTitledEnumSchemaSchema:In,SingleSelectEnumSchemaSchema:Tn,UntitledMultiSelectEnumSchemaSchema:Ut,TitledMultiSelectEnumSchemaSchema:Ot,MultiSelectEnumSchemaSchema:co,EnumSchemaSchema:uo,PrimitiveSchemaDefinitionSchema:we,ElicitRequestFormParamsSchema:Re,ElicitRequestURLParamsSchema:kn,ElicitRequestParamsSchema:Ue,ElicitRequestSchema:lo,ElicitationCompleteNotificationParamsSchema:po,ElicitationCompleteNotificationSchema:mo,ElicitResultSchema:ho,ResourceTemplateReferenceSchema:fo,PromptReferenceSchema:go,CompleteRequestParamsSchema:yo,CompleteRequestSchema:Pn,CompleteResultSchema:So,RootSchema:_o,ListRootsRequestSchema:or,ListRootsResultSchema:An,RootsListChangedNotificationSchema:wo,TaskCreationParamsSchema:Ro,TaskStatusSchema:bo,TaskSchema:st,CreateTaskResultSchema:fe,TaskStatusNotificationParamsSchema:vo,TaskStatusNotificationSchema:qt,GetTaskRequestSchema:ir,GetTaskResultSchema:sr,GetTaskPayloadRequestSchema:ar,GetTaskPayloadResultSchema:vi,ListTasksRequestSchema:ge,ListTasksResultSchema:Z,CancelTaskRequestSchema:zt,CancelTaskResultSchema:y.merge(st),ClientRequestSchema:P([tt,D,Pn,cn,tn,Xr,jr,nt,Lr,Gr,Vr,sn,er,ir,ar,ge,zt]),ClientNotificationSchema:P([C,rt,Gt,wo,qt]),ClientResultSchema:P([k,Sn,_n,ho,An,sr,Z,fe]),ServerRequestSchema:P([tt,yn,lo,or,ir,ar,ge,zt]),ServerNotificationSchema:P([C,rt,un,Wr,Br,so,Et,qt,mo]),ServerResultSchema:P([k,Mr,So,Xt,Qr,$r,Zt,Hr,rr,tr,sr,Z,fe]),CallToolResultWireSchema:q().superRefine((ce,dg)=>{if(!(typeof ce!="object"||ce===null||Array.isArray(ce)||ce.content!==void 0)){for(let Pa of Ol)if(Pa in ce){dg.addIssue({code:"custom",message:`content is required when the body carries '${Pa}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(Hg).pipe(rr)}}n(Bg,"build$1");var Fg;function as(){return Fg??=Bg()}n(as,"buildSchemas2025");function ql(e){return e.type!=="object"}n(ql,"isNonObjectJsonSchemaRoot");var Gg=new Set(["const","enum","default","examples"]),Jg=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function _l(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}n(_l,"establishesNewBase");function Vg(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(_l(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=Sl(e.$schema)&&e.$recursiveAnchor!==!0,o=n((i,s)=>{if(Array.isArray(i))return i.map(u=>o(u,!1));if(i===null||typeof i!="object"||!s&&_l(i.$id))return i;let c={},a=!1;for(let[u,p]of Object.entries(i))s?c[u]=o(p,!1):(u==="$ref"||u==="$dynamicRef")&&typeof p=="string"?c[u]=p==="#"?"#/properties/result":p.startsWith("#/")?`#/properties/result${p.slice(1)}`:p:u==="$recursiveRef"&&p==="#"&&r?a=!0:Gg.has(u)?c[u]=p:Jg.has(u)?c[u]=o(p,!0):c[u]=o(p,!1);return a&&("$ref"in c?c.allOf=[...Array.isArray(c.allOf)?c.allOf:[],{$ref:"#/properties/result"}]:c.$ref="#/properties/result"),c},"rewriteRefs");return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}n(Vg,"wrapOutputSchemaForLegacy");var zl={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},Ml={"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},Kg={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},Go;function Wo(){if(Go)return Go;let e=as();return Go={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}},Go}n(Wo,"registryMaps");function Wg(){Wo()}n(Wg,"warmRegistryMaps2025");function Nl(e){return Object.prototype.hasOwnProperty.call(zl,e)}n(Nl,"hasRequestMethod2025");function jl(e){return Object.prototype.hasOwnProperty.call(Ml,e)}n(jl,"hasNotificationMethod2025");function Zg(e){return Object.prototype.hasOwnProperty.call(Kg,e)}n(Zg,"hasResultMethod");function Yg(e){return Zg(e)?Wo().resultSchemas[e]:void 0}n(Yg,"getResultSchema");function Xg(e){return Nl(e)?Wo().requestSchemas[e]:void 0}n(Xg,"getRequestSchema");function Qg(e){return jl(e)?Wo().notificationSchemas[e]:void 0}n(Qg,"getNotificationSchema");var aT=Object.keys(zl),cT=Object.keys(Ml);function rs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(rs,"isPlainObject$4");function Jo(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}n(Jo,"triState$1");var wl={ok:!1,reason:"not-in-era"};function Rl(e){return rs(e)&&rs(e.outputSchema)&&ql(e.outputSchema)}n(Rl,"toolNeedsLegacyWrap");var cs={era:"2025-11-25",hasRequestMethod:Nl,hasNotificationMethod:jl,validateRequest:n((e,t)=>Jo(Xg(e),t),"validateRequest"),validateResult:n((e,t)=>Jo(Yg(e),t),"validateResult"),validateNotification:n((e,t)=>Jo(Qg(e),t),"validateNotification"),hasInputRequestMethod:n(()=>!1,"hasInputRequestMethod"),validateInputRequest:n(()=>wl,"validateInputRequest"),validateInputResponse:n(()=>wl,"validateInputResponse"),samplingResultVariant:n(((e,t)=>{let r=as();return Jo(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:n(e=>{},"outboundEnvelope"),validateEnvelopeMeta:n(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let r=Ul(e),o=r.structuredContent;if(o===void 0)return r;let i=typeof o!="object"||o===null||Array.isArray(o),s=t!==void 0&&ql(t);return!i&&!s?r:{...r,structuredContent:{result:o}}},decodeResult(e,t){if(rs(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:r}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;return!Array.isArray(r)||!r.some(o=>Rl(o))?t:{...t,tools:r.map(o=>Rl(o)?{...o,outputSchema:Vg(o.outputSchema)}:o)}},encodeErrorCode:n(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:n(e=>{},"checkInboundEnvelope")};function ey(){let e=Ti(()=>P([d(),b(),E(),To(),T(d(),e),_(e)])),t=T(d(),e),r=P([d(),b().int()]),o=d(),i=P([d(),b().int()]),s=j(["user","assistant"]),c=j(["debug","info","notice","warning","error","critical","alert","emergency"]),a=d().refine(Z=>{try{return atob(Z),!0}catch{return!1}},{message:"Invalid Base64 string"}),u=m({ttl:b().optional()}),p=m({taskId:d()}),h=M({progressToken:r.optional(),"io.modelcontextprotocol/related-task":p.optional()}),f=m({_meta:h.optional()}),y=f.extend({task:u.optional()}),S=m({_meta:h.optional()}),k=m({method:d(),params:S.loose().optional()}),w=m({src:d(),mimeType:d().optional(),sizes:_(d()).optional(),theme:j(["light","dark"]).optional()}),C=m({icons:_(w).optional()}),U=m({name:d(),title:d().optional()}),O=U.extend({...U.shape,...C.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),L=xn(m({applyDefaults:E().optional()}),t),F=ko(Z=>Z&&typeof Z=="object"&&!Array.isArray(Z)&&Object.keys(Z).length===0?{form:{}}:Z,xn(m({form:L.optional(),url:t.optional()}),t.optional())),ee=M({list:t.optional(),cancel:t.optional(),requests:M({sampling:M({createMessage:t.optional()}).optional(),elicitation:M({create:t.optional()}).optional()}).optional()}),G=M({list:t.optional(),cancel:t.optional(),requests:M({tools:M({call:t.optional()}).optional()}).optional()}),V=m({experimental:T(d(),t).optional(),sampling:m({context:t.optional(),tools:t.optional()}).optional(),elicitation:F.optional(),roots:m({listChanged:E().optional()}).optional(),tasks:ee.optional(),extensions:T(d(),t).optional()}),Be=m({experimental:T(d(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:m({listChanged:E().optional()}).optional(),resources:m({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:m({listChanged:E().optional()}).optional(),tasks:G.optional(),extensions:T(d(),t).optional()}),oe=m({progress:b(),total:z(b()),message:z(d())}),Me=m({...S.shape,...oe.shape,progressToken:r}),D=k.extend({method:g("notifications/progress"),params:Me}),Ee=S.extend({level:c,logger:d().optional(),data:q()}),Mr=k.extend({method:g("notifications/message"),params:Ee}),Gt=m({uri:d(),mimeType:z(d()),_meta:T(d(),q()).optional()}),tt=Gt.extend({text:d()}),vt=Gt.extend({blob:a}),Ne=m({audience:_(s).optional(),priority:b().min(0).max(1).optional(),lastModified:En.datetime({offset:!0}).optional()}),rt=m({...U.shape,...C.shape,uri:d(),description:z(d()),mimeType:z(d()),size:z(b()),annotations:Ne.optional(),_meta:z(M({}))}),Jt=m({...U.shape,...C.shape,uriTemplate:d(),description:z(d()),mimeType:z(d()),annotations:Ne.optional(),_meta:z(M({}))}),Fe=k.extend({method:g("notifications/resources/list_changed"),params:S.optional()}),Ge=S.extend({uri:d()}),Vt=k.extend({method:g("notifications/resources/updated"),params:Ge}),Kt=m({name:d(),description:z(d()),required:z(E())}),Ct=m({...U.shape,...C.shape,description:z(d()),arguments:z(_(Kt)),_meta:z(M({}))}),Wt=k.extend({method:g("notifications/prompts/list_changed"),params:S.optional()}),je=m({type:g("text"),text:d(),annotations:Ne.optional(),_meta:T(d(),q()).optional()}),xe=m({type:g("image"),data:a,mimeType:d(),annotations:Ne.optional(),_meta:T(d(),q()).optional()}),It=m({type:g("audio"),data:a,mimeType:d(),annotations:Ne.optional(),_meta:T(d(),q()).optional()}),Nr=m({type:g("tool_use"),name:d(),id:d(),input:T(d(),q()),_meta:T(d(),q()).optional()}),jr=m({type:g("resource"),resource:P([tt,vt]),annotations:Ne.optional(),_meta:T(d(),q()).optional()}),$r=rt.extend({type:g("resource_link")}),nt=P([je,xe,It,$r,jr]),Zt=m({role:s,content:nt}),Tt=m({title:d().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Dr=k.extend({method:g("notifications/tools/list_changed"),params:S.optional()}),Lr=m({name:d().optional()}),Hr=m({hints:_(Lr).optional(),costPriority:b().min(0).max(1).optional(),speedPriority:b().min(0).max(1).optional(),intelligencePriority:b().min(0).max(1).optional()}),Br=m({mode:j(["auto","required","none"]).optional()}),Fr=m({type:g("boolean"),title:d().optional(),description:d().optional(),default:E().optional()}),Gr=m({type:g("string"),title:d().optional(),description:d().optional(),minLength:b().optional(),maxLength:b().optional(),format:j(["email","uri","date","date-time"]).optional(),default:d().optional()}),Jr=m({type:j(["number","integer"]),title:d().optional(),description:d().optional(),minimum:b().optional(),maximum:b().optional(),default:b().optional()}),Vr=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),default:d().optional()}),Kr=m({type:g("string"),title:d().optional(),description:d().optional(),oneOf:_(m({const:d(),title:d()})),default:d().optional()}),Wr=m({type:g("string"),title:d().optional(),description:d().optional(),enum:_(d()),enumNames:_(d()).optional(),default:d().optional()}),Zr=P([Vr,Kr]),Yr=m({type:g("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({type:g("string"),enum:_(d())}),default:_(d()).optional()}),Xr=m({type:g("array"),title:d().optional(),description:d().optional(),minItems:b().optional(),maxItems:b().optional(),items:m({anyOf:_(m({const:d(),title:d()}))}),default:_(d()).optional()}),Qr=P([Yr,Xr]),en=P([Wr,Zr,Qr]),tn=P([en,Fr,Gr,Jr]),kt=y.extend({mode:g("form").optional(),message:d(),requestedSchema:m({type:g("object"),properties:T(d(),tn),required:_(d()).optional()}).catchall(q())}),Pt=m({type:g("ref/resource"),uri:d()}),At=m({type:g("ref/prompt"),name:d()}),rn=m({uri:d().startsWith("file://"),name:d().optional(),_meta:T(d(),q()).optional()}),ot=V.shape,nn=m({experimental:ot.experimental,sampling:ot.sampling,elicitation:ot.elicitation,roots:ot.roots,extensions:ot.extensions}),ke=Be.shape,Yt=m({experimental:ke.experimental,logging:ke.logging,completions:ke.completions,prompts:ke.prompts,resources:ke.resources,tools:ke.tools,extensions:ke.extensions}),Xt=M({progressToken:r.optional(),[cr]:d(),[Un]:O.optional(),[ur]:nn,[On]:c.optional()}),Et=m({...U.shape,...C.shape,description:d().optional(),inputSchema:M({$schema:d().optional(),type:g("object")}),outputSchema:M({$schema:d().optional()}).optional(),annotations:Tt.optional(),_meta:T(d(),q()).optional()}),on=m({type:g("tool_result"),toolUseId:d(),content:_(nt),structuredContent:q().optional(),isError:E().optional(),_meta:T(d(),q()).optional()}),Qt=P([je,xe,It,Nr,on]),xt=m({role:s,content:P([Qt,_(Qt)]),_meta:T(d(),q()).optional()}),er=d(),tr=M({[dr]:O.optional().catch(void 0)}),rr=tr.optional();function ae(Z){return M({_meta:rr,resultType:er.default("complete"),...Z})}n(ae,"wireResult");let sn=ae({}),so=ae({nextCursor:o.optional()}),nr=ae({content:_(nt),structuredContent:q().optional(),isError:E().optional()}),an=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),tools:_(Et),nextCursor:o.optional()}),cn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),prompts:_(Ct),nextCursor:o.optional()}),dn=ae({description:d().optional(),messages:_(Zt)}),un=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),resources:_(rt),nextCursor:o.optional()}),ln=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),resourceTemplates:_(Jt),nextCursor:o.optional()}),pn=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),contents:_(P([tt,vt]))}),mn=ae({completion:m({values:_(d()).max(100),total:b().int().optional(),hasMore:E().optional()}).loose()}),ao=ae({ttlMs:b().int().min(0),cacheScope:j(["public","private"])}),hn=ae({ttlMs:b().int().min(0).catch(0),cacheScope:j(["public","private"]).catch("private"),supportedVersions:_(d()),capabilities:Yt,instructions:d().optional()}),it=m({messages:_(xt),modelPreferences:Hr.optional(),systemPrompt:d().optional(),includeContext:j(["none","thisServer","allServers"]).optional(),temperature:b().optional(),maxTokens:b().int(),stopSequences:_(d()).optional(),metadata:t.optional(),tools:_(Et).optional(),toolChoice:Br.optional()}),fn=m({method:g("sampling/createMessage"),params:it}),gn=m({method:g("roots/list"),params:m({_meta:T(d(),q()).optional()}).optional()}),yn=m({...xt.shape,model:d(),stopReason:d().optional()}),Sn=m({roots:_(rn)}),_n=m({action:j(["accept","decline","cancel"]),content:T(d(),P([d(),b(),E(),_(d())])).optional()}),wn=m({mode:g("url"),message:d(),url:d().url()}),Rn=P([kt,wn]),bn=m({method:g("elicitation/create"),params:Rn}),vn=P([fn,gn,bn]),Cn=P([yn,Sn,_n]),In=T(d(),vn),Tn=T(d(),Cn),Ut=ae({inputRequests:In.optional(),requestState:d().optional()}),Ot={inputResponses:Tn.optional(),requestState:d().optional()},co=m({_meta:Xt,...Ot}),uo=M({progressToken:r.optional()});function we(Z,zt){return m({method:g(Z),params:m({_meta:Xt,...zt})})}n(we,"wireRequest");function Re(Z,zt){return m({method:g(Z),params:m({_meta:uo.optional(),...zt}).optional()})}n(Re,"dispatchRequest");let kn={name:d(),arguments:T(d(),q()).optional(),...Ot},Ue={cursor:o.optional()},lo=we("tools/call",kn),po=we("tools/list",Ue),mo=we("prompts/list",Ue),ho=we("prompts/get",{name:d(),arguments:T(d(),d()).optional(),...Ot}),fo=we("resources/list",Ue),go=we("resources/templates/list",Ue),yo=we("resources/read",{uri:d(),...Ot}),Pn={ref:P([At,Pt]),argument:m({name:d(),value:d()}),context:m({arguments:T(d(),d()).optional()}).optional()},So=we("completion/complete",Pn),_o=we("server/discover",{}),or=m({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:_(d()).optional()}),An={notifications:or},wo=we("subscriptions/listen",An),Ro=tr.extend({"io.modelcontextprotocol/subscriptionId":i}),bo=M({_meta:Ro,resultType:er.default("complete")}),st={"tools/call":Re("tools/call",kn),"tools/list":Re("tools/list",Ue),"prompts/get":Re("prompts/get",{name:d(),arguments:T(d(),d()).optional()}),"prompts/list":Re("prompts/list",Ue),"resources/list":Re("resources/list",Ue),"resources/templates/list":Re("resources/templates/list",Ue),"resources/read":Re("resources/read",{uri:d()}),"completion/complete":Re("completion/complete",Pn),"server/discover":Re("server/discover",{}),"subscriptions/listen":Re("subscriptions/listen",An)};function fe(Z){return M({_meta:rr,...Z})}n(fe,"liftedResult");let vo={"tools/call":fe({content:_(nt),structuredContent:q().optional(),isError:E().optional()}),"tools/list":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),tools:_(Et),nextCursor:o.optional()}),"prompts/get":fe({description:d().optional(),messages:_(Zt)}),"prompts/list":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),prompts:_(Ct),nextCursor:o.optional()}),"resources/list":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),resources:_(rt),nextCursor:o.optional()}),"resources/templates/list":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),resourceTemplates:_(Jt),nextCursor:o.optional()}),"resources/read":fe({ttlMs:b().int().min(0),cacheScope:j(["public","private"]),contents:_(P([tt,vt]))}),"completion/complete":fe({completion:m({values:_(d()).max(100),total:b().int().optional(),hasMore:E().optional()}).loose()}),"server/discover":fe({ttlMs:b().int().min(0).catch(0),cacheScope:j(["public","private"]).catch("private"),supportedVersions:_(d()),capabilities:Yt,instructions:d().optional()}),"subscriptions/listen":fe({})},qt=M({"io.modelcontextprotocol/subscriptionId":i.optional()}),ir=m({method:g("notifications/subscriptions/acknowledged"),params:m({_meta:qt.optional(),notifications:or})}),sr=m({_meta:qt.optional(),requestId:i,reason:d().optional()}),ar=m({method:g("notifications/cancelled"),params:sr}),vi={"notifications/cancelled":ar,"notifications/progress":D,"notifications/message":Mr,"notifications/resources/updated":Vt,"notifications/resources/list_changed":Fe,"notifications/tools/list_changed":Dr,"notifications/prompts/list_changed":Wt,"notifications/subscriptions/acknowledged":ir},ge=n(Z=>m({jsonrpc:g("2.0"),id:P([d(),b().int()]),result:Z}).strict(),"wireResultResponse");return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:i,RoleSchema:s,LoggingLevelSchema:c,TaskMetadataSchema:u,RelatedTaskMetadataSchema:p,RequestMetaSchema:h,BaseRequestParamsSchema:f,TaskAugmentedRequestParamsSchema:y,NotificationsParamsSchema:S,NotificationSchema:k,IconSchema:w,IconsSchema:C,BaseMetadataSchema:U,ImplementationSchema:O,ClientTasksCapabilitySchema:ee,ServerTasksCapabilitySchema:G,ClientCapabilitiesSchema:V,ServerCapabilitiesSchema:Be,ProgressSchema:oe,ProgressNotificationParamsSchema:Me,ProgressNotificationSchema:D,LoggingMessageNotificationParamsSchema:Ee,LoggingMessageNotificationSchema:Mr,ResourceContentsSchema:Gt,TextResourceContentsSchema:tt,BlobResourceContentsSchema:vt,AnnotationsSchema:Ne,ResourceSchema:rt,ResourceTemplateSchema:Jt,ResourceListChangedNotificationSchema:Fe,ResourceUpdatedNotificationParamsSchema:Ge,ResourceUpdatedNotificationSchema:Vt,PromptArgumentSchema:Kt,PromptSchema:Ct,PromptListChangedNotificationSchema:Wt,TextContentSchema:je,ImageContentSchema:xe,AudioContentSchema:It,ToolUseContentSchema:Nr,EmbeddedResourceSchema:jr,ResourceLinkSchema:$r,ContentBlockSchema:nt,PromptMessageSchema:Zt,ToolAnnotationsSchema:Tt,ToolListChangedNotificationSchema:Dr,ModelHintSchema:Lr,ModelPreferencesSchema:Hr,ToolChoiceSchema:Br,BooleanSchemaSchema:Fr,StringSchemaSchema:Gr,NumberSchemaSchema:Jr,UntitledSingleSelectEnumSchemaSchema:Vr,TitledSingleSelectEnumSchemaSchema:Kr,LegacyTitledEnumSchemaSchema:Wr,SingleSelectEnumSchemaSchema:Zr,UntitledMultiSelectEnumSchemaSchema:Yr,TitledMultiSelectEnumSchemaSchema:Xr,MultiSelectEnumSchemaSchema:Qr,EnumSchemaSchema:en,PrimitiveSchemaDefinitionSchema:tn,ElicitRequestFormParamsSchema:kt,ResourceTemplateReferenceSchema:Pt,PromptReferenceSchema:At,RootSchema:rn,ClientCapabilities2026Schema:nn,ServerCapabilities2026Schema:Yt,RequestMetaEnvelopeSchema:Xt,ToolSchema:Et,ToolResultContentSchema:on,SamplingMessageContentBlockSchema:Qt,SamplingMessageSchema:xt,ResultTypeSchema:er,ResultMetaSchema:tr,ResultSchema:sn,PaginatedResultSchema:so,CallToolResultSchema:nr,ListToolsResultSchema:an,ListPromptsResultSchema:cn,GetPromptResultSchema:dn,ListResourcesResultSchema:un,ListResourceTemplatesResultSchema:ln,ReadResourceResultSchema:pn,CompleteResultSchema:mn,CacheableResultSchema:ao,DiscoverResultSchema:hn,CreateMessageRequestParamsSchema:it,CreateMessageRequestSchema:fn,ListRootsRequestSchema:gn,CreateMessageResultSchema:yn,ListRootsResultSchema:Sn,ElicitResultSchema:_n,ElicitRequestURLParamsSchema:wn,ElicitRequestParamsSchema:Rn,ElicitRequestSchema:bn,InputRequestSchema:vn,InputResponseSchema:Cn,InputRequestsSchema:In,InputResponsesSchema:Tn,InputRequiredResultSchema:Ut,InputResponseRequestParamsSchema:co,CallToolRequestSchema:lo,ListToolsRequestSchema:po,ListPromptsRequestSchema:mo,GetPromptRequestSchema:ho,ListResourcesRequestSchema:fo,ListResourceTemplatesRequestSchema:go,ReadResourceRequestSchema:yo,CompleteRequestSchema:So,DiscoverRequestSchema:_o,SubscriptionFilterSchema:or,SubscriptionsListenRequestSchema:wo,SubscriptionsListenResultMetaSchema:Ro,SubscriptionsListenResultSchema:bo,dispatchRequestSchemas:st,dispatchResultSchemas:vo,NotificationMetaSchema:qt,SubscriptionsAcknowledgedNotificationSchema:ir,CancelledNotificationParamsSchema:sr,CancelledNotificationSchema:ar,notificationSchemas2026:vi,JSONRPCResultResponseSchema:ge(sn),CallToolResultResponseSchema:ge(P([nr,Ut])),ListToolsResultResponseSchema:ge(an),ListPromptsResultResponseSchema:ge(cn),GetPromptResultResponseSchema:ge(P([dn,Ut])),ListResourcesResultResponseSchema:ge(un),ListResourceTemplatesResultResponseSchema:ge(ln),ReadResourceResultResponseSchema:ge(P([pn,Ut])),CompleteResultResponseSchema:ge(mn),DiscoverResultResponseSchema:ge(hn)}}n(ey,"build");var ty;function pt(){return ty??=ey()}n(pt,"buildSchemas2026");var ry=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function ny(e){return ry.includes(e)}n(ny,"isCacheableResultMethod");var ds=Symbol("modelcontextprotocol.resultCacheHintFallback");function oy(e){return e[ds]}n(oy,"cacheHintFallbackOf");function $l(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}n($l,"isValidCacheTtlMs");function Dl(e){return e==="public"||e==="private"}n(Dl,"isValidCacheScope");var A=(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})({}),se=class Ll extends Error{static{n(this,"ProtocolError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return ve(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 ve(this,t)}constructor(t,r,o){super(r),this.code=t,this.data=o,this.name="ProtocolError",Dt(this,new.target)}static fromError(t,r,o){if(t===A.UrlElicitationRequired&&o){let i=o;if(i.elicitations)return new Zo(i.elicitations,r)}if(t===A.UnsupportedProtocolVersion&&o){let i=o;if(Array.isArray(i.supported)&&typeof i.requested=="string")return new Bl({supported:i.supported,requested:i.requested},r)}if(t===A.InvalidParams||t===A.ResourceNotFound){let i=o;if(typeof i?.uri=="string"&&(t===A.ResourceNotFound||Object.keys(i).length===1))return new Hl(i.uri,r)}if(t===A.MissingRequiredClientCapability&&o){let i=o;if(i.requiredCapabilities!==null&&typeof i.requiredCapabilities=="object"&&!Array.isArray(i.requiredCapabilities))return new Fl({requiredCapabilities:i.requiredCapabilities},r)}return new Ll(t,r,o)}},Hl=class extends se{static{n(this,"ResourceNotFoundError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(A.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Zo=class extends se{static{n(this,"UrlElicitationRequiredError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(A.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Bl=class extends se{static{n(this,"UnsupportedProtocolVersionError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(A.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Fl=class extends se{static{n(this,"MissingRequiredClientCapabilityError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(A.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},iy=0,sy="private",ay=["tools/call","prompts/get","resources/read"];function cy(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||ay.includes(e))return t;throw new se(A.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}n(cy,"stampResultType");function dy(e,t){let r=oy(t);if(t.resultType!=="complete"||!ny(e))return r===void 0?t:hy(t);let o=t,i=$l(o.ttlMs)?o.ttlMs:py(r),s=Dl(o.cacheScope)?o.cacheScope:my(r),c={...o,ttlMs:i,cacheScope:s};return delete c[ds],c}n(dy,"fillCacheFields");function uy(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(uy,"isPlainObject$3");function ly(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[dr]:t}}:!uy(r)||r[dr]!==void 0?e:{...e,_meta:{...r,[dr]:t}}}n(ly,"stampServerInfoMeta");function py(e){return e!==void 0&&$l(e.ttlMs)?e.ttlMs:iy}n(py,"resolveTtlMs");function my(e){return e!==void 0&&Dl(e.cacheScope)?e.cacheScope:sy}n(my,"resolveCacheScope");function hy(e){let t={...e};return delete t[ds],t}n(hy,"stripCacheHintFallback");var fy=["elicitation/create","sampling/createMessage","roots/list"],Vo;function us(){if(Vo)return Vo;let e=pt();return Vo={request:{"elicitation/create":m({method:g("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":m({method:g("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":m({method:g("roots/list"),params:M({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Vo}n(us,"inputSchemaMaps");function gy(){us()}n(gy,"warmInputSchemaMaps2026");function Gl(e){return fy.includes(e)}n(Gl,"isInputRequestMethod2026");function Zi(e){return Gl(e)?us().request[e]:void 0}n(Zi,"getInputRequestSchema2026");function yy(e){return Gl(e)?us().response[e]:void 0}n(yy,"getInputResponseSchema2026");var ls={"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},Jl={"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 Vl(e){return Object.prototype.hasOwnProperty.call(ls,e)}n(Vl,"hasRequestMethod2026");function Kl(e){return Object.prototype.hasOwnProperty.call(Jl,e)}n(Kl,"hasNotificationMethod2026");function Sy(e){return Object.prototype.hasOwnProperty.call(ls,e)}n(Sy,"hasResultMethod2026");function _y(e){return Vl(e)?pt().dispatchRequestSchemas[e]:void 0}n(_y,"getRequestSchema2026");function wy(e){return Sy(e)?pt().dispatchResultSchemas[e]:void 0}n(wy,"getResultSchema2026");function Ry(e){return Kl(e)?pt().notificationSchemas2026[e]:void 0}n(Ry,"getNotificationSchema2026");var dT=Object.keys(ls),uT=Object.keys(Jl);function Bn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Bn,"isPlainObject$2");function Ln(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}n(Ln,"triState");var by={ok:!1,reason:"not-in-era"},vy=[cr,ur];function Cy(e,t){let r=t,o=!1,i=n(()=>(o||(r={...r},o=!0),r),"copy"),s=t.tools;e==="tools/list"&&Array.isArray(s)&&s.some(a=>Bn(a)&&"execution"in a)&&(i().tools=s.map(a=>{if(!Bn(a)||!("execution"in a))return a;let u={...a};return delete u.execution,u}));let c=t.capabilities;if(Bn(c)&&"tasks"in c){let a={...c};delete a.tasks,i().capabilities=a}return r}n(Cy,"enforceDeletedFields");var ps={era:"2026-07-28",hasRequestMethod:Vl,hasNotificationMethod:Kl,hasInputRequestMethod:n(e=>Zi(e)!==void 0,"hasInputRequestMethod"),validateRequest:n((e,t)=>Ln(_y(e),t),"validateRequest"),validateResult:n((e,t)=>Ln(wy(e),t),"validateResult"),validateNotification:n((e,t)=>Ln(Ry(e),t),"validateNotification"),validateInputRequest:n((e,t)=>Ln(Zi(e),t),"validateInputRequest"),validateInputResponse:n((e,t)=>Ln(yy(e),t),"validateInputResponse"),samplingResultVariant:n(()=>by,"samplingResultVariant"),outboundEnvelope(e){return{[cr]:e.protocolVersion,[Un]:e.clientInfo,[ur]:e.clientCapabilities,...e.logLevel!==void 0&&{[On]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of vy)o in e||t.push({key:o,problem:"missing"});let r=pt().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let o of r.error.issues){let i=o.path.map(String),s=i.length>0?i.join("."):"_meta";i.length===1&&t.some(c=>c.key===s&&c.problem==="missing")||t.push({key:s,problem:o.message})}return t},projectCallToolResult:n(e=>Ul(e),"projectCallToolResult"),inputRequestSchema:Zi,decodeResult(e,t){if(!Bn(t))return{kind:"invalid",error:new re(ie.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new re(ie.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 r!="string")return{kind:"invalid",error:new re(ie.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let c=t.inputRequests,a=Bn(c)?c:{},u=t.requestState;return Object.keys(a).length===0&&typeof u!="string"?{kind:"invalid",error:new re(ie.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:a,...typeof u=="string"&&{requestState:u}}}if(r!=="complete")return{kind:"invalid",error:new re(ie.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=Wl(),i=Object.hasOwn(o,e)?o[e]:void 0;if(i!==void 0){let c=i.safeParse(t);if(!c.success)return{kind:"invalid",error:new re(ie.InvalidResult,`Invalid result for ${e}: ${c.error}`,{method:e})}}let s={...t};return delete s.resultType,{kind:"complete",result:s}},encodeResult(e,t,r){return ly(dy(e,cy(e,Cy(e,t))),r)},encodeErrorCode:n(e=>e===-32002?-32602:e,"encodeErrorCode"),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=pt().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(r=>r.message).join("; ")}`}},Ko;function Wl(){if(Ko)return Ko;let e=pt();return Ko={"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},Ko}n(Wl,"getWireResultSchemas");function Iy(){Wl()}n(Iy,"warmWireResultSchemas2026");var ms="2026-07-28";function Gn(e){return e!==void 0&&xl(e)?ps:cs}n(Gn,"codecForVersion");function bl(e){return e.revision!==void 0?Gn(e.revision).era:e.era==="modern"?ps.era:cs.era}n(bl,"classifiedWireEra");function Yi(e){return Zl.some(t=>t.hasRequestMethod(e))}n(Yi,"isSpecRequestMethod");function Xi(e){return Zl.some(t=>t.hasNotificationMethod(e))}n(Xi,"isSpecNotificationMethod");var Zl=[cs,ps],Ty=gl({AnnotationsSchema:n(()=>Tc,"AnnotationsSchema"),AudioContentSchema:n(()=>id,"AudioContentSchema"),BaseMetadataSchema:n(()=>oc,"BaseMetadataSchema"),BaseRequestParamsSchema:n(()=>Fa,"BaseRequestParamsSchema"),BlobResourceContentsSchema:n(()=>Cc,"BlobResourceContentsSchema"),BooleanSchemaSchema:n(()=>Oi,"BooleanSchemaSchema"),CallToolRequestParamsSchema:n(()=>wd,"CallToolRequestParamsSchema"),CallToolRequestSchema:n(()=>Rd,"CallToolRequestSchema"),CallToolResultSchema:n(()=>Sd,"CallToolResultSchema"),CancelTaskRequestSchema:n(()=>hu,"CancelTaskRequestSchema"),CancelTaskResultSchema:n(()=>fu,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:n(()=>ec,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:n(()=>tc,"CancelledNotificationSchema"),ClientCapabilitiesSchema:n(()=>cc,"ClientCapabilitiesSchema"),ClientNotificationSchema:n(()=>yu,"ClientNotificationSchema"),ClientRequestSchema:n(()=>gu,"ClientRequestSchema"),ClientResultSchema:n(()=>Su,"ClientResultSchema"),ClientTasksCapabilitySchema:n(()=>sc,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:n(()=>_d,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:n(()=>Wd,"CompleteRequestParamsSchema"),CompleteRequestSchema:n(()=>Zd,"CompleteRequestSchema"),CompleteResultSchema:n(()=>Yd,"CompleteResultSchema"),ContentBlockSchema:n(()=>dd,"ContentBlockSchema"),CreateMessageRequestParamsSchema:n(()=>zd,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:n(()=>Md,"CreateMessageRequestSchema"),CreateMessageResultSchema:n(()=>Nd,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:n(()=>jd,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:n(()=>iu,"CreateTaskResultSchema"),CursorSchema:n(()=>Da,"CursorSchema"),DiscoverRequestSchema:n(()=>hc,"DiscoverRequestSchema"),DiscoverResultSchema:n(()=>xi,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:n(()=>xo,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:n(()=>Hd,"ElicitRequestParamsSchema"),ElicitRequestSchema:n(()=>Bd,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:n(()=>Uo,"ElicitRequestURLParamsSchema"),ElicitResultSchema:n(()=>Jd,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:n(()=>Fd,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:n(()=>Gd,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:n(()=>ad,"EmbeddedResourceSchema"),EmptyResultSchema:n(()=>Qa,"EmptyResultSchema"),EnumSchemaSchema:n(()=>Ld,"EnumSchemaSchema"),GetPromptRequestParamsSchema:n(()=>td,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:n(()=>rd,"GetPromptRequestSchema"),GetPromptResultSchema:n(()=>ld,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:n(()=>uu,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:n(()=>lu,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:n(()=>cu,"GetTaskRequestSchema"),GetTaskResultSchema:n(()=>du,"GetTaskResultSchema"),IconSchema:n(()=>rc,"IconSchema"),IconsSchema:n(()=>nc,"IconsSchema"),ImageContentSchema:n(()=>od,"ImageContentSchema"),ImplementationSchema:n(()=>ic,"ImplementationSchema"),InitializeRequestParamsSchema:n(()=>dc,"InitializeRequestParamsSchema"),InitializeRequestSchema:n(()=>uc,"InitializeRequestSchema"),InitializeResultSchema:n(()=>pc,"InitializeResultSchema"),InitializedNotificationSchema:n(()=>mc,"InitializedNotificationSchema"),JSONArraySchema:n(()=>ja,"JSONArraySchema"),JSONObjectSchema:n(()=>Na,"JSONObjectSchema"),JSONRPCErrorResponseSchema:n(()=>qn,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:n(()=>Ei,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:n(()=>Pi,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:n(()=>Nt,"JSONRPCRequestSchema"),JSONRPCResponseSchema:n(()=>Xa,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:n(()=>Ai,"JSONRPCResultResponseSchema"),JSONValueSchema:n(()=>Ma,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:n(()=>Mi,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:n(()=>Ui,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:n(()=>Qc,"ListPromptsRequestSchema"),ListPromptsResultSchema:n(()=>ed,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:n(()=>xc,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:n(()=>Uc,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:n(()=>Ac,"ListResourcesRequestSchema"),ListResourcesResultSchema:n(()=>Ec,"ListResourcesResultSchema"),ListRootsRequestSchema:n(()=>Qd,"ListRootsRequestSchema"),ListRootsResultSchema:n(()=>eu,"ListRootsResultSchema"),ListTasksRequestSchema:n(()=>pu,"ListTasksRequestSchema"),ListTasksResultSchema:n(()=>mu,"ListTasksResultSchema"),ListToolsRequestSchema:n(()=>gd,"ListToolsRequestSchema"),ListToolsResultSchema:n(()=>yd,"ListToolsResultSchema"),LoggingLevelSchema:n(()=>vd,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:n(()=>Td,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:n(()=>kd,"LoggingMessageNotificationSchema"),ModelHintSchema:n(()=>Pd,"ModelHintSchema"),ModelPreferencesSchema:n(()=>Ad,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:n(()=>Dd,"MultiSelectEnumSchemaSchema"),NotificationSchema:n(()=>Ka,"NotificationSchema"),NotificationsParamsSchema:n(()=>Va,"NotificationsParamsSchema"),NumberSchemaSchema:n(()=>Eo,"NumberSchemaSchema"),PaginatedRequestParamsSchema:n(()=>_c,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:n(()=>wc,"PaginatedRequestSchema"),PaginatedResultSchema:n(()=>Rc,"PaginatedResultSchema"),PingRequestSchema:n(()=>fc,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:n(()=>$i,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:n(()=>yc,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:n(()=>Sc,"ProgressNotificationSchema"),ProgressSchema:n(()=>gc,"ProgressSchema"),ProgressTokenSchema:n(()=>$a,"ProgressTokenSchema"),PromptArgumentSchema:n(()=>Yc,"PromptArgumentSchema"),PromptListChangedNotificationSchema:n(()=>pd,"PromptListChangedNotificationSchema"),PromptMessageSchema:n(()=>ud,"PromptMessageSchema"),PromptReferenceSchema:n(()=>Kd,"PromptReferenceSchema"),PromptSchema:n(()=>Xc,"PromptSchema"),ReadResourceRequestParamsSchema:n(()=>qc,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:n(()=>zc,"ReadResourceRequestSchema"),ReadResourceResultSchema:n(()=>Mc,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:n(()=>Ha,"RelatedTaskMetadataSchema"),RequestIdSchema:n(()=>Ya,"RequestIdSchema"),RequestMetaSchema:n(()=>Ba,"RequestMetaSchema"),RequestSchema:n(()=>Ja,"RequestSchema"),ResourceContentsSchema:n(()=>bc,"ResourceContentsSchema"),ResourceLinkSchema:n(()=>cd,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:n(()=>Nc,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:n(()=>Oc,"ResourceRequestParamsSchema"),ResourceSchema:n(()=>kc,"ResourceSchema"),ResourceTemplateReferenceSchema:n(()=>Vd,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:n(()=>Pc,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:n(()=>Wc,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:n(()=>Zc,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:n(()=>Wa,"ResultMetaObjectSchema"),ResultSchema:n(()=>Za,"ResultSchema"),RoleSchema:n(()=>Ic,"RoleSchema"),RootSchema:n(()=>Xd,"RootSchema"),RootsListChangedNotificationSchema:n(()=>tu,"RootsListChangedNotificationSchema"),SamplingContentSchema:n(()=>Ud,"SamplingContentSchema"),SamplingMessageContentBlockSchema:n(()=>Od,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:n(()=>qd,"SamplingMessageSchema"),ServerCapabilitiesSchema:n(()=>lc,"ServerCapabilitiesSchema"),ServerNotificationSchema:n(()=>wu,"ServerNotificationSchema"),ServerRequestSchema:n(()=>_u,"ServerRequestSchema"),ServerResultSchema:n(()=>Ru,"ServerResultSchema"),ServerTasksCapabilitySchema:n(()=>ac,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:n(()=>Cd,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:n(()=>Id,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:n(()=>$d,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:n(()=>Ao,"StringSchemaSchema"),SubscribeRequestParamsSchema:n(()=>jc,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:n(()=>$c,"SubscribeRequestSchema"),SubscriptionFilterSchema:n(()=>Hc,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:n(()=>Gc,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:n(()=>Jc,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:n(()=>Bc,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:n(()=>Fc,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:n(()=>Vc,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:n(()=>Kc,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:n(()=>Ga,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:n(()=>ru,"TaskCreationParamsSchema"),TaskMetadataSchema:n(()=>La,"TaskMetadataSchema"),TaskSchema:n(()=>ou,"TaskSchema"),TaskStatusNotificationParamsSchema:n(()=>su,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:n(()=>au,"TaskStatusNotificationSchema"),TaskStatusSchema:n(()=>nu,"TaskStatusSchema"),TextContentSchema:n(()=>nd,"TextContentSchema"),TextResourceContentsSchema:n(()=>vc,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:n(()=>ji,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:n(()=>zi,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:n(()=>md,"ToolAnnotationsSchema"),ToolChoiceSchema:n(()=>Ed,"ToolChoiceSchema"),ToolExecutionSchema:n(()=>hd,"ToolExecutionSchema"),ToolListChangedNotificationSchema:n(()=>bd,"ToolListChangedNotificationSchema"),ToolResultContentSchema:n(()=>xd,"ToolResultContentSchema"),ToolSchema:n(()=>fd,"ToolSchema"),ToolUseContentSchema:n(()=>sd,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:n(()=>Dc,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:n(()=>Lc,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:n(()=>Ni,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:n(()=>qi,"UntitledSingleSelectEnumSchemaSchema")});var Yl=n(e=>Nt.safeParse(e).success,"isJSONRPCRequest"),Xl=n(e=>Pi.safeParse(e).success,"isJSONRPCNotification"),ns=n(e=>Ai.safeParse(e).success,"isJSONRPCResultResponse"),Ql=n(e=>qn.safeParse(e).success,"isJSONRPCErrorResponse");var Fn=-32020,lT=[{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:[A.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:[Fn,A.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:[A.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:[A.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:[A.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:[Fn],conformance:["http-header-validation"],rationale:"SEP-2243 standard `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 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. 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:[A.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:[Fn],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."}],pT={[A.ParseError]:400,[A.InvalidRequest]:400,[A.MethodNotFound]:404,[A.UnsupportedProtocolVersion]:400,[A.MissingRequiredClientCapability]:400,[Fn]:400};function hs(e,t){return Oa(e,t)}n(hs,"parseSchema");function Hn(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}n(Hn,"shapeKeys");function os(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}n(os,"isStandardSchema");var vl=!1,is="draft-2020-12";function ky(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:is});else if(r.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().");vl||(vl=!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.")),o=Ci(e,{target:is,io:t})}else throw new Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return o.type!==void 0?o:ep(o)?{type:"object",...o}:o;if(o.type!==void 0&&o.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(o.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...o}}n(ky,"standardSchemaToJsonSchema");function ep(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every(o=>o!==null&&typeof o=="object"&&(o.type==="object"||ep(o)))}return!1}n(ep,"isProvablyObjectShapedRoot");function Py(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}n(Py,"formatIssue");async function Qi(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(o=>Py(o)).join(", ")}:{success:!0,data:r.value}}n(Qi,"validateStandardSchema");function Ay(e){let t=Ci(e,{target:is,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}n(Ay,"zodEmittedPattern");var Ey=/\\\.\\d\{(\d+)\}/;function xy(e){let t=Ey.exec(e),r=[void 0,-1,0];return t&&r.push(Number(t[1])),[!1,!0].flatMap(o=>[!1,!0].flatMap(i=>r.map(s=>En.datetime({local:o,offset:i,precision:s}))))}n(xy,"datetimeReferenceSchemas");function Uy(e,t){let r;switch(e){case"email":r=[qa()];break;case"uri":r=[za()];break;case"date":r=[En.date()];break;case"date-time":r=xy(t);break}return new Set(r.map(o=>Ay(o)).filter(o=>o!==void 0))}n(Uy,"referencePatternsForFormat");function Oy(e,t,r){return r!=="zod"?!0:Uy(e,t).has(t)}n(Oy,"isLibraryFormatPattern");function Jn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(Jn,"isJsonObject");function qy(e){try{return ky(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new se(A.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}n(qy,"convertStandardElicitationSchema");var zy=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function fs(e){return zy.has(e)||e.startsWith("x-")}n(fs,"isAnnotationOnlyJsonSchemaKeyword");var My=new Set(["$schema",...Object.keys(xo.shape.requestedSchema.shape)]),Cl={string:Hn([Ao,qi,zi,Mi]),number:Hn([Eo]),integer:Hn([Eo]),boolean:Hn([Oi]),array:Hn([Ni,ji])},Ny=new Set(Ao.shape.format.unwrap().options);function jy(e,t,r,o){if(!Jn(e))return e;let i=typeof e.type=="string"&&Object.hasOwn(Cl,e.type)?Cl[e.type]:void 0;if(i===void 0)return e;let s={};for(let[c,a]of Object.entries(e))i.has(c)||fs(c)?s[c]=a:c==="pattern"&&e.type==="string"&&typeof e.format=="string"?Ny.has(e.format)?(typeof a!="string"||!Oy(e.format,a,r))&&o.push(`${t}.${c}`):s[c]=a:o.push(`${t}.${c}`);return s}n(jy,"walkProperty");function $y(e,t){let r={},o=[];for(let[i,s]of Object.entries(e))i==="properties"&&Jn(s)?r[i]=Object.fromEntries(Object.entries(s).map(([c,a])=>[c,jy(a,`properties.${c}`,t,o)])):My.has(i)?r[i]=s:fs(i)||o.push(i);if(o.length>0)throw new se(A.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}n($y,"walkRequestedSchema");function Dy(e,t){if(!Jn(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!hs($i,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}n(Dy,"describeUnsupportedProperties");function ss(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,i)=>ss(o,t[i],`${r}[${i}]`)):!Jn(e)||!Jn(t)?[]:Object.entries(e).flatMap(([o,i])=>{let s=r?`${r}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?ss(i,t[o],s):fs(o)?[]:[s]})}n(ss,"findDroppedConstraintPaths");function Ly(e){if(!os(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=$y(qy(e.requestedSchema),t),o=hs(xo.shape.requestedSchema,r);if(!o.success)throw new se(A.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${Dy(r,o.error.message)}`);let i=ss(r,o.data);if(i.length>0)throw new se(A.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${i.join(", ")}`);let s=(o.data.required??[]).filter(c=>!Object.prototype.hasOwnProperty.call(o.data.properties,c));if(s.length>0)throw new se(A.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${s.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}n(Ly,"normalizeElicitInputParams");function Hy(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState=="string";if(!t&&!r)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}}}n(Hy,"buildInputRequired");var mT=Object.assign(Hy,{elicit(e){try{return{method:"elicitation/create",params:Ly(e)}}catch(t){throw t instanceof se?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 By=["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"],Fy={IdJagTokenExchangeResponseSchema:Di,OAuthClientInformationFullSchema:jt,OAuthClientInformationSchema:zn,OAuthClientMetadataSchema:vu,OAuthClientRegistrationErrorSchema:Cu,OAuthErrorResponseSchema:Oo,OAuthMetadataSchema:mr,OAuthProtectedResourceMetadataSchema:pr,OAuthTokenRevocationRequestSchema:Iu,OAuthTokensSchema:at,OpenIdProviderDiscoveryMetadataSchema:hr,OpenIdProviderMetadataSchema:bu},tp={},rp={};function np(e,t){let r=e.slice(0,-6);tp[r]=t,rp[r]=o=>t.safeParse(o).success}n(np,"register");for(let e of By)np(e,Ty[e]);for(let[e,t]of Object.entries(Fy))np(e,t);var Gy=Object.freeze(tp),Jy=Object.freeze(rp);function Vy(e){switch(e){case"initialize":case"notifications/initialized":return Gn(void 0);case"server/discover":return Gn(ms);default:return}}n(Vy,"bootstrapOutboundCodec");var op=6e4,Ky=[cr,Un,ur,On],Wy=["inputResponses","requestState"];function Il(e,t){let r=e.params;if(!es(r))return{message:e,lifted:{}};let o=r._meta,i=es(o)?Ky.filter(u=>u in o):[],s=t==="request"?Wy.filter(u=>u in r):[];if(i.length===0&&s.length===0)return{message:e,lifted:{}};let c={},a={...r};if(i.length>0&&es(o)){let u={},p={...o};for(let h of i)u[h]=o[h],delete p[h];c.envelope=u,Object.keys(p).length>0?a._meta=p:delete a._meta}for(let u of s)u==="inputResponses"&&(c.inputResponses=a[u]),u==="requestState"&&(c.requestState=a[u]),delete a[u];return{message:{...e,params:a},lifted:c}}n(Il,"liftWireOnlyMaterial");function Tl(e,t){let r=e.validateResult(t,void 0);if(!(!r.ok&&r.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(o){let i=e.validateResult(t,o);return i.ok?{value:i.value}:{issues:[{message:i.reason==="invalid"?i.message:`not-in-era: ${t}`}]}}}}}n(Tl,"codecResultValidator");function ip(e){return()=>e}n(ip,"requestStateAccessor");var Zy=ip(void 0),Yy,Xy=class{static{n(this,"Protocol")}_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{Yy=n((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??ki,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 r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new re(ie.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&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,o,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new re(ie.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});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 r=this.transport?.onerror;this._transport.onerror=i=>{r?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),ns(i)||Ql(i)?this._onresponse(i):Yl(i)?this._onrequest(i,s):Xl(i)?this._onnotification(i,s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},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 o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new re(ie.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let o of e.values())o(r);for(let o of t.values())o.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=Il(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let c=bl(t.classification);if(c!==o.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${c} but this instance serves ${o.era}`));return}}if(Xi(r.method)&&!o.hasNotificationMethod(r.method))return;let i=this._notificationHandlers.get(r.method),s=this.fallbackNotificationHandler;i===void 0&&s===void 0||Promise.resolve().then(()=>i===void 0?s(r):i(r,o)).catch(c=>this._onerror(new Error(`Uncaught error in notification handler: ${c}`)))}_onrequest(e,t){let{message:r,lifted:o}=Il(e,"request"),i=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 s=this._transport,c=n((w,C,U)=>{let O={jsonrpc:"2.0",id:r.id,error:{code:w,message:C,...U!==void 0&&{data:U}}};s?.send(O).catch(L=>this._onerror(new Error(`Failed to send an error response: ${L}`)))},"sendErrorResponse");if(t?.classification!==void 0){let w=bl(t.classification);if(w!==i.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${w} but this instance serves ${i.era}`));let C=t.classification.revision??w;c(A.UnsupportedProtocolVersion,`Unsupported protocol version: ${C}`,{supported:this._supportedProtocolVersions,requested:C});return}}if(Yi(r.method)&&!i.hasRequestMethod(r.method)){c(A.MethodNotFound,"Method not found");return}let a=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(a===void 0){c(A.MethodNotFound,"Method not found");return}let u=i.checkInboundEnvelope(o);if(u!==void 0){c(A.InvalidParams,u);return}let p=n((w,C)=>this._notificationViaCodec(this._resolveOutboundCodec(w.method),w,{...C,relatedRequestId:r.id}),"sendNotification"),h=n((w,C,U)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(w.method),w,C,{...U,relatedRequestId:r.id}),"sendRequest"),f=new AbortController;this._requestHandlerAbortControllers.set(r.id,f);let y=o.inputResponses===void 0?void 0:Qy(o.inputResponses),S={sessionId:s?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...y!==void 0&&{inputResponses:y.accepted},...y!==void 0&&y.droppedKeys.length>0&&{droppedInputResponseKeys:y.droppedKeys},requestState:o.requestState===void 0?Zy:ip(o.requestState),signal:f.signal,send:n(((w,C,U)=>{let O=this._resolveOutboundCodec(w.method);if(this._assertOutboundRequestInEra(O,w.method),os(C))return h(w,C,U);let L=Tl(O,w.method);if(L===void 0)throw new TypeError(`'${w.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return h(w,L,C)}),"send"),notify:p},http:t?.authInfo?{authInfo:t.authInfo}:void 0},k=this.buildContext(S,t);Promise.resolve().then(()=>a(r,k)).then(async w=>{if(f.signal.aborted)return;let C;try{C=i.encodeResult(r.method,w,this._outboundServerInfo())}catch(O){this._onerror(new Error(`Failed to encode result for ${r.method}: ${O}`)),c(A.InternalError,"Internal error");return}let U={result:C,jsonrpc:"2.0",id:r.id};await s?.send(U)},async w=>{if(f.signal.aborted)return;let C=Number.isSafeInteger(w.code)?w.code:A.InternalError,U={jsonrpc:"2.0",id:r.id,error:{code:i.encodeErrorCode(C),message:w.message??"Internal error",...w.data!==void 0&&{data:w.data}}};await s?.send(U)}).catch(w=>this._onerror(new Error(`Failed to send response: ${w}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===f&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,o=Number(t),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),c=this._timeoutInfo.get(o);if(c&&s&&c.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(a);return}i(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===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),ns(e)?r(e):r(se.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let o=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(o,e.method),os(t))return this._requestWithSchemaViaCodec(o,e,t,r);let i=Tl(o,e.method);if(i===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(o,e,i,t)}_negotiatedWireCodec(){return Gn(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Vy(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Yi(t)&&!e.hasRequestMethod(t))throw new re(ie.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let o=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r)}_requestWithSchemaViaCodec(e,t,r,o){let{relatedRequestId:i,resumptionToken:s,onresumptiontoken:c,headers:a}=o??{},u=Date.now(),p,h;return new Promise((f,y)=>{let S=n(G=>{y(G)},"earlyReject");if(!this._transport){S(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(G){S(G);return}if(o?.signal?.aborted){let G=o.signal.reason;throw G instanceof re?G:new re(ie.RequestTimeout,String(G))}let k=e.era===ms&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,w=this._requestMessageId++;h=w;let C={...t,jsonrpc:"2.0",id:w};o?.onprogress&&(this._progressHandlers.set(w,o.onprogress),C.params={...t.params,_meta:{...t.params?._meta,progressToken:w}});let U=this._envelopeOutbound(C),O=!1,L=n(G=>{O||(this._progressHandlers.delete(w),k===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(G)}}),{relatedRequestId:i,resumptionToken:s,onresumptiontoken:c}).catch(V=>this._onerror(new Error(`Failed to send cancellation: ${V}`))):k.abort(),y(G instanceof re?G:new re(ie.RequestTimeout,String(G))))},"cancel");this._responseHandlers.set(w,G=>{if(o?.signal?.aborted)return;if(O=!0,G instanceof Error)return y(G);let V;try{V=e.decodeResult(t.method,G.result)}catch(oe){return y(oe instanceof Error?oe:new Error(String(oe)))}if(V.kind==="invalid")return y(V.error);if(V.kind==="input_required"){if(o?.allowInputRequired===!0)return f(eS(V));let oe={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:u,retry:n((Me,D)=>this._requestWithSchemaViaCodec(e,Me===void 0?{method:t.method}:{method:t.method,params:Me},r,D),"retry")};return f(this._resolveNonCompleteResult(V,oe))}let Be=V.result;Qi(r,Be).then(oe=>{oe.success?f(oe.data):y(new re(ie.InvalidResult,`Invalid result for ${t.method}: ${oe.error}`))},y)}),p=n(()=>L(o?.signal?.reason),"onAbort"),o?.signal?.addEventListener("abort",p,{once:!0});let F=o?.timeout??op,ee=n(()=>L(new re(ie.RequestTimeout,"Request timed out",{timeout:F})),"timeoutHandler");this._setupTimeout(w,F,o?.maxTotalTimeout,ee,o?.resetTimeoutOnProgress??!1),this._transport.send(U,{relatedRequestId:i,resumptionToken:s,onresumptiontoken:c,headers:a,requestSignal:k?.signal}).catch(G=>{this._progressHandlers.delete(w),y(G)})}).finally(()=>{p&&o?.signal?.removeEventListener("abort",p),h!==void 0&&(this._responseHandlers.delete(h),this._cleanupTimeout(h))})}async notification(e,t){return this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new re(ie.NotConnected,"Not connected");if(Xi(t.method)&&!e.hasNotificationMethod(t.method))throw new re(ie.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 o=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId){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(o,r).catch(i=>this._onerror(i))});return}await this._transport.send(o,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let o;if(typeof t=="function"){if(!Yi(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=n((i,s)=>{let c=this._negotiatedWireCodec(),a=c.validateRequest(e,i);if(!a.ok&&a.reason==="not-in-era"&&(a=c.validateInputRequest(e,i)),!a.ok)throw a.reason==="not-in-era"?new se(A.InternalError,`No wire schema for ${e} in the resolved era`):new Error(a.message);return Promise.resolve(t(a.value,s))},"stored")}else if(r)o=n(async(i,s)=>{let c=await Qi(t.params,{...i.params});if(!c.success)throw new se(A.InvalidParams,`Invalid params for ${e}: ${c.error}`);return r(c.data,s)},"stored");else throw new TypeError("setRequestHandler: handler is required");this._requestHandlers.set(e,this._wrapHandler(e,o))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.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,r){if(typeof t=="function"){if(!Xi(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,i)=>{let s=i.validateNotification(e,o);if(!s.ok)throw s.reason==="not-in-era"?new se(A.InternalError,`No wire schema for ${e} in the resolved era`):new Error(s.message);return Promise.resolve(t(s.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async o=>{let i=await Qi(t.params,{...o.params});if(!i.success)throw new se(A.InvalidParams,`Invalid params for notification ${e}: ${i.error}`);await r(i.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function es(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(es,"isPlainObject$1");function kl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}n(kl,"isPlainObject");function Qy(e){let t={},r=[];if(!kl(e))return{accepted:t,droppedKeys:r};for(let[o,i]of Object.entries(e)){if(!kl(i)||"method"in i||"result"in i){r.push(o);continue}t[o]=i}return{accepted:t,droppedKeys:r}}n(Qy,"partitionInputResponses");function eS(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}n(eS,"manualInputRequiredValue");var tS=fl((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=i;function i(a){if(!a)throw new TypeError("argument string is required");var u=typeof a=="object"?s(a):a;if(typeof u!="string")throw new TypeError("argument string is required to be a string");var p=u.indexOf(";"),h=p!==-1?u.slice(0,p).trim():u.trim();if(!o.test(h))throw new TypeError("invalid media type");var f=new c(h.toLowerCase());if(p!==-1){var y,S,k;for(t.lastIndex=p;S=t.exec(u);){if(S.index!==p)throw new TypeError("invalid parameter format");p+=S[0].length,y=S[1].toLowerCase(),k=S[2],k.charCodeAt(0)===34&&(k=k.slice(1,-1),k.indexOf("\\")!==-1&&(k=k.replace(r,"$1"))),f.parameters[y]=k}if(p!==u.length)throw new TypeError("invalid parameter format")}return f}n(i,"parse");function s(a){var u;if(typeof a.getHeader=="function"?u=a.getHeader("content-type"):typeof a.headers=="object"&&(u=a.headers&&a.headers["content-type"]),typeof u!="string")throw new TypeError("content-type header is missing from object");return u}n(s,"getcontenttype");function c(a){this.parameters=Object.create(null),this.type=a}n(c,"ContentType")})),hT=yl(tS(),1);var rS=10*1024*1024;function gs(){as(),pt(),Wg(),gy(),Iy()}n(gs,"preloadSchemas");var TT=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");var nS=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,oS=[0,31,28,31,30,31,30,31,31,30,31,30,31],iS=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,sS=/^(?=.{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,aS=/^(?:[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,cS=/^(?:(?:[^\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,dS=/^(?:(?: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,uS=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,lS=/^(?:\/(?:[^~/]|~0|~1)*)*$/,pS=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,mS=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,hS=n(e=>{if(e[0]==='"')return!1;let[t,r,...o]=e.split("@");return!t||!r||o.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},"EMAIL"),fS=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,gS=/^((([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,yS=n(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)),"DURATION");function De(e){return e.test.bind(e)}n(De,"bind");var kT={date:sp,time:ap.bind(void 0,!1),"date-time":wS,duration:yS,uri:vS,"uri-reference":De(aS),"uri-template":De(cS),url:De(dS),email:hS,hostname:De(sS),ipv4:De(fS),ipv6:De(gS),regex:IS,uuid:De(uS),"json-pointer":De(lS),"json-pointer-uri-fragment":De(pS),"relative-json-pointer":De(mS)};function SS(e){return e%4===0&&(e%100!==0||e%400===0)}n(SS,"isLeapYear");function sp(e){let t=e.match(nS);if(!t)return!1;let r=+t[1],o=+t[2],i=+t[3];return o>=1&&o<=12&&i>=1&&i<=(o==2&&SS(r)?29:oS[o])}n(sp,"date");function ap(e,t){let r=t.match(iS);if(!r)return!1;let o=+r[1],i=+r[2],s=+r[3],c=!!r[5];return(o<=23&&i<=59&&s<=59||o==23&&i==59&&s==60)&&(!e||c)}n(ap,"time");var _S=/t|\s/i;function wS(e){let t=e.split(_S);return t.length==2&&sp(t[0])&&ap(!0,t[1])}n(wS,"date_time");var RS=/\/|:/,bS=/^(?:[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 vS(e){return RS.test(e)&&bS.test(e)}n(vS,"uri");var CS=/[^\\]\\Z/;function IS(e){if(CS.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}n(IS,"regex");gs();var cp=!1;var ys;ys=globalThis.crypto;async function kS(e){return(await ys).getRandomValues(new Uint8Array(e))}n(kS,"getRandomValues");async function PS(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await kS(e-o.length);for(let s of i)s<r&&(o+=t[s%t.length])}return o}n(PS,"random");async function AS(e){return await PS(e)}n(AS,"generateVerifier");async function ES(e){let t=await(await ys).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(ES,"generateChallenge");async function Ss(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await AS(e),r=await ES(t);return{code_verifier:t,code_challenge:r}}n(Ss,"pkceChallenge");var Vn=class extends Error{static{n(this,"OAuthClientFlowError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return ve(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 ve(this,e)}constructor(e){super(e),this.name=new.target.name,Dt(this,new.target)}},vs=class extends Vn{static{n(this,"IssuerMismatchError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 \xA73.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`),this.kind=e,this.expected=t,this.received=r}},xS=class extends Vn{static{n(this,"RegistrationRejectedError")}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}},pp=class extends Vn{static{n(this,"InsecureTokenEndpointError")}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 / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},_s=class extends Vn{static{n(this,"AuthorizationServerMismatchError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server changed between redirect and callback (redirected to ${JSON.stringify(e)}, callback resolved ${JSON.stringify(t)}); refusing to send authorization_code/code_verifier to a different token endpoint`),this.recordedIssuer=e,this.currentIssuer=t}},hk=class extends Vn{static{n(this,"InsufficientScopeError")}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 dp(e,t,r){if(e!==void 0)return e.issuer===void 0?(r?.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):mp(e.issuer,t)?e:void 0}n(dp,"discardIfIssuerMismatch");function mp(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}n(mp,"issuersMatch");var fk=class extends Error{static{n(this,"UnauthorizedError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return ve(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 ve(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",Dt(this,new.target)}};function hp(e){return e?.authorization_response_iss_parameter_supported===!0}n(hp,"isIssParameterSupported");function fp({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new vs("authorization_response",t,void 0);return}if(e!==t)throw new vs("authorization_response",t,e)}}n(fp,"validateAuthorizationResponseIssuer");function US(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(US,"isClientAuthMethod");var ws="code",Rs="S256";function OS(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&US(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}n(OS,"selectClientAuthMethod");function qS(e,t,r,o){let{client_id:i,client_secret:s}=t;switch(e){case"client_secret_basic":zS(i,s,r);return;case"client_secret_post":MS(i,s,o);return;case"none":NS(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(qS,"applyClientAuthentication");function zS(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}n(zS,"applyBasicAuth");function MS(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(MS,"applyPostAuth");function NS(e,t){t.set("client_id",e)}n(NS,"applyPublicAuth");function gp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}n(gp,"isLoopbackHost");function jS(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!gp(t.hostname))throw new pp(t.href);return t}n(jS,"assertSecureTokenEndpoint");function $S(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||gp(r.hostname))return"native"}return"web"}n($S,"deriveApplicationType");function DS(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??$S(t.redirect_uris)}}n(DS,"resolveClientMetadata");async function up(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Oo.parse(JSON.parse(r));return mt.fromResponse(o)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new mt(ue.ServerError,i)}}n(up,"parseErrorResponse");async function Cs(e,t){try{return await bs(e,t)}catch(r){if(r instanceof mt){if(r.code===ue.InvalidClient||r.code===ue.UnauthorizedClient)return await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await bs(e,t);if(r.code===ue.InvalidGrant)return await e.invalidateCredentials?.("tokens"),await bs(e,t)}throw r}}n(Cs,"auth");function LS(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:o,clientMetadata:i}=e,s=t||r?.scopes_supported?.join(" ")||i.scope;return s&&o?.scopes_supported?.includes("offline_access")&&!s.split(" ").includes("offline_access")&&i.grant_types?.includes("refresh_token")&&(s=`${s} offline_access`),s}n(LS,"determineScope");async function bs(e,{serverUrl:t,authorizationCode:r,iss:o,scope:i,resourceMetadataUrl:s,fetchFn:c,skipIssuerMetadataValidation:a,forceReauthorization:u}){let p=DS(e),h=await e.discoveryState?.(),f,y,S,k,w=s;if(!w&&h?.resourceMetadataUrl&&(w=new URL(h.resourceMetadataUrl)),h?.authorizationServerUrl){if(y=h.authorizationServerUrl,f=h.resourceMetadata,S=h.authorizationServerMetadata??await wp(y,{fetchFn:c,skipIssuerValidation:a}),!f)try{f=await Sp(t,{resourceMetadataUrl:w},c)}catch(D){if(D instanceof TypeError)throw D}(S!==h.authorizationServerMetadata||f!==h.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(y),resourceMetadataUrl:w?.toString(),resourceMetadata:f,authorizationServerMetadata:S})}else{let D=await VS(t,{resourceMetadataUrl:w,fetchFn:c,skipIssuerMetadataValidation:a});y=D.authorizationServerUrl,S=D.authorizationServerMetadata,f=D.resourceMetadata,k={authorizationServerUrl:String(y),resourceMetadataUrl:w?.toString(),resourceMetadata:f,authorizationServerMetadata:S}}let C=S?.issuer??String(y),U={issuer:C};if(await e.saveAuthorizationServerUrl?.(C),r!==void 0){let D=h?.authorizationServerMetadata?.issuer??h?.authorizationServerUrl;if(D===void 0){if(e.saveDiscoveryState!==void 0)throw new _s("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",C);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(!mp(D,C))throw new _s(D,C)}k&&await e.saveDiscoveryState?.(k);let O=await HS(t,e,f);O&&await e.saveResourceUrl?.(String(O));let L=LS({requestedScope:i,resourceMetadata:f,authServerMetadata:S,clientMetadata:e.clientMetadata}),F=await Promise.resolve(e.clientInformation(U)),ee=dp(F,C,{canPersistStamp:e.saveClientInformation!==void 0});if(ee===void 0&&F?.issuer&&e.saveClientInformation===void 0)throw new _s(F.issuer,C);if(ee&&ee.issuer===void 0&&(ee={...ee,issuer:C},await e.saveClientInformation?.(ee,U)),!ee){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let D=S?.client_id_metadata_document_supported===!0,Ee=e.clientMetadataUrl;if(Ee&&!Is(Ee))throw new mt(ue.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${Ee}`);if(D&&Ee)ee={client_id:Ee,issuer:C},await e.saveClientInformation?.(ee,U);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");ee={...await XS(y,{metadata:S,clientMetadata:p,scope:L,fetchFn:c}),issuer:C},await e.saveClientInformation(ee,U)}}let G=!e.redirectUrl;if(r!==void 0||G){r!==void 0&&fp({iss:o,expectedIssuer:S?.issuer,issParameterSupported:hp(S)});let D=await YS(e,y,{metadata:S,resource:O,authorizationCode:r,iss:o,scope:L,fetchFn:c});return await e.saveTokens({...D,issuer:C},U),"AUTHORIZED"}let V=dp(await e.tokens(U),C);if(V&&V.issuer===void 0&&(V={...V,issuer:C},await e.saveTokens(V,U)),V?.refresh_token&&!u)try{let D=await ZS(y,{metadata:S,clientInformation:ee,refreshToken:V.refresh_token,resource:O,addClientAuthentication:e.addClientAuthentication,fetchFn:c});return await e.saveTokens({...D,issuer:C},U),"AUTHORIZED"}catch(D){if(D instanceof pp||!(!(D instanceof mt)||D.code===ue.ServerError))throw D}let Be=e.state?await e.state():void 0,{authorizationUrl:oe,codeVerifier:Me}=await KS(y,{metadata:S,clientInformation:ee,state:Be,redirectUrl:e.redirectUrl,scope:L,resource:O});return await e.saveCodeVerifier(Me),await e.redirectToAuthorization(oe),"REDIRECT"}n(bs,"authInternal");function Is(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(Is,"isHttpsUrl");async function HS(e,t,r){let o=Al(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!El({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}n(HS,"selectResourceURL");function yp(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r?.toLowerCase()!=="bearer"||!o)return{};let i=Yo(e,"resource_metadata")||void 0,s;if(i)try{s=new URL(i)}catch{}let c=Yo(e,"scope")||void 0,a=Yo(e,"error")||void 0,u=Yo(e,"error_description")||void 0;return{resourceMetadataUrl:s,scope:c,error:a,errorDescription:u}}n(yp,"extractWWWAuthenticateParams");function Yo(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),i=r.match(o);if(i){let s=i[1]||i[2];if(s)return s}return null}n(Yo,"extractFieldFromWwwAuth");async function Sp(e,t,r=fetch){let o=await GS(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.text?.().catch(()=>{}),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.text?.().catch(()=>{}),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return pr.parse(await o.json())}n(Sp,"discoverOAuthProtectedResourceMetadata");async function _p(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(!(o instanceof TypeError)||!cp)throw o;if(t)try{return await r(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}n(_p,"fetchWithCorsRetry");function BS(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(BS,"buildWellKnownPath");async function lp(e,t,r=fetch){return await _p(e,{"MCP-Protocol-Version":t},r)}n(lp,"tryMetadataDiscovery");function FS(e,t){return e?t==="/"?!1:e.status>=400&&e.status<500||e.status===502:!0}n(FS,"shouldAttemptFallback");async function GS(e,t,r,o){let i=new URL(e),s=o?.protocolVersion??Po,c;if(o?.metadataUrl)c=new URL(o.metadataUrl);else{let u=BS(t,i.pathname);c=new URL(u,o?.metadataServerUrl??i),c.search=i.search}let a=await lp(c,s,r);return!o?.metadataUrl&&FS(a,i.pathname)&&(a=await lp(new URL(`/.well-known/${t}`,i),s,r)),a}n(GS,"discoverMetadataWithFallback");function JS(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let i=t.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:"oidc"},{url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}n(JS,"buildDiscoveryUrls");async function wp(e,{fetchFn:t=fetch,protocolVersion:r=Po,skipIssuerValidation:o=!1}={}){let i={"MCP-Protocol-Version":r,Accept:"application/json"},s=JS(e);for(let{url:c,type:a}of s){let u=await _p(c,i,t);if(!u)continue;if(!u.ok){if(await u.text?.().catch(()=>{}),u.status>=400&&u.status<500||u.status===502)continue;throw new Error(`HTTP ${u.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${c}`)}let p=a==="oauth"?mr.parse(await u.json()):hr.parse(await u.json());if(!o){let h=typeof e=="string"?e:e.href;if(!(p.issuer===h||h.endsWith("/")&&p.issuer===h.slice(0,-1)))throw new vs("metadata",h,p.issuer)}return p}}n(wp,"discoverAuthorizationServerMetadata");async function VS(e,t){let r,o;try{r=await Sp(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch(s){if(s instanceof TypeError)throw s}o||(o=String(new URL("/",e)));let i=await wp(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(VS,"discoverOAuthServerInfo");async function KS(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:i,state:s,resource:c}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(ws))throw new Error(`Incompatible auth server: does not support response type ${ws}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Rs))throw new Error(`Incompatible auth server: does not support code challenge method ${Rs}`)}else a=new URL("/authorize",e);let u=await Ss(),p=u.code_verifier,h=u.code_challenge;return a.searchParams.set("response_type",ws),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",h),a.searchParams.set("code_challenge_method",Rs),a.searchParams.set("redirect_uri",String(o)),s&&a.searchParams.set("state",s),i&&a.searchParams.set("scope",i),i?.split(" ").includes("offline_access")&&a.searchParams.append("prompt","consent"),c&&a.searchParams.set("resource",c.href),{authorizationUrl:a,codeVerifier:p}}n(KS,"startAuthorization");function WS(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(WS,"prepareAuthorizationCodeRequest");async function Rp(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:i,resource:s,fetchFn:c}){let a=jS(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});s&&r.set("resource",s.href),i?await i(u,r,a,t):o&&qS(OS(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let p=await(c??fetch)(a,{method:"POST",headers:u,body:r});if(!p.ok)throw await up(p);let h=await p.json();try{return at.parse(h)}catch(f){throw typeof h=="object"&&h!==null&&"error"in h?await up(JSON.stringify(h)):f}}n(Rp,"executeTokenRequest");async function ZS(e,{metadata:t,clientInformation:r,refreshToken:o,resource:i,addClientAuthentication:s,fetchFn:c}){return{refresh_token:o,...await Rp(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:s,resource:i,fetchFn:c})}}n(ZS,"refreshAuthorization");async function YS(e,t,{metadata:r,resource:o,authorizationCode:i,iss:s,scope:c,fetchFn:a}={}){i!==void 0&&fp({iss:s,expectedIssuer:r?.issuer,issParameterSupported:hp(r)});let u=c??e.clientMetadata.scope,p;if(e.prepareTokenRequest&&(p=await e.prepareTokenRequest(u)),!p){if(!i)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");p=WS(i,await e.codeVerifier(),e.redirectUrl)}let h=await e.clientInformation({issuer:r?.issuer??String(t)});return Rp(t,{metadata:r,tokenRequestParams:p,clientInformation:h??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:a})}n(YS,"fetchToken");async function XS(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:i}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);let c={...r,...o===void 0?{}:{scope:o}},a=await(i??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!a.ok)throw new xS({status:a.status,body:await a.text(),submittedMetadata:c});return jt.parse(await a.json())}n(XS,"registerClient");var gk=class extends Error{static{n(this,"SseError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return ve(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 ve(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,Dt(this,new.target)}};function QS(e){let t=Nt.safeParse(e);return t.success?t.data.id:void 0}n(QS,"parseJsonRpcRequestId");function bp(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return QS(t)}catch{return}}n(bp,"readJsonRpcRequestIdFromBody");function Xo(e){return qn.parse({jsonrpc:lr,...e.id===void 0?{}:{id:e.id},error:{code:e.error.code,message:e.error.message,...e.error.data===void 0?{}:{data:e.error.data}}})}n(Xo,"jsonRpcErrorResponse");function vp(e){return new Zo([Uo.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(vp,"urlElicitationRequiredError");var ei=l.record(l.string(),l.unknown()),e_=l.record(l.string(),l.unknown()),ft=l.array(l.string().min(1)).min(1).optional(),t_=l.object({name:l.string().min(1),description:l.string().min(1).optional(),annotations:e_.optional(),_meta:ei.optional(),roles:ft,groups:ft,public:l.boolean().optional()}).strict(),r_=l.object({name:l.string().min(1),description:l.string().min(1).optional(),_meta:ei.optional(),roles:ft,groups:ft,public:l.boolean().optional()}).strict(),n_=l.object({uri:l.string().min(1),name:l.string().min(1).optional(),description:l.string().min(1).optional(),mimeType:l.string().min(1).optional(),_meta:ei.optional(),roles:ft,groups:ft,public:l.boolean().optional()}).strict(),o_=l.object({uriTemplate:l.string().min(1),name:l.string().min(1).optional(),description:l.string().min(1).optional(),mimeType:l.string().min(1).optional(),_meta:ei.optional(),roles:ft,groups:ft,public:l.boolean().optional()}).strict(),i_=l.array(l.union([l.string(),t_])),s_=l.array(l.union([l.string(),r_])),a_=l.array(l.union([l.string(),n_])),c_=l.array(l.union([l.string(),o_])),d_=l.object({module:l.unknown(),export:l.string().min(1)}).strict(),u_=l.object({mode:l.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:l.string().min(1).optional(),groupClaim:l.string().min(1).optional(),identifier:d_.optional()}).strict(),l_=l.object({tools:i_.optional(),prompts:s_.optional(),resources:a_.optional(),resourceTemplates:c_.optional(),accessControl:u_.optional()}).strict(),ht=[{option:"tools",listMethod:"tools/list",resultProperty:"tools",itemProperty:"name",directMethods:["tools/call"]},{option:"prompts",listMethod:"prompts/list",resultProperty:"prompts",itemProperty:"name",directMethods:["prompts/get"]},{option:"resources",listMethod:"resources/list",resultProperty:"resources",itemProperty:"uri",directMethods:["resources/read"]},{option:"resourceTemplates",listMethod:"resources/templates/list",resultProperty:"resourceTemplates",itemProperty:"uriTemplate",directMethods:[]}];function p_(e,t){return Pu(l_,e,`MCP capability filter policy "${t}"`)}n(p_,"parseMcpCapabilityFilterOptions");function Se(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Se,"isRecord");function Kn(e){return typeof e.method=="string"?e.method:void 0}n(Kn,"messageMethod");function Cp(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}n(Cp,"correlationKey");function Ip(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}n(Ip,"asStringArray");function Tp(e,t){if(!Se(e))return[];let r=t in e?e[t]:t.split(".").reduce((o,i)=>Se(o)?o[i]:void 0,e);return Array.isArray(r)?r.filter(o=>typeof o=="string"):typeof r=="string"?r.split(/\s+/).filter(o=>o.length>0):[]}n(Tp,"readClaimValues");function Ps(e,t){if(typeof e=="string")return{key:e,public:!1};if(!Se(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:Ip(e.roles),groups:Ip(e.groups),public:e.public===!0}}n(Ps,"normalizeEntry");function m_(e,t,r){if(e.public)return!0;let o=e.roles??[],i=e.groups??[];return o.length===0&&i.length===0?!1:o.some(s=>t.has(s))||i.some(s=>r.has(s))}n(m_,"isCallerAllowed");function Qo(e,t,r,o){if(e===void 0)return;let i=[];for(let s of e){let c=Ps(s,t);c!==void 0&&m_(c,r,o)&&i.push(c.key)}return i}n(Qo,"allowedKeys");var Ap=n((e,t,r)=>{let o=r.accessControl?.roleClaim??"roles",i=r.accessControl?.groupClaim??"groups",s=new Set(Tp(e.user?.data,o)),c=new Set(Tp(e.user?.data,i));return{tools:Qo(r.tools,"name",s,c),prompts:Qo(r.prompts,"name",s,c),resources:Qo(r.resources,"uri",s,c),resourceTemplates:Qo(r.resourceTemplates,"uriTemplate",s,c)}},"claimsCapabilityResolver");function h_(e,t){let r=[];for(let o of ht){let i=e[o.option];if(i!==void 0)for(let s of i){let c=Ps(s,o.itemProperty);if(c===void 0)continue;let a=(c.roles?.length??0)>0||(c.groups?.length??0)>0;c.public&&a&&r.push(`${o.option} "${c.key}"`)}}if(r.length>0)throw new K(`MCP capability filter policy "${t}" - with accessControl.mode "rolesAndGroups", a capability cannot set both "public": true and roles/groups ("public" opens it to everyone, roles/groups restrict it). Remove one of the two on: ${r.join(", ")}`)}n(h_,"assertNoConflictingMarkup");function f_(e,t){let r=[];for(let o of ht){let i=e[o.option];if(i!==void 0)for(let s of i){let c=Ps(s,o.itemProperty);c!==void 0&&((c.roles?.length??0)>0||(c.groups?.length??0)>0||c.public)&&r.push(`${o.option} "${c.key}"`)}}if(r.length>0)throw new K(`MCP capability filter policy "${t}" - accessControl.mode is "allPublic" (the default) but these capabilities set roles/groups/public; set accessControl.mode to "rolesAndGroups" or remove the markup: ${r.join(", ")}`)}n(f_,"assertNoMarkup");function g_(e,t){let r=e.identifier;if(r===void 0)throw new K(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);if(r.module===null||typeof r.module!="object")throw new K(`MCP capability filter policy "${t}" - accessControl.identifier.module must reference a module, e.g. $import(./modules/mcp-access-control)`);if(!r.export)throw new K(`MCP capability filter policy "${t}" - accessControl.identifier.export must be specified`);let o=r.module[r.export];if(typeof o!="function")throw new K(`MCP capability filter policy "${t}" - accessControl.identifier must resolve to a valid function`);let i=o;return async(s,c,a)=>{let u=await i(s,c,a);if(u==null)throw new v(`MCP capability filter policy "${t}" - accessControl resolver returned no value; return an AllowedCapabilities object (use empty arrays to deny)`);if(typeof u!="object"||Array.isArray(u))throw new v(`MCP capability filter policy "${t}" - accessControl resolver must return an AllowedCapabilities object`);return u}}n(g_,"buildCustomResolver");function y_(e,t){let r=e.accessControl,o=r?.mode??"allPublic";if(o==="function"){if(r===void 0)throw new K(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);return g_(r,t)}if(o==="rolesAndGroups")return h_(e,t),Ap;f_(e,t)}n(y_,"buildCapabilityResolver");function S_(e){let t={};for(let r of ht){let o=e[r.option];if(o===void 0)continue;let i=new Map;for(let s of o){let c=v_(s,r.itemProperty);c!==void 0&&i.set(c.key,c)}t[r.option]=i}return t}n(S_,"buildProjectionMaps");function Ts(e){return e===void 0?void 0:ht.find(t=>t.listMethod===e)}n(Ts,"findListRule");function __(e){return e===void 0?void 0:ht.find(t=>t.directMethods.includes(e))}n(__,"findDirectRule");function w_(e){switch(e.method){case"tools/call":return{option:"tools",target:e.params.name};case"prompts/get":return{option:"prompts",target:e.params.name};case"resources/read":return{option:"resources",target:e.params.uri};default:return}}n(w_,"directCapabilityAccess");function R_(e){let t=__(Kn(e));if(t===void 0||!Se(e.raw))return;let r=e.raw.params;if(!Se(r))return;let o=r[t.itemProperty==="uri"?"uri":"name"];return typeof o=="string"?{option:t.option,target:o}:void 0}n(R_,"rawDirectCapabilityAccess");function b_(e){return Response.json(Xo({...e==null?{}:{id:e},error:{code:A.MethodNotFound,message:"Method not found"}}))}n(b_,"methodNotFoundResponse");function v_(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!Se(e))return;let r=e[t];if(typeof r!="string")return;let o={...e};return delete o.roles,delete o.groups,delete o.public,{key:r,overlay:o}}n(v_,"buildProjection");function kp(e){let t=e.base[e.property],r=e.overlay[e.property];return Se(r)?Se(t)?{...t,...r}:r:t}n(kp,"mergeRecordProperty");function C_(e,t){let r={...e,...t.overlay},o=kp({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let i=kp({base:e,overlay:t.overlay,property:"_meta"});return i!==void 0&&(r._meta=i),r}n(C_,"applyProjection");function Pp(e,t,r,o){if(!Se(e))return e;let i=e.result;if(!Se(i))return e;let s=i[t.resultProperty];return!Array.isArray(s)||!s.every(c=>Se(c)&&typeof c[t.itemProperty]=="string")?e:{...e,result:{...i,[t.resultProperty]:s.flatMap(c=>{if(!Se(c))return[];let a=c[t.itemProperty];if(typeof a!="string")return[];if(o!==void 0&&!o.has(a))return[];let u=r.get(a);return u===void 0?[]:[C_(c,u)]})}}}n(Pp,"filterAndProjectItems");function I_(e){let{envelope:t,responseBody:r,projectionMaps:o,allowedSets:i}=e;if(Array.isArray(r)){if(t.shape!=="batch")return r;let u=new Map;for(let p of t.messages){let h=Ts(Kn(p)),f=h===void 0?void 0:Cp(p.id);h!==void 0&&f!==void 0&&u.set(f,h)}return u.size===0?r:r.map(p=>{if(!Se(p)||"error"in p)return p;let h=Cp(p.id),f=h===void 0?void 0:u.get(h),y=f===void 0?void 0:o[f.option];return f===void 0||y===void 0?p:Pp(p,f,y,i?.[f.option])})}if(t.shape!=="single"||!Se(r)||"error"in r)return r;let s=t.messages[0],c=Ts(s===void 0?void 0:Kn(s)),a=c===void 0?void 0:o[c.option];return c===void 0||a===void 0?r:Pp(r,c,a,i?.[c.option])}n(I_,"filterResponseBody");function T_(e){return e.headers.get("content-type")?.includes("json")??!1}n(T_,"isJsonResponse");var ks=class extends Io{static{n(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#t;constructor(t,r){let o=p_(t,r);super(o,r),this.#r=r,this.#e=S_(o),this.#t=y_(o,r)}async handler(t,r){let o=await hl(t);if(o===null)return t;let i=this.#t!==void 0&&this.#n(o)?await this.#i(t,r):void 0;for(let c of o.messages){let a=c.type==="request"?w_(c):R_(c);if(a===void 0)continue;let u=this.#e[a.option];if(u===void 0)continue;let p=i?.[a.option];if(!u.has(a.target)||p!==void 0&&!p.has(a.target))return b_(c.type==="request"?c.id:c.id??void 0)}if(!this.#o(o))return t;let s=this.#e;return r.addResponseSendingHook(async c=>{if(!T_(c))return c;let a;try{a=await c.clone().json()}catch{return c}let u=I_({envelope:o,responseBody:a,projectionMaps:s,allowedSets:i});if(u===a)return c;let p=new Headers(c.headers);return p.delete("content-length"),new Response(JSON.stringify(u),{status:c.status,statusText:c.statusText,headers:p})}),t}#n(t){return t.messages.some(r=>{let o=Kn(r);return o===void 0?!1:ht.some(i=>this.#e[i.option]===void 0?!1:i.listMethod===o||i.directMethods.includes(o))})}#o(t){return t.messages.some(r=>{let o=Ts(Kn(r));return o!==void 0&&this.#e[o.option]!==void 0})}async#i(t,r){let o=this.#t;if(o===void 0)return{};let i;try{i=await o(t,r,this.options)}catch(c){r.log.error(`MCP capability filter policy "${this.#r}" - access-control resolver threw; denying configured capabilities`,c);let a={};for(let u of ht)this.#e[u.option]!==void 0&&(a[u.option]=new Set);return a}let s={};for(let c of ht){let a=this.#e[c.option];if(a===void 0)continue;let u=i[c.option];if(u===void 0)continue;let p=new Set;if(Array.isArray(u))for(let h of u)typeof h=="string"&&a.has(h)&&p.add(h);s[c.option]=p}return s}};var As="zuplo.com",k_=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),P_=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Ep(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(Ep,"s2FaviconHref");function A_(e){return`https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&drop_404_icon=true&fallback_opts=TYPE,SIZE,URL&url=http://${e}&size=128`}n(A_,"strictFaviconHref");var ti=Ep(As);function Es(e){let t=e.toLowerCase();return t===As||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Ep(As):A_(e)}n(Es,"resolveIconHref");function E_(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(E_,"hostnameFromHost");function x_(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(x_,"isLocalOrAddressHost");function U_(e){let t=E_(e).toLowerCase().replace(/\.$/,"");if(x_(t)||P_.some(s=>t===s.slice(1)||t.endsWith(s)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let o=r.slice(-2).join("."),i=k_.has(o)?3:2;return r.slice(-i).join(".")}n(U_,"inferFaviconDomain");function xs(e){return{src:Es(U_(e)),mimeType:"image/png",sizes:["128x128"]}}n(xs,"resolveMcpFaviconIcon");function ri(e){try{return xs(new URL(e).host)}catch{return}}n(ri,"resolveMcpFaviconIconFromUrl");function gt(e){let t=ye().connectionsById.get(e);if(!t)throw new K(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,description:t.description,serverInfo:t.serverInfo,transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}n(gt,"getUpstreamServerConfig");function ni(e){let t=ye().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new K(`Unknown auth profile "${String(e.authProfileId)}" for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares a matching auth mode for that upstream connection.`);return t.authConfig}n(ni,"getUpstreamAuthConfig");function br(e,t){let r=ni({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new K(`Upstream server "${e}" does not use upstream OAuth. Select authMode "shared-oauth" or "user-oauth" before starting an upstream OAuth connection flow.`);return r.oauth}n(br,"requireUpstreamOAuthConfig");function xp(e,t){let r=ni({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new K(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}n(xp,"requireUpstreamIdJagConfig");function Up(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let r=n(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",r,{once:!0}),()=>t.removeEventListener("abort",r)}n(Up,"mergeAbortSignals");async function O_(e){try{await e.cancel()}catch{}}n(O_,"cancelReader");async function oi(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],i=0,s=await r.read();for(;!s.done;){let u=s.value;if(i+=u.byteLength,i>t.maxBytes)throw await O_(r),t.createLimitError();o.push(u),s=await r.read()}let c=new Uint8Array(i),a=0;for(let u of o)c.set(u,a),a+=u.byteLength;return c}n(oi,"readBoundedByteStream");var q_=2,z_=1024*1024,M_=1e4,N_=new Set([301,302,303,307,308]),j_=["authorization","proxy-authorization","cookie","cookie2"];function Us(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Us,"readRequestUrl");function vr(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(vr,"readRequestMethod");function $_(e,t,r){let o=e.headers.get("content-length");if(!o)return;let i=Number.parseInt(o,10);if(Number.isFinite(i)&&i>t)throw new v({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[I]:r}})}n($_,"assertContentLengthWithinLimit");async function D_(e,t,r){return $_(e,t,r),oi(e.body,{maxBytes:t,createLimitError:n(()=>new v({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[I]:r}}),"createLimitError")})}n(D_,"readBoundedResponseBody");function L_(e,t){let r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}n(L_,"responseFromBufferedBody");function H_(e,t){if(!N_.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(H_,"resolveRedirectUrl");function Op(e,t){try{return t.validateUrl(e)}catch(r){throw new v({message:"Outbound URL was not allowed.",extensionMembers:{[I]:t.problemCode}},{cause:r})}}n(Op,"validateOutboundUrl");function B_(e,t){throw e instanceof v&&qo(e.extensionMembers?.[I])?e:new v({message:"Outbound fetch failed.",extensionMembers:{[I]:t}},{cause:e})}n(B_,"normalizeFetchError");function Wn(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[o,i]of Object.entries(t.extra))i!==void 0&&(r[o]=i);t.error!==void 0&&pe(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(Wn,"logOutboundFailure");async function F_(e,t,r,o,i,s,c){let a=vr(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";Wn(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:i,method:a,host:te(s),error:u,extra:{abortReason:c()}}),B_(u,i)}}n(F_,"fetchWithNormalizedError");function G_(e){if(e.redirects>=e.maxRedirects)throw new v({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[I]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new v({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[I]:e.problemCode}})}n(G_,"assertRedirectAllowed");function J_(e,t){let r=new Headers(e);for(let o of j_)r.delete(o);for(let o of t)r.delete(o);return r}n(J_,"stripCrossOriginHeaders");function V_(e,t,r,o,i){let s={...e,method:t,redirect:"manual",signal:r};return o&&(s.headers=J_(e.headers,i)),s}n(V_,"buildRedirectInit");function K_(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(K_,"buildInitialRequestInit");function W_(e){let t=vr(e.currentInput,e.currentInit);G_({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=Op(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),o=new URL(e.currentUrl),i=r.origin!==o.origin,s=r.toString();return{currentInput:s,currentUrl:s,currentInit:V_(e.currentInit,t,e.signal,i,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(W_,"followRedirect");async function Os(e,t,r){let o=r.problemCode??"invalid_request",i=r.maxRedirects??q_,s=r.maxResponseBytes??z_,c=r.timeoutMs??M_,a=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,h=new AbortController,f=Up(h,t.signal),y=!1,S=setTimeout(()=>{y=!0,h.abort()},c),k=e,w=K_(e,t,h.signal),C;try{C=Op(Us(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(O){throw Wn(p,{event:"outbound_url_blocked",problemCode:o,method:vr(e,t),host:te(Us(e)),error:O}),clearTimeout(S),f?.(),O}let U=0;try{for(;;){let O=await F_(p,a,k,w,o,C,()=>y?`timeout_after_${c}ms`:void 0),L=H_(O,C);if(L!==void 0)try{let F=W_({currentInput:k,currentInit:w,currentUrl:C,redirectUrl:L,redirects:U,maxRedirects:i,problemCode:o,validateUrl:r.validateUrl,signal:h.signal,additionalCrossOriginStrippedHeaders:u});k=F.currentInput,w=F.currentInit,C=F.currentUrl,U=F.redirects;continue}catch(F){throw Wn(p,{event:"outbound_redirect_blocked",problemCode:o,method:vr(k,w),host:te(C),error:F,extra:{redirects:U,maxRedirects:i,redirectTargetHost:te(L)}}),F}try{return L_(O,await D_(O,s,o))}catch(F){throw Wn(p,{event:"outbound_response_size_exceeded",problemCode:o,method:vr(k,w),host:te(C),error:F,extra:{maxResponseBytes:s,status:O.status}}),F}}}finally{clearTimeout(S),f?.()}}n(Os,"runSafeOutboundExchange");async function Zn(e,t,r){let o=await Os(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(i){throw Wn(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:vr(e,t),host:te(Us(e)),error:i,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new v({message:"Outbound JSON response could not be parsed.",extensionMembers:{[I]:r.problemCode??"invalid_request"}},{cause:i})}}n(Zn,"runSafeOutboundJsonExchange");function qp(e,t={},r={}){return Os(e,t,{...r,validateUrl:$n})}n(qp,"fetchConfiguredOutbound");function zp(e,t={},r={}){return Zn(e,t,{...r,validateUrl:$n})}n(zp,"fetchConfiguredOutboundJson");function ii(e,t={},r={}){return Zn(e,t,{...r,validateUrl:nl})}n(ii,"fetchIdentityProviderJson");function Mp(e,t={},r={}){return Zn(e,t,{...r,validateUrl:Lo})}n(Mp,"fetchCimdClientMetadataJson");function Np(e,t={},r={}){return Zn(e,t,{...r,validateUrl:Dn})}n(Np,"fetchCimdClientJwksJson");import{errors as Bp,jwtVerify as Fp,SignJWT as Gp}from"jose";var _e="zuplo-mcp-gateway",Ce=_e,Ie="HS256";import{base64url as Z_}from"jose";var Y_=new TextEncoder,X_="MCP gateway could not initialize secure key material.",Q_=32,jp=new Map,$p=new Map,ew;function tw(){return ew??Aa.instance.authPrivateKey}n(tw,"readAuthPrivateKey");function Dp(e){return new Pe(X_,e===void 0?void 0:{cause:e})}n(Dp,"createGeneratedKeyMaterialError");function Lp(e,t){let r=Z_.decode(t);if(r.byteLength!==Q_)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(Lp,"decodeJwkKeyField");function rw(e){let t=tw();if(!t)throw Dp();try{let r=JSON.parse(t);if(r.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.d!="string"||typeof r.x!="string")throw new Error("Generated deployment auth key is not an Ed25519 JWK.");let o=Lp("d",r.d);Lp("x",r.x);let i=Y_.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),s=new Uint8Array(i.byteLength+o.byteLength);return s.set(i),s.set(o,i.byteLength),s}catch(r){throw Dp(r)}}n(rw,"decodeGeneratedKeyMaterial");function nw(e){let t=jp.get(e);return t||(t=rw(e),jp.set(e,t)),t}n(nw,"getMasterKeyMaterial");async function Le(e){let t=$p.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(nw(e.keyMaterialPurpose));return $p.set(e.purpose,r),r}n(Le,"readCachedDerivedKey");var ow="SHA-256",iw=32,sw="zuplo-mcp-gateway:",aw=new TextEncoder,Hp=new WeakMap;async function yt(e,t){let r=Hp.get(e);r||(r=new Map,Hp.set(e,r));let o=r.get(t);if(o)return o;let i=await cw(e,t);return r.set(t,i),i}n(yt,"deriveGatewaySigningKey");async function cw(e,t){let r=me(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=aw.encode(`${sw}${t}`),s=await crypto.subtle.deriveBits({name:"HKDF",hash:ow,salt:new Uint8Array,info:me(i)},o,iw*8);return new Uint8Array(s)}n(cw,"hkdfExpand");var Jp=900,dw=900,uw=$u.extend({id:cl}),lw=uw.extend({exp:l.number().int().positive(),iat:l.number().int().positive().optional()}),Vp=Li.extend({id:dl,purpose:l.literal("browser_connect")}),pw=Li.extend({purpose:l.literal("browser_connect")}),mw=Vp.extend({exp:l.number().int().positive(),iat:l.number().int().positive().optional()}),Kp=Jp*1e3;async function Wp(){return Le({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>yt(e,"oauth-state"),"derive")})}n(Wp,"getOAuthStateKey");async function Zp(){return Le({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>yt(e,"browser-connect"),"derive")})}n(Zp,"getBrowserConnectKey");async function Yp(e){let t=Math.floor(Date.now()/1e3)+Jp;return new Gp(e).setProtectedHeader({alg:Ie,typ:"JWT"}).setIssuer(_e).setAudience(Ce).setIssuedAt().setExpirationTime(t).sign(await Wp())}n(Yp,"signOAuthState");async function si(e){try{let{payload:t}=await Fp(e,await Wp(),{algorithms:[Ie],issuer:_e,audience:Ce});return lw.parse(t)}catch(t){throw t instanceof Bp.JWTExpired?new v({message:"OAuth state has expired",extensionMembers:{[I]:"oauth_state_expired"}},{cause:t}):new v({message:"OAuth state could not be verified",extensionMembers:{[I]:"oauth_state_invalid"}},{cause:t})}}n(si,"verifyOAuthState");async function Xp(e){let t=Math.floor(Date.now()/1e3)+dw,r=pw.parse(e),o=Vp.parse({...r,id:ml()});return new Gp(o).setProtectedHeader({alg:Ie,typ:"JWT"}).setIssuer(_e).setAudience(Ce).setIssuedAt().setExpirationTime(t).sign(await Zp())}n(Xp,"signBrowserConnectTicket");async function Qp(e){try{let{payload:t}=await Fp(e,await Zp(),{algorithms:[Ie],issuer:_e,audience:Ce});return mw.parse(t)}catch(t){throw t instanceof Bp.JWTExpired?new v({message:"Browser connect ticket has expired",extensionMembers:{[I]:"oauth_state_expired"}},{cause:t}):new v({message:"Browser connect ticket could not be verified",extensionMembers:{[I]:"oauth_state_invalid"}},{cause:t})}}n(Qp,"verifyBrowserConnectTicket");async function em(e){if((await N().consumeBrowserConnectTicket({id:e.id,expiresAt:$(new Date(e.exp*1e3)),now:$(new Date)})).kind==="consumed")throw new v({message:"Browser connect ticket has already been used",extensionMembers:{[I]:"oauth_state_reused"}})}n(em,"consumeBrowserConnectTicket");function hw(e,t,r=!1){return r?`${e} authorization must be renewed before this ${t} can be used.`:`${e} authorization is required before this ${t} can be used.`}n(hw,"buildConnectRequiredMessage");async function fw(e){let t=Y(e.requestUrl,e.requestHeaders),r=new URL(e.path,t);return e.redirect&&r.searchParams.set("redirect","true"),r.searchParams.set("operationId",e.operationId),r.searchParams.set("browserTicket",await Xp({...Nn(e),purpose:"browser_connect"})),r.toString()}n(fw,"buildGatewayBrowserTicketUrl");function gw(e){return de().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(gw,"buildGatewayConnectPath");async function qs(e){return fw({...e,path:gw(e.upstreamServerId),redirect:!0})}n(qs,"buildGatewayConnectUrl");async function ai(e){let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await qs(t),message:hw(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(ai,"buildRedirectConnectRequiredResponse");function tm(e){return yw({...e,message:e.requiresReconsent?`An administrator must reconnect ${e.upstreamDisplayName} before this tool can be used.`:`An administrator must connect ${e.upstreamDisplayName} before this tool can be used.`})}n(tm,"buildAdminConnectRequiredResponse");function yw(e){return{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},message:e.message,nextAction:"admin_setup_required"}}n(yw,"buildAdminSetupRequiredResponse");var rm=12;async function nm(e){let t=await crypto.subtle.digest("SHA-256",me(new TextEncoder().encode(e)));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}n(nm,"sha256Hex");async function Lt(e){if(e)return(await nm(e)).slice(0,rm)}n(Lt,"fingerprintSecret");async function Cr(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await nm(t)).slice(0,rm)}n(Cr,"fingerprintConnectionIdentity");var Sw=6e4;function Ir(e,t){return e===void 0?!0:e.status!==t.status||e.encryptedAccessToken!==t.encryptedAccessToken||e.encryptedRefreshToken!==t.encryptedRefreshToken||e.expiresAt!==t.expiresAt||e.scopes.length!==t.scopes.length||e.scopes.some((r,o)=>t.scopes[o]!==r)}n(Ir,"credentialGenerationChanged");function he(e){if(!e)return"no_connection";if(e.status!=="active")return"inactive";if(!e.encryptedAccessToken)return"no_access_token";if(e.expiresAt){let t=new Date(e.expiresAt).getTime();if(t<=Date.now())return"expired";if(t<=Date.now()+Sw)return"near_expiry"}return"usable"}n(he,"describeAccessTokenState");var om=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function _w(e,t){return e&&e.length>0?e.join(t):void 0}n(_w,"joinOAuthScopes");function ww(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of om)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(ww,"sanitizeAuthorizationServerMetadata");function im(e){let t=ww(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(im,"sanitizeOAuthDiscoveryState");function sm(e){let t=new URL(e);for(let r of om){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(sm,"dedupeSingletonAuthorizationRequestParams");function ci(e){let t=new URL(e);return be(t)&&ku(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(ci,"normalizeLoopbackOAuthRedirectUri");function am(e){return _w(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(am,"readProtectedResourceMetadataScope");function Rw(e){return`Zuplo MCP Gateway - ${e}`}n(Rw,"buildGatewayOAuthClientName");function bw(e,t){return e&&e.length>0?e.join(t):void 0}n(bw,"joinOAuthScopeList");function vw(e){if(e.clientRegistration.mode!=="auto")return bw(e.scopes,e.scopeDelimiter)}n(vw,"readPublicClientMetadataScope");function zs(e){return new URL(de().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(zs,"buildOAuthClientMetadataDocumentUrl");function Ms(e){let t=gt(e.upstreamServerId);return{client_name:Rw(t.displayName),client_uri:new URL("/",e.origin).toString(),redirect_uris:[e.redirectUri],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",...e.scope===void 0?{}:{scope:e.scope},token_endpoint_auth_method:"none"}}n(Ms,"buildGatewayOAuthClientMetadata");function cm(e,t,r){let o=br(t,r),i=vw(o);return{client_id:zs({origin:e,upstreamServerId:t}),...Ms({origin:e,upstreamServerId:t,redirectUri:ci(new URL(o.redirectPath,e)).toString(),scope:i})}}n(cm,"buildOAuthClientMetadataDocument");import{base64url as St}from"jose";var Cw="SHA-256",Tr="AES-GCM",Iw=12,js="zuplo-secret",$s=1,dm="generated:auth_private_key:token-encryption",Tw=l.object({version:l.literal($s),keyId:l.literal(dm),algorithm:l.literal(Tr),iv:l.string().min(1),ciphertext:l.string().min(1)}).strict();async function Ns(){return Le({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(Cw,me(e));return crypto.subtle.importKey("raw",t,{name:Tr},!1,["encrypt","decrypt"])},"derive")})}n(Ns,"getEncryptionKey");function um(e){return me(new TextEncoder().encode(`${js}:v${e.version}:${e.keyId}`))}n(um,"getAssociatedData");function kw(e){return`${js}:v${e.version}:${St.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(kw,"encodeEnvelope");function Pw(e){let t=`${js}:v${$s}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(St.decode(r));return Tw.parse(JSON.parse(o))}n(Pw,"decodeEnvelope");async function Ze(e){let t=await Ns(),r=crypto.getRandomValues(new Uint8Array(Iw)),o={version:$s,keyId:dm},i=await crypto.subtle.encrypt({name:Tr,iv:r,additionalData:um(o)},t,new TextEncoder().encode(e));return kw({...o,algorithm:Tr,iv:St.encode(r),ciphertext:St.encode(new Uint8Array(i))})}n(Ze,"encryptSecret");async function Ye(e){let t=Pw(e);if(t){let c=await Ns(),a=await crypto.subtle.decrypt({name:Tr,iv:me(St.decode(t.iv)),additionalData:um(t)},c,me(St.decode(t.ciphertext)));return new TextDecoder().decode(a)}let[r,o]=e.split(".");if(!r||!o)throw new Pe("Encrypted payload is malformed");let i=await Ns(),s=await crypto.subtle.decrypt({name:Tr,iv:me(St.decode(r))},i,me(St.decode(o)));return new TextDecoder().decode(s)}n(Ye,"decryptSecret");var lm={issuer:l.string().min(1).optional()},Aw=l.union([jt.extend(lm),zn.extend(lm)]),pm=l.object({authorizationServerUrl:l.url(),resourceMetadataUrl:l.url().optional(),resourceMetadata:pr.optional(),authorizationServerMetadata:l.union([mr,hr]).optional()}).passthrough(),Ew="Bearer",xw="__zuplo_refresh_only_upstream_access_token__";function Ds(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Ds,"splitScopes");function Ls(e,t){let r=new Set(e);return t.every(o=>r.has(o))}n(Ls,"scopesCover");function Uw(e){return gr.parse(e)}n(Uw,"parsePkceCodeVerifier");function Ow(e){if(typeof e.expires_in=="number")return $(new Date(Date.now()+e.expires_in*1e3))}n(Ow,"readTokenExpiry");async function mm(e){if(e!==void 0)return Ze(JSON.stringify(e))}n(mm,"encryptJson");async function hm(e,t){if(!e)return;let r=await Ye(e);try{return t.parse(JSON.parse(r))}catch(o){throw new v({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[I]:"oauth_state_invalid"}},{cause:o})}}n(hm,"decryptJson");function qw(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(qw,"clientInformationAllowsRedirectUri");function zw(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(zw,"clientInformationMatchesCurrentClientMetadataUrl");function Mw(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(Mw,"isUrlBasedClientInformation");function Nw(e,t){return t===void 0?e:{...e,scope:t}}n(Nw,"applyOAuthClientMetadataScope");function jw(e,t){return am({state:e,delimiter:t})}n(jw,"readResourceMetadataScope");function $w(e,t){return e&&e.length>0?e.join(t):void 0}n($w,"joinOAuthScopeList");function Dw(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new K(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return jt.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(Dw,"buildManualOAuthClientInformation");function Lw(e,t){let r=zs({origin:new URL(t).origin,upstreamServerId:e});return Is(r)?r:void 0}n(Lw,"buildClientMetadataUrl");function Hw(e){for(let t of e)if(t!==void 0)return t}n(Hw,"firstDefined");function Bw(e){let t=br(e.target.upstreamServerId,e.target.authProfileId),r=$w(t.scopes,t.scopeDelimiter),o=Ms({origin:new URL(e.redirectUri).origin,upstreamServerId:e.target.upstreamServerId,redirectUri:e.redirectUri,scope:r});if(t.clientRegistration.mode==="manual")return{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,configuredClientInformation:Dw({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let i=Lw(e.target.upstreamServerId,e.redirectUri);return i===void 0?{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,clientMetadataUrl:i}}n(Bw,"buildInitialOAuthClientSetup");function Fw(e,t){if(t===void 0)return Hw([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(Fw,"readEncryptedClientInformation");function Gw(e){return e.pendingState?.encryptedDiscoveryState}n(Gw,"readEncryptedDiscoveryState");function Hs(e,t){return t===void 0?e:{...e,issuer:t}}n(Hs,"applyIssuerStamp");var _t=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredScope;scopeDelimiter;promptOverride;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;credentialState;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;tokensLoaded=!1;tokenPersistenceOutcome;connectionFingerprintValue;usedRefreshTokenFingerprintValue;constructor(t){let r=Bw({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.clientMetadataValue=r.clientMetadata,this.configuredScope=r.configuredScope,this.scopeDelimiter=r.scopeDelimiter,this.promptOverride=r.promptOverride,this.configuredClientInformation=r.configuredClientInformation,r.clientMetadataUrl!==void 0&&(this.clientMetadataUrl=r.clientMetadataUrl),this.credentialState={sourceConnection:t.connection,currentConnection:t.connection},this.pendingState=t.pendingState?{...t.pendingState}:void 0,this.encryptedClientInformation=Fw(t,this.configuredClientInformation),this.encryptedDiscoveryState=Gw(t)}get authorizationUrl(){return this.authorizationUrlValue}get configuredAuthorizationScope(){return this.configuredScope}get usedRefreshTokenFingerprint(){return this.usedRefreshTokenFingerprintValue}get currentConnection(){return this.credentialState.currentConnection}get tokenWriteWasPersisted(){return this.tokenPersistenceOutcome==="persisted"}connectionSatisfiesRequestedScope(t,r){let o=Ds(this.configuredScope??r??this.readEffectiveScope());return Ls(t.scopes,o)}readUsablePeerAdoption(t){let r=this.credentialState.peerAdoption?.connection;return r!==void 0&&he(r)==="usable"&&this.connectionSatisfiesRequestedScope(r,t)?r:void 0}async adoptConnectionForDirectResolution(t,r){this.adoptPeerConnection(t,r),this.tokensLoaded=!1,this.credentialState.sdkTokenMemo=void 0;let o=W();o&&o.info({event:"upstream_oauth_peer_credential_adopted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:t.id,adoptionReason:r,sourceUpdatedAt:this.credentialState.sourceConnection?.updatedAt,resultingUpdatedAt:t.updatedAt,sourceScopeCount:this.credentialState.sourceConnection?.scopes.length,resultingScopeCount:t.scopes.length,accessTokenGenerationFingerprint:await this.storedSecretFingerprint(t.encryptedAccessToken),refreshTokenGenerationFingerprint:await this.storedSecretFingerprint(t.encryptedRefreshToken)},"Adopted a concurrent upstream OAuth credential")}adoptPeerConnection(t,r){this.credentialState.currentConnection=t,this.credentialState.peerAdoption={connection:t,reason:r}}async connectionFingerprint(){return this.connectionFingerprintValue===void 0&&(this.connectionFingerprintValue=await Cr({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}async storedSecretFingerprint(t){if(t!==void 0)try{return await Lt(await Ye(t))}catch{return}}async conditionalUpsertCredential(t,r){try{return await N().conditionalUpsertUpstreamConnection(t,r)}catch(o){let i=W();if(i){let s=Object.assign(new Error("Upstream OAuth conditional storage write failed",{cause:o}),{event:"upstream_oauth_conditional_write_failed",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),sourceUpdatedAt:"expectedUpdatedAt"in r?r.expectedUpdatedAt:void 0,expectAbsent:"expectAbsent"in r,scopeCount:t.scopes.length});i.error(s,"Upstream OAuth conditional storage write failed")}throw o}}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return Nw(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return Yp({id:t.id,...Nn({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId})})}async clientInformation(t){return this.configuredClientInformation?Hs(this.configuredClientInformation,t?.issuer):this.loadPersistedClientInformation(t)}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,W()?.info({event:"upstream_oauth_client_registered",upstreamServerId:this.target.upstreamServerId,clientId:"client_id"in t?t.client_id:void 0,redirectUriCount:"redirect_uris"in t?t.redirect_uris.length:void 0},"Upstream OAuth client registered for the gateway"),!Mw({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await mm(t),await this.syncPendingState(!1)))}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=im(pm.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await mm(r),await this.syncPendingState(!1),W()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:te(r.authorizationServerUrl),resourceMetadataHost:te(r.resourceMetadataUrl),resource:r.resourceMetadata?.resource,scopesSupportedCount:r.resourceMetadata?.scopes_supported?.length,hasResourceMetadata:r.resourceMetadata!==void 0},"Upstream OAuth discovery resolved authorization server and resource"),this.inferredScope=jw(r,this.scopeDelimiter);let o=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&o!==void 0){let i=Ds(this.configuredScope).filter(s=>!o.includes(s));i.length>0&&W()?.debug({event:"upstream_oauth_configured_scopes_not_advertised",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,unadvertisedScopes:i,scopesSupported:o},"Configured upstream OAuth scopes include values the resource metadata does not advertise")}}async tokens(t){let r=await this.loadStoredTokens();if(r!==void 0)return Hs(r,t?.issuer)}async saveTokens(t){let r=at.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=this.credentialState.sourceConnection,s=!r.refresh_token&&!!i?.encryptedRefreshToken,c=r.refresh_token?await Ze(r.refresh_token):i?.encryptedRefreshToken;this.credentialState.sdkTokenMemo=r.refresh_token||!i?.encryptedRefreshToken?r:at.parse({...r,refresh_token:await Ye(i.encryptedRefreshToken)}),this.tokensLoaded=!0;let a={id:i?.id??Ho(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await Ze(r.access_token),encryptedRefreshToken:c,scopes:Ds(r.scope??this.readEffectiveScope()),expiresAt:Ow(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)},u=i?{expectedUpdatedAt:i.updatedAt}:{expectAbsent:!0},p=await this.conditionalUpsertCredential(a,u),h=!1;if(p.kind==="precondition_failed"&&p.connection!==void 0&&(he(p.connection)!=="usable"||!Ls(p.connection.scopes,a.scopes)||!Ir(i,p.connection))){h=!0;let y=p.connection,S={id:y.id,ownerMode:y.ownerMode,subjectId:y.subjectId,upstreamServerId:y.upstreamServerId,authProfileId:y.authProfileId,status:"active",encryptedAccessToken:a.encryptedAccessToken,encryptedRefreshToken:r.refresh_token===void 0?y.encryptedRefreshToken:a.encryptedRefreshToken,scopes:a.scopes,expiresAt:a.expiresAt,metadata:y.metadata};W()?.info({event:"upstream_oauth_bounded_rebase_attempted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:y.id,sourceUpdatedAt:i?.updatedAt,winnerUpdatedAt:y.updatedAt,sourceScopeCount:i?.scopes.length,winnerScopeCount:y.scopes.length,resultingScopeCount:S.scopes.length},"Retrying an upstream OAuth token write against the CAS winner"),p=await this.conditionalUpsertCredential(S,{expectedUpdatedAt:y.updatedAt})}if(p.kind!=="persisted"&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),this.tokenPersistenceOutcome=p.kind,p.kind==="persisted"?(this.credentialState.currentConnection=p.connection,this.credentialState.peerAdoption=void 0):p.kind==="precondition_failed"&&p.connection!==void 0?(this.credentialState.currentConnection=p.connection,Ir(i,p.connection)&&he(p.connection)==="usable"&&Ls(p.connection.scopes,a.scopes)?this.adoptPeerConnection(p.connection,"cas_loss"):this.credentialState.peerAdoption=void 0):(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0),h){let y=p.kind==="persisted"?"succeeded":p.kind==="precondition_failed"?"lost":"exhausted";W()?.info({event:`upstream_oauth_bounded_rebase_${y}`,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.credentialState.currentConnection?.id,sourceUpdatedAt:i?.updatedAt,resultingUpdatedAt:this.credentialState.currentConnection?.updatedAt,sourceScopeCount:i?.scopes.length,resultingScopeCount:this.credentialState.currentConnection?.scopes.length},`Upstream OAuth bounded rebase ${y}`)}let f=p.kind==="persisted"?p.connection:void 0;W()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:f?.id??this.credentialState.currentConnection?.id,hasRefreshToken:!!c,sourceScopeCount:i?.scopes.length,priorStatus:i?.status,priorUpdatedAt:i?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await Lt(r.refresh_token),reusedSnapshotRefreshToken:s,scopeCount:a.scopes.length,expiresAt:a.expiresAt,outcome:p.kind,rebaseAttempted:h,resultingUpdatedAt:f?.updatedAt??this.credentialState.currentConnection?.updatedAt,resultingScopeCount:f?.scopes.length??this.credentialState.currentConnection?.scopes.length},f?"Upstream OAuth tokens persisted; upstream connection is active":"Upstream OAuth token persistence yielded to concurrent storage state")}async redirectToAuthorization(t){let r=sm(t);this.promptOverride===!1?r.searchParams.delete("prompt"):this.promptOverride!==void 0&&r.searchParams.set("prompt",this.promptOverride),this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:Uw(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new v({message:"OAuth code verifier is missing",extensionMembers:{[I]:"oauth_state_invalid"}});return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",o=t==="all"||t==="client",i=t==="all"||t==="discovery",s=t==="all"||t==="verifier";o&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),i&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=void 0,this.challengeScope=void 0,this.inferredScope=void 0),r&&(this.credentialState.sdkTokenMemo=void 0,this.tokensLoaded=!0),await this.syncPendingState(s),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:pl(),...Nn({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,operationId:this.target.operationId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:$(new Date(Date.now()+Kp)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await N().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(t){if(this.clientInformationLoaded)return this.cachedClientInformation;let r;try{r=await hm(this.encryptedClientInformation,Aw)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(r&&(!qw(r,this.redirectUriValue)||!zw({clientInformation:r,clientMetadataUrl:this.clientMetadataUrl}))){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}return r===void 0&&this.pendingState?.codeVerifier!==void 0&&this.clientMetadataUrl!==void 0&&(r=Hs(zn.parse({client_id:this.clientMetadataUrl}),t?.issuer)),this.cachedClientInformation=r,this.clientInformationLoaded=!0,this.cachedClientInformation}async readCachedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;this.discoveryStateLoaded=!0;try{this.cachedDiscoveryState=await hm(this.encryptedDiscoveryState,pm)}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0}return this.cachedDiscoveryState}readEffectiveScope(){return this.configuredScope??this.challengeScope??this.inferredScope}async loadStoredTokens(){if(this.tokensLoaded)return this.credentialState.sdkTokenMemo;this.tokensLoaded=!0;let t=this.credentialState.currentConnection;if(!t||t.status!=="active"){W()?.debug({event:"upstream_oauth_tokens_not_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:t?.id,status:t?.status??"not_connected"},"Upstream OAuth tokens not loaded; connection is not active");return}let r=t.encryptedAccessToken?await Ye(t.encryptedAccessToken):void 0,o=t.encryptedRefreshToken?await Ye(t.encryptedRefreshToken):void 0;if(!r&&!o)return;let i=W();this.usedRefreshTokenFingerprintValue=i?await Lt(o):void 0,i?.debug({event:"upstream_oauth_tokens_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:t.id,hasAccessToken:!!r,hasRefreshToken:!!o,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,expiresAt:t.expiresAt},"Upstream OAuth tokens loaded from stored connection");let s=at.parse({access_token:r??xw,token_type:Ew,refresh_token:o,scope:t.scopes.length>0?t.scopes.join(" "):void 0});return this.credentialState.sdkTokenMemo=s,s}async persistCredentialInvalidation(t){let r=this.credentialState.sourceConnection;if(!r)return;let o=r.status,i=r.updatedAt,s={id:r.id,ownerMode:r.ownerMode,subjectId:r.subjectId,upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,status:r.status,encryptedAccessToken:r.encryptedAccessToken,encryptedRefreshToken:r.encryptedRefreshToken,scopes:[...r.scopes],expiresAt:r.expiresAt,metadata:r.metadata?{...r.metadata}:void 0};t&&(s.status="reconsent_required",s.encryptedAccessToken=void 0,s.encryptedRefreshToken=void 0,s.scopes=[],s.expiresAt=void 0),s.metadata=this.readStoredOAuthPersistence(r.metadata?.connectedBySubjectId);let c=await this.conditionalUpsertCredential(s,{expectedUpdatedAt:r.updatedAt});c.kind==="persisted"?(this.credentialState.currentConnection=c.connection,this.credentialState.peerAdoption=void 0):c.kind==="missing"?(this.credentialState.currentConnection=void 0,this.credentialState.peerAdoption=void 0):c.connection!==void 0&&(this.credentialState.currentConnection=c.connection,Ir(r,c.connection)&&he(c.connection)==="usable"&&this.connectionSatisfiesRequestedScope(c.connection)?this.adoptPeerConnection(c.connection,"cas_loss"):this.credentialState.peerAdoption=void 0);let a=W();if(a){let u=c.kind==="missing"?void 0:c.connection,p={event:"upstream_oauth_credentials_invalidated",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:u?.id,clearedTokens:t,priorStatus:o,newStatus:u?.status,priorUpdatedAt:i,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,outcome:c.kind};c.kind==="precondition_failed"?a.warn({...p,event:"upstream_oauth_invalidation_precondition_lost"},"Upstream OAuth credential invalidation yielded to concurrent storage state"):t?a.warn(p,"Upstream OAuth credentials invalidated; connection now requires reconsent"):a.debug(p,"Upstream OAuth credential metadata rewritten")}}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var Jw=3e4,Vw=256*1024,Kw=2,Ww="does not support dynamic client registration",Zw=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],Yw=["HTTP 403 Forbidden","Access Denied","permission to access"],Xw=new Set([ue.AccessDenied,ue.InvalidClient,ue.InvalidGrant,ue.InvalidRequest,ue.InvalidScope,ue.InvalidTarget,ue.UnauthorizedClient,ue.UnsupportedGrantType]);function Qw(e){return e instanceof Error&&e.message.includes(Ww)}n(Qw,"isDynamicClientRegistrationUnsupported");function eR(e){return e instanceof Error&&Zw.some(t=>e.message.includes(t))}n(eR,"isProtectedResourceMetadataUnavailable");function tR(e){return e instanceof Error&&Yw.some(t=>e.message.includes(t))}n(tR,"isUpstreamProviderAccessDenied");function rR(e){return e instanceof mt&&Xw.has(e.code)}n(rR,"isStoredConnectionReconsentError");function nR(e){if(e.error instanceof v&&e.error.extensionMembers?.[I]!==void 0)return e.error;if(Qw(e.error))return new v({message:`The authorization server for ${e.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register an OAuth client for the gateway manually before retrying.`,extensionMembers:{[I]:"upstream_client_registration_required"}},{cause:e.error});if(eR(e.error))return new v({message:`The upstream MCP server "${e.upstreamServerId}" does not publish OAuth protected resource metadata at "${e.resourceMetadataUrl}". Configure protectedResourceMetadataUrl to a working metadata document, use a provider-supported legacy client, or contact the provider to approve/allowlist this gateway OAuth client before retrying.`,extensionMembers:{[I]:"upstream_oauth_discovery_unavailable"}},{cause:e.error});if(tR(e.error))return new v({message:`The upstream provider denied access while connecting ${e.upstreamServerId}. Confirm the provider allows this gateway and its OAuth client, then retry.`,extensionMembers:{[I]:"upstream_provider_access_denied"}},{cause:e.error})}n(nR,"mapUpstreamOAuthSetupError");function oR(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(oR,"readOAuthFetchRequest");function iR(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(iR,"responseLooksJson");function sR(e,t){let r=e.headers.get("content-type")??"",o=t.trimStart().toLowerCase();return r.includes("html")||o.startsWith("<!doctype html")||o.startsWith("<html")}n(sR,"responseLooksHtml");function aR(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new v({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[I]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[ct]:e.response.status,[yr]:r,[dt]:e.request.url.toString(),[Sr]:e.body}})}n(aR,"throwUpstreamHtmlError");function cR(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return{};let r=t;return{error:typeof r.error=="string"?r.error:void 0,errorDescription:typeof r.error_description=="string"?r.error_description:void 0}}catch{return{}}}n(cR,"readUpstreamOAuthErrorBody");function dR(e){let{error:t,errorDescription:r}=cR(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.request.method??"GET",host:te(e.request.url),path:e.request.url.pathname,status:e.response.status,oauthError:t,oauthErrorDescription:r?.slice(0,256)},"Upstream OAuth HTTP request returned an error response")}n(dR,"logUpstreamOAuthHttpError");function gm(e){return async(t,r)=>{let o=oR(t),i=W(),s=Date.now(),c=await qp(t,r,{maxRedirects:Kw,maxResponseBytes:Vw,problemCode:"upstream_token_exchange_failed",timeoutMs:Jw}),a=await c.clone().text();if(i?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:o.method??"GET",host:te(o.url),path:o.url.pathname,status:c.status,durationMs:Date.now()-s,responseChars:a.length},"Upstream OAuth HTTP request completed"),c.ok||dR({log:i,upstreamServerId:e,request:o,response:c,body:a}),!c.ok&&sR(c,a)&&aR({upstreamServerId:e,request:o,response:c,body:a}),!iR(c,a))return c;try{JSON.parse(a)}catch(u){throw new v({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[I]:"upstream_token_exchange_failed"}},{cause:u})}return c}}n(gm,"createUpstreamOAuthFetch");function ym(e){W()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:te(e.serverUrl),resourceMetadataHost:te(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}n(ym,"logUpstreamOAuthFlowStarted");function Sm(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=te(e.serverUrl);r!==void 0&&(t.serverHost=r);let o=e.error instanceof v?e.error.extensionMembers?.[I]:void 0;typeof o=="string"&&(t.code=o),pe(t,"error",e.error),W()?.warn(t,"Upstream OAuth flow failed before a connection was established")}n(Sm,"logUpstreamOAuthFlowFailed");function _m(e,t){return e.configuredAuthorizationScope??t.requestedScope}n(_m,"readAuthorizationRequestScope");async function wm(e,t){e.applyChallengeScope(t.requestedScope),ym({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:gm(t.upstreamServerId)},o=_m(e,t);return o!==void 0&&(r.scope=o),await Cs(e,r)}catch(r){Sm({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=nR({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(wm,"runUpstreamOAuth");async function uR(e,t){e.applyChallengeScope(t.requestedScope),ym({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:gm(t.upstreamServerId)};t.iss!==void 0&&(r.iss=t.iss);let o=_m(e,t);o!==void 0&&(r.scope=o);try{return await Cs(e,r)}catch(i){throw Sm({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:i}),i}}n(uR,"exchangeUpstreamAuthorizationCode");async function fm(e){let t=e.provider.readUsablePeerAdoption(e.requestedScope);if(t!==void 0)return await e.provider.adoptConnectionForDirectResolution(t,"cas_loss"),!0;let[r]=await N().batchGetUpstreamConnections([{owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}]);return r===void 0||he(r)!=="usable"||!Ir(e.connection,r)||!e.provider.connectionSatisfiesRequestedScope(r,e.requestedScope)?!1:(await e.provider.adoptConnectionForDirectResolution(r,"boundary_reread"),!0)}n(fm,"adoptPeerCredentialAtResolutionBoundary");async function Rm(e,t){let r=await wm(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new v({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}}):new v({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}})}n(Rm,"requireUpstreamAuthorizationRedirect");async function bm(e){let t=he(e.connection),r=!!e.forceRefresh,o=!r&&t==="usable"&&e.connection!==void 0&&e.provider.connectionSatisfiesRequestedScope(e.connection,e.requestedScope),i=W(),s=i?await Cr({owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}):void 0;if(i?.debug({event:"upstream_oauth_refresh_decision",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,ownerMode:e.target.owner.mode,connectionFingerprint:s,connectionId:e.connection?.id,accessTokenState:t,forceRefresh:r,willRefresh:!o,expiresAt:e.connection?.expiresAt,connectionUpdatedAt:e.connection?.updatedAt},o?"Reusing stored upstream access token":"Refreshing upstream credential"),o)return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let c;try{c=await wm(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(a){if(e.connection===void 0||!rR(a))throw a;return i?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:a.code,connectionFingerprint:s,connectionId:e.connection.id,rejectedRefreshTokenFingerprint:e.provider.usedRefreshTokenFingerprint,connectionUpdatedAt:e.connection.updatedAt,connectionExpiresAt:e.connection.expiresAt},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),await fm({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope})?{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}:{kind:"connect_required",payload:await Bs({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}if(c==="AUTHORIZED"){let a=e.provider.readUsablePeerAdoption(e.requestedScope);return a!==void 0&&await e.provider.adoptConnectionForDirectResolution(a,"cas_loss"),!e.provider.tokenWriteWasPersisted&&a===void 0?{kind:"connect_required",payload:await Bs({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:void 0,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}:{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}}if(c!=="REDIRECT")throw new v({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${c}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new v({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}});return await fm({provider:e.provider,connection:e.connection,target:e.target,requestedScope:e.requestedScope})?{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}}:{kind:"connect_required",payload:await Bs({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}n(bm,"authorizeUpstreamOAuthSession");async function lR(e){let t=await si(e.stateToken),r=await N().consumeUpstreamOAuthState({id:t.id,now:$(new Date)}),o=pR(r);return mR({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),hR(o),o}n(lR,"consumeStoredCallbackState");function pR(e){switch(e.kind){case"consumed":throw new v({message:"OAuth state has already been used",extensionMembers:{[I]:"oauth_state_reused"}});case"missing":throw new v({message:"OAuth state is missing or expired",extensionMembers:{[I]:"oauth_state_expired"}});case"available":return e.record}}n(pR,"readConsumedCallbackState");function mR(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.operationId===e.signedState.operationId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw new v({message:"OAuth callback did not match the initiating request",extensionMembers:{[I]:"oauth_callback_mismatch"}})}n(mR,"assertStoredCallbackStateMatches");function hR(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new v({message:"OAuth state has expired",extensionMembers:{[I]:"oauth_state_expired"}})}n(hR,"assertStoredCallbackStateFresh");async function Bs(e){if(e.owner.mode==="shared"){let r={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,requiresReconsent:!!e.connection};return e.connection!==void 0&&(r.connectionId=e.connection.id),tm(r)}let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,subject:"tool",requiresReconsent:!!e.connection,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return e.connection!==void 0&&(t.connectionId=e.connection.id),ai(t)}n(Bs,"buildOAuthConnectRequiredResponse");async function vm(e){let t=await lR({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=No(t),[o]=await N().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),i={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};o!==void 0&&(i.connection=o);let s=new _t(i),c=await uR(s,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,...e.iss===void 0?{}:{iss:e.iss},resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(c==="AUTHORIZED"){let a=s.readUsablePeerAdoption();if(a!==void 0&&await s.adoptConnectionForDirectResolution(a,"cas_loss"),!s.tokenWriteWasPersisted&&a===void 0)throw new v({message:`OAuth callback storage changed while connecting ${e.upstreamServerId}. Restart the connection flow and try again.`,extensionMembers:{[I]:"upstream_token_exchange_failed"}});return t}throw c!=="REDIRECT"?new v({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${c}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}}):new v({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[I]:"upstream_token_exchange_failed"}})}n(vm,"finishUpstreamOAuthCallback");import{importPKCS8 as fR,SignJWT as gR}from"jose";var Im=1e4,Tm=64*1024,km=2,yR=300,qe=l.string().min(1),SR=l.object({access_token:qe,issued_token_type:l.literal(Bi),token_type:l.string().optional(),expires_in:l.number().int().positive().optional(),scope:qe.optional()}).passthrough(),_R=l.object({id_token:qe,token_type:qe.optional(),expires_in:l.number().int().positive().optional(),refresh_token:qe.optional(),scope:qe.optional()}).passthrough(),wR=l.object({access_token:qe,token_type:qe,expires_in:l.number().int().positive().optional(),scope:qe.optional(),resource:qe.optional(),refresh_token:qe.optional()}).passthrough();function Cm(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(Cm,"formEncodeClientCredential");function RR(e){return e.replaceAll("\\n",`
26
26
  `)}n(RR,"normalizePem");async function bR(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??yR,o=await fR(RR(e.clientAuth.privateKeyPem),t),i={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new gR({jti:crypto.randomUUID()}).setProtectedHeader(i).setIssuer(e.clientAuth.clientId).setSubject(e.clientAuth.clientId).setAudience(e.clientAuth.audience??e.tokenUrl).setIssuedAt().setExpirationTime(`${r}s`).sign(o)}n(bR,"createPrivateKeyJwtClientAssertion");async function vR(e){switch(e.clientAuth.method){case"client_secret_post":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_secret",e.clientAuth.clientSecret);return;case"client_secret_basic":{let t=Cm(e.clientAuth.clientId),r=Cm(e.clientAuth.clientSecret);e.headers.authorization=`Basic ${btoa(`${t}:${r}`)}`;return}case"private_key_jwt":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_assertion_type",$o),e.form.set("client_assertion",await bR({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}n(vR,"appendClientAuthentication");async function Fs(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await vR({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}n(Fs,"buildFormRequest");function Pm(e){return(t,r)=>ii(t,r,{context:e,maxRedirects:km,maxResponseBytes:Tm,problemCode:"upstream_token_exchange_failed",timeoutMs:Im})}n(Pm,"defaultIdpFetchJson");function CR(e){return(t,r)=>zp(t,r,{context:e,maxRedirects:km,maxResponseBytes:Tm,problemCode:"upstream_token_exchange_failed",timeoutMs:Im})}n(CR,"defaultResourceAsFetchJson");function di(e){let t={[I]:e.code,[dt]:e.tokenUrl};return e.response!==void 0&&(t[ct]=e.response.status),new v({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}n(di,"runtimeError");function Gs(e){if(!e.response.ok)throw di({code:"upstream_token_exchange_failed",message:(()=>{switch(e.stage){case"idp_refresh_token":return"IdP refresh-token grant failed while renewing the upstream ID-JAG subject token.";case"idp_token_exchange":return"IdP token exchange failed while requesting an upstream ID-JAG.";case"resource_as_jwt_bearer":return"Upstream Resource AS rejected the ID-JAG JWT-bearer exchange."}})(),tokenUrl:e.tokenUrl,response:e.response})}n(Gs,"assertTokenEndpointSucceeded");function IR(e){let t=_R.safeParse(e.json);if(!t.success)throw di({code:"upstream_token_response_invalid",message:"IdP refresh-token grant returned an invalid subject-token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={idToken:t.data.id_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),t.data.scope!==void 0&&(r.scope=t.data.scope),r}n(IR,"parseIdpRefreshTokenResponse");function TR(e){let t=SR.safeParse(e.json);if(!t.success)throw di({code:"upstream_token_response_invalid",message:"IdP token exchange returned an invalid ID-JAG response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={assertion:t.data.access_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),r}n(TR,"parseIdJagTokenExchangeResponse");function kR(e){let t=wR.safeParse(e.json);if(!t.success)throw di({code:"upstream_token_response_invalid",message:"Upstream Resource AS returned an invalid JWT-bearer token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={accessToken:t.data.access_token,tokenType:t.data.token_type};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),t.data.resource!==void 0&&(r.resource=t.data.resource),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),r}n(kR,"parseAccessTokenResponse");async function Am(e){let t=new URLSearchParams({grant_type:jo,requested_token_type:Bi,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,audience:e.audience});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope),e.authorizationDetails!==void 0&&t.set("authorization_details",JSON.stringify(e.authorizationDetails));let r=e.fetchJson??Pm(e.context),{response:o,json:i}=await r(e.idp.tokenUrl,await Fs({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return Gs({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),TR({json:i,response:o,tokenUrl:e.idp.tokenUrl})}n(Am,"requestIdJag");async function Em(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??Pm(e.context),{response:o,json:i}=await r(e.idp.tokenUrl,await Fs({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return Gs({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),IR({json:i,response:o,tokenUrl:e.idp.tokenUrl})}n(Em,"refreshIdpSubjectToken");async function xm(e){let t=new URLSearchParams({grant_type:lt,assertion:e.assertion});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope);let r=e.fetchJson??CR(e.context),{response:o,json:i}=await r(e.resourceAs.tokenUrl,await Fs({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return Gs({response:o,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),kR({json:i,response:o,tokenUrl:e.resourceAs.tokenUrl})}n(xm,"exchangeIdJagForAccessToken");function PR(e){return he(e)==="usable"}n(PR,"hasUsableAccessToken");function AR(e){if(e.tokenType.toLowerCase()!=="bearer")throw new v({message:"Upstream Resource AS returned a token type the MCP gateway cannot send as a bearer token.",extensionMembers:{[I]:"upstream_token_response_invalid"}})}n(AR,"assertBearerToken");function Um(e,t){if(t===Rr)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}n(Um,"hasExpiredSubjectToken");async function ER(e){let t=await Ye(e.encryptedSubjectToken);if(e.subjectTokenType!==Rr)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await Em({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});if(r.refreshToken===void 0)return{connection:e.connection,subjectToken:r.idToken,subjectTokenType:jn};let o=await N().upsertUpstreamConnection({id:e.connection.id,ownerMode:e.connection.ownerMode,subjectId:e.connection.subjectId,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,status:"active",encryptedAccessToken:e.connection.encryptedAccessToken,encryptedRefreshToken:e.connection.encryptedRefreshToken,scopes:e.connection.scopes,expiresAt:e.connection.expiresAt,metadata:{...e.connection.metadata??{},encryptedIdpSubjectToken:await Ze(r.refreshToken),idpSubjectTokenType:Rr,idpSubjectTokenExpiresAt:void 0}});return W()?.info({event:"upstream_id_jag_subject_token_rotated",upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,connectionFingerprint:e.connectionFingerprint,connectionId:o.id,priorStatus:e.connection.status,priorUpdatedAt:e.connection.updatedAt,usedSubjectRefreshTokenFingerprint:await Lt(t),newSubjectRefreshTokenFingerprint:await Lt(r.refreshToken)},"Upstream ID-JAG IdP subject refresh token rotated and persisted"),{connection:o,subjectToken:r.idToken,subjectTokenType:jn}}n(ER,"resolveIdJagSubjectToken");async function Om(e){let t="preloadedConnection"in e?e.preloadedConnection:(await N().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0],r=he(t),o=!!e.forceRefresh,i=!o&&r==="usable",s=W(),c=s?await Cr({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}):void 0;if(s?.debug({event:"upstream_id_jag_auth_decision",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,ownerMode:e.owner.mode,connectionFingerprint:c,connectionId:t?.id,accessTokenState:r,forceRefresh:o,willMint:!i,expiresAt:t?.expiresAt,connectionUpdatedAt:t?.updatedAt},i?"Reusing stored upstream ID-JAG access token":"Minting upstream ID-JAG access token"),!e.forceRefresh&&PR(t))return{kind:"authorized",credential:{type:"bearer_token",token:await Ye(t.encryptedAccessToken)}};let a=t?.metadata?.encryptedIdpSubjectToken,u=t?.metadata?.idpSubjectTokenType;if(t?.status!=="active"||a===void 0||u===void 0||Um(t,u))return s?.debug({event:"upstream_id_jag_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:c,connectionId:t?.id,status:t?.status??"not_connected",hasSubjectToken:a!==void 0,subjectTokenType:u,subjectTokenExpired:u!==void 0&&Um(t,u)},"Upstream ID-JAG requires an admin subject-token binding"),{kind:"connect_required",payload:{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,message:`An IdP subject-token binding is required for ${e.upstreamDisplayName} before this tool can use XAA / ID-JAG.`,nextAction:"admin_setup_required"}};let p=gt(e.upstreamServerId),h=xp(e.upstreamServerId,e.authProfileId),f=h.resourceAs.resource??p.transport.baseUrl,y=e.requestedScope??(h.scopes.length===0?void 0:h.scopes.join(h.scopeDelimiter)),S=await ER({connection:t,connectionFingerprint:c,encryptedSubjectToken:a,subjectTokenType:u,idp:{tokenUrl:h.idp.tokenUrl},clientAuth:h.idp.clientAuth,context:e.context}),k=await Am({idp:{tokenUrl:h.idp.tokenUrl},subjectToken:S.subjectToken,subjectTokenType:S.subjectTokenType,audience:h.resourceAs.audience,resource:f,scope:y,clientAuth:h.idp.clientAuth,context:e.context}),w=k.scope??y,C=await xm({resourceAs:{tokenUrl:h.resourceAs.tokenUrl},assertion:k.assertion,resource:f,scope:w,clientAuth:h.resourceAs.clientAuth,context:e.context});if(AR(C),t!==void 0){let O=(C.scope??w)?.split(/[,\s]+/).filter(Boolean)??[],L=C.expiresIn===void 0?void 0:$(new Date(Date.now()+C.expiresIn*1e3)),F=await N().upsertUpstreamConnection({id:S.connection.id,ownerMode:S.connection.ownerMode,subjectId:S.connection.subjectId,upstreamServerId:S.connection.upstreamServerId,authProfileId:S.connection.authProfileId,status:"active",encryptedAccessToken:await Ze(C.accessToken),encryptedRefreshToken:S.connection.encryptedRefreshToken,scopes:O,expiresAt:L,metadata:S.connection.metadata});s?.info({event:"upstream_id_jag_access_token_persisted",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:c,connectionId:F.id,priorStatus:S.connection.status,priorUpdatedAt:S.connection.updatedAt,scopeCount:O.length,expiresAt:L},"Upstream ID-JAG access token persisted; connection is active")}return{kind:"authorized",credential:{type:"bearer_token",token:C.accessToken}}}n(Om,"authorizeUpstreamIdJagRequest");var ui=new Map;function xR(e){return[...new Set(e?.split(/[,\s]+/).filter(Boolean)??[])].sort().join(" ")}n(xR,"normalizeRefreshFlightScope");function UR(e){return ci(new URL(e.callbackPath,Y(e.requestUrl,e.requestHeaders))).toString()}n(UR,"buildGatewayOAuthRedirectUri");async function Js(e){let t=gt(e.upstreamServerId),r=br(e.upstreamServerId,e.authProfileId),o=UR({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),i="preloadedConnection"in e?e.preloadedConnection:(await N().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:i,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,returnTo:e.returnTo},redirectUri:o,returnOrigin:Y(e.request.url,e.request.headers)}}}n(Js,"prepareUpstreamOAuthRequest");async function qm(e){let t=await Js(e),r=new _t({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Rm(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(qm,"startUpstreamConnect");async function zm(e){let t=await Js(e),r=new _t({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),o=n(()=>bm({target:e,provider:r,connection:t.connection,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl}),"runSession");if(!e.forceRefresh&&t.connection!==void 0&&he(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return o();let i=ul({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}),s=JSON.stringify([i,xR(r.configuredAuthorizationScope??e.requestedScope)]),c=ui.get(s);if(c!==void 0){W()?.debug({event:"upstream_oauth_refresh_single_flight_coalesced",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,ownerMode:e.owner.mode},"Upstream OAuth refresh joined an isolate-local single-flight");let p=await c;if(p.kind==="usable"&&r.connectionSatisfiesRequestedScope(p.connection,e.requestedScope))return await r.adoptConnectionForDirectResolution(p.connection,"single_flight"),{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:r}};let{preloadedConnection:h,...f}=e;if(t=await Js(f),r=new _t({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}}),!e.forceRefresh&&t.connection!==void 0&&he(t.connection)==="usable"&&r.connectionSatisfiesRequestedScope(t.connection,e.requestedScope))return o()}let a=o(),u;return u=a.then(()=>{let p=r.currentConnection;return p!==void 0&&he(p)==="usable"?{kind:"usable",connection:p}:{kind:"unresolved"}}).catch(()=>({kind:"unresolved"})).finally(()=>{ui.get(s)===u&&ui.delete(s)}),ui.set(s,u),a}n(zm,"authorizeUpstreamRequest");async function kr(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return zm({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo});case"id-jag":return Om({request:e.request,context:e.context,authMode:t.authMode,ownerMode:t.ownerMode,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,upstreamDisplayName:t.upstreamDisplayName,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo})}let r=t;throw new Pe(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}n(kr,"resolveUpstreamCredentialForRoute");async function Mm(e){if(e.connectRequest.authMode==="id-jag")throw new Pe(`Upstream server ${e.connectRequest.upstreamServerId} uses XAA / ID-JAG and does not support browser OAuth connection flows.`);let t=await qm({request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,operationId:e.connectRequest.operationId,returnTo:e.connectRequest.returnTo});return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,operationId:e.connectRequest.operationId}}n(Mm,"startUpstreamConnectForRequest");async function Nm(e){let r=(await si(e.callbackRequest.state)).authProfileId;if(ni({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}).mode==="id-jag")throw new Pe(`Upstream server ${e.callbackRequest.upstreamServerId} uses XAA / ID-JAG and does not support OAuth callbacks.`);return vm({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,...e.callbackRequest.iss===void 0?{}:{iss:e.callbackRequest.iss},upstreamServerConfig:gt(e.callbackRequest.upstreamServerId)})}n(Nm,"finishUpstreamCallbackForRequest");function OR(e){return{upstreamServerId:e.connection.upstreamServerId,operationId:e.operationId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(OR,"buildRouteAuthBaseFromConnection");function jm(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:Du(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(jm,"buildRouteAuthBaseFromPolicyOptions");function li(e,t){let o=ye().byOperationId.get(t);if(!o)throw new K(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new K(`MCP route "${t}" does not declare an MCP token exchange policy. Add one before starting an upstream connection flow.`);if(o.connection.upstreamServerId!==e)throw new K(`MCP route "${t}" does not bind upstream "${e}". Check the route's MCP upstream policies and bind the upstream before starting an upstream connection flow.`);return OR({connection:o.connection,operationId:t})}n(li,"resolveRouteAuthBase");function Vs(e,t){switch(e){case"user":return _r(t);case"shared":return ju()}}n(Vs,"buildOwnerForSubject");function Pr(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:Vs("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:Vs("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:Vs("user",t),initiatedBySubjectId:t}}}n(Pr,"resolveRouteAuthForSubject");var qR=A.InvalidRequest,zR=new Set(["connection","keep-alive","proxy-connection","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]);function MR(e,t){return{credentialType:e.type,forceRefresh:t}}n(MR,"buildCredentialResolvedAttributes");function NR(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(NR,"connectRequiredReasonCode");function $m(e){J(e.context,{eventType:H.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:MR(e.credential,e.forceRefresh===!0)})}n($m,"emitCredentialResolvedAnalyticsEvent");function Dm(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(J(e.context,{eventType:H.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"connect_required",reasonClass:"auth",attributes:t}),e.payload.state==="reconsent_required"){J(e.context,{eventType:H.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}J(e.context,{eventType:H.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:NR(e.payload.state),reasonClass:"auth",attributes:t})}n(Dm,"emitCredentialMissingAnalyticsEvents");function jR(e){let t=e.route.raw();return Mo.parse(t?.operationId)}n(jR,"readOperationId");async function $R(e,t,r,o){let i=await kr({request:e,context:o,routeAuth:t});if(i.kind==="connect_required")return Dm({context:o,payload:i.payload,routeBinding:t}),o.log.info({event:"mcp_upstream_connect_required",upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId},"MCP upstream proxy: upstream connection required"),{kind:"connect_required",payload:i.payload};let s=i.credential;if($m({context:o,credential:s,routeBinding:t}),s.type==="bearer_token")return{kind:"headers",headers:[["authorization",`Bearer ${s.token}`]]};let c=await s.provider.tokens();return c?{kind:"headers",headers:[["authorization",`${c.token_type??"Bearer"} ${c.access_token}`]]}:(o.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:t.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens"),Response.json({error:"no_upstream_tokens"},{status:401}))}n($R,"buildCredentialHeaders");var DR=new Set(["authorization","cookie","cookie2"]);function LR(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return t&&typeof t=="object"&&!Array.isArray(t)&&"method"in t&&typeof t.method=="string"?t.method:void 0}catch{return}}n(LR,"readJsonRequestMethod");function HR(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(HR,"isJsonResponse");function Ks(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Ks,"isRecord");function BR(e){return Array.isArray(e)&&e.length>0}n(BR,"hasIconList");function FR(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=ri(qu(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(FR,"readFallbackServerIcons");function GR(e){if(!Ks(e.body))return e.body;let t=e.body.result;if(!Ks(t))return e.body;let r=t.serverInfo;return!Ks(r)||BR(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}n(GR,"addMissingServerIcons");function JR(e,t){let r=Lm(e);for(let o of DR)r.delete(o);for(let[o,i]of t)r.set(o,i);return new xa(e,{headers:r})}n(JR,"applyUpstreamHeaders");var VR=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function KR(e){let t=e.get("connection");return t===null?[]:t.split(",").map(r=>r.trim()).filter(r=>VR.test(r))}n(KR,"connectionNominatedHeaderNames");function Lm(e){let t=new Headers(e.headers);for(let r of KR(t))t.delete(r);for(let r of zR)t.delete(r);return t}n(Lm,"buildProxyHeaders");async function WR(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(WR,"readRetryBody");function Hm(e,t){let r=t.authUrl===void 0?void 0:vp({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(Xo({id:bp(e),error:{code:r?.code??qR,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(Hm,"connectRequiredJsonRpcResponse");async function ZR(e){let{scope:t}=yp(e.upstreamResponse),r=await kr({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="connect_required")return Dm({context:e.context,payload:r.payload,routeBinding:e.routeAuth,forceRefresh:!0}),{kind:"connect_required",payload:r.payload};let o=new Headers(e.headers),i=r.credential;if($m({context:e.context,credential:i,routeBinding:e.routeAuth,forceRefresh:!0}),i.type==="bearer_token")return o.set("authorization",`Bearer ${i.token}`),{kind:"headers",headers:o};let s=await i.provider.tokens();return s?(o.set("authorization",`${s.token_type??"Bearer"} ${s.access_token}`),{kind:"headers",headers:o}):(e.context.log.warn({event:"mcp_upstream_no_tokens_after_refresh",upstreamServerId:e.routeAuth.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens after refresh"),{kind:"response",response:Response.json({error:"no_upstream_tokens"},{status:401})})}n(ZR,"applyRefreshedCredentialHeaders");function YR(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await ZR({request:e.request,context:e.context,headers:Lm(r),routeAuth:e.routeAuth,upstreamResponse:t});if(o.kind==="connect_required")return Hm(e.requestBody,o.payload);if(o.kind==="response")return o.response;let i=zu({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return Co.fetch(i.url,i.init)})}n(YR,"installUpstreamAuthRetryHook");function XR(e){if(LR(e.requestBody)!=="initialize")return;let t=FR({connection:e.connection,context:e.context});t===void 0||t.length===0||e.context.addResponseSendingHook(async r=>{if(!HR(r))return r;let o;try{o=await r.clone().json()}catch{return r}let i=GR({body:o,icons:t});if(i===o)return r;let s=new Headers(r.headers);return s.delete("content-length"),new Response(JSON.stringify(i),{status:r.status,statusText:r.statusText,headers:s})})}n(XR,"installInitializeIconHook");async function Ws(e,t,r){let o=jR(t),i=await WR(e),s=jm({connection:r,operationId:o}),c=$t(e.user,e.url,e.headers);t.log.setLogProperties?.({requestId:t.requestId}),Ju(t,c);let a=Pr(s,c.subjectId),u=await $R(e,a,r,t);if(!(u instanceof Response)&&u.kind==="connect_required")return Hm(i,u.payload);if(u instanceof Response)return u;let p=JR(e,u.headers);return YR({request:p,context:t,requestBody:i,routeAuth:a}),XR({context:t,requestBody:i,connection:r}),p}n(Ws,"mcpTokenExchangePolicy");var Zs=class extends Io{static{n(this,"McpTokenExchangeInboundPolicy")}static policyType="mcp-token-exchange";#e;constructor(t,r){let o=Lu(t,r);super(o,r),this.#e=o}async handler(t,r){return Ws(t,r,this.#e)}};var Bm=Symbol("Html");function QR(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}n(QR,"escapeHtml");function eb(e){return e===null||typeof e!="object"?!1:e[Bm]===!0}n(eb,"isHtml");function Fm(e){return e==null||e===!1?"":Array.isArray(e)?e.map(Fm).join(""):eb(e)?e.value:QR(String(e))}n(Fm,"renderValue");function Xe(e){return{[Bm]:!0,value:e}}n(Xe,"trustedHtml");var Ae=Xe("");function B(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=Fm(t[o]),r+=e[o+1]??"";return Xe(r)}n(B,"html");function Ar(e){return e.value}n(Ar,"renderHtml");function Gm(e){return B`<p class="card__description">${e.detail}</p>${e.guidance} ${e.technicalDetails} ${e.action}`}n(Gm,"renderBrowserErrorPage");var Er=Xe('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;justify-content:center;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;min-height:40px;padding:8px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.reconnect-action{align-items:center;margin-right:auto;display:inline-flex;position:relative}.reconnect-button{gap:7px}.tooltip{width:16px;height:16px;color:var(--accent);background:color-mix(in srgb,var(--accent)8%,transparent);cursor:help;border:1.5px solid;border-radius:50%;justify-content:center;align-items:center;font-size:10.5px;font-weight:700;line-height:1;display:inline-flex;position:relative}.tooltip:after{content:attr(aria-label);z-index:10;border-radius:var(--radius-sm);background:var(--accent);width:280px;max-width:min(280px,100vw - 48px);color:var(--accent-text);box-shadow:var(--shadow);text-align:left;white-space:normal;opacity:0;pointer-events:none;padding:12px 14px;font-size:13px;font-weight:600;line-height:1.45;transition:opacity .12s;position:absolute;bottom:calc(100% + 12px);left:50%;transform:translate(-50%)}.tooltip:before{content:"";z-index:11;border-left:7px solid #0000;border-right:7px solid #0000;border-top:8px solid var(--accent);opacity:0;pointer-events:none;transition:opacity .12s;position:absolute;bottom:calc(100% + 5px);left:50%;transform:translate(-50%)}.tooltip:hover:after,.tooltip:hover:before,.tooltip:focus-visible:after,.tooltip:focus-visible:before{opacity:1}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}@media (width<=480px){body{padding:0}.card{box-shadow:none;border-left:0;border-right:0;border-radius:0;min-height:100dvh}.card__head{padding:24px 20px 16px}.card__body{padding:16px 20px}.card__footer{flex-direction:column-reverse;align-items:stretch;padding:14px 20px}.card__footer .button{width:100%}.reconnect-action{justify-content:center;width:100%;margin-right:0}.reconnect-action .button{flex:1}.tooltip:after{left:auto;right:0;transform:none}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function xr(e){return B`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" href="${e.iconHref}" /><style>
27
27
  ${e.styles}
28
28
  </style></head><body><main class="card"><header class="card__head">${e.headerIcon}<h1 class="card__title">${e.heading}</h1>${e.subhead}</header><div class="card__body">${e.body}</div>${e.footer}</main></body></html>`}n(xr,"renderShell");var tb="text/html; charset=utf-8";function Ur(e){try{return new URL(e).host}catch{return""}}n(Ur,"safeHostFromUrl");function He(e){let t=nb(e.kind??"authorization_failed"),r=rb(e);return new Response(Ar(xr({title:e.title??t.title,iconHref:"",styles:Er,headerIcon:Ae,heading:e.title??t.title,subhead:"",body:Gm({detail:e.detail,guidance:B`<p class="card__description">${t.guidance}</p>`,technicalDetails:cb({diagnostic:r,upstreamHtml:e.upstreamHtml}),action:sb(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":tb,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(He,"browserErrorPageResponse");function rb(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??ob(t),timestamp:e.diagnostic?.timestamp??new Date().toISOString(),...e.requestId===void 0&&e.diagnostic?.requestId===void 0?{}:{requestId:e.diagnostic?.requestId??e.requestId},...e.diagnostic?.operationId===void 0?{}:{operationId:e.diagnostic.operationId},...e.diagnostic?.routePath===void 0?{}:{routePath:e.diagnostic.routePath},...e.diagnostic?.upstreamServerId===void 0?{}:{upstreamServerId:e.diagnostic.upstreamServerId},...e.diagnostic?.authProfileId===void 0?{}:{authProfileId:e.diagnostic.authProfileId},...e.diagnostic?.upstreamUrl===void 0?{}:{upstreamUrl:e.diagnostic.upstreamUrl},...e.diagnostic?.metadataUrl===void 0?{}:{metadataUrl:e.diagnostic.metadataUrl},...e.diagnostic?.httpStatus===void 0?{}:{httpStatus:e.diagnostic.httpStatus},...e.diagnostic?.contentType===void 0?{}:{contentType:e.diagnostic.contentType},...e.diagnostic?.providerError===void 0?{}:{providerError:e.diagnostic.providerError},...e.diagnostic?.providerErrorDescription===void 0?{}:{providerErrorDescription:e.diagnostic.providerErrorDescription},suggestedFix:e.diagnostic?.suggestedFix??ib(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}n(rb,"buildBrowserErrorDiagnostic");function nb(e){switch(e){case"session_expired":return{title:"Authorization expired",guidance:"Return to your MCP client and reconnect. Expired authorization requests cannot be resumed."};case"access_denied":return{title:"Authorization canceled",guidance:"Return to your MCP client to retry if you want to grant access."};case"configuration_error":return{title:"Configuration needs attention",guidance:"Contact your workspace admin with this error code. The gateway or upstream configuration must be fixed before retrying."};case"connection_failed":return{title:"Connection failed",guidance:"Return to your MCP client and reconnect this upstream. If this keeps happening, contact your gateway administrator with this error code."};case"invalid_request":return{title:"Authorization request invalid",guidance:"Return to your MCP client and try connecting again. If this keeps happening, the client request may need to be fixed."};case"admin_required":return{title:"Admin setup required",guidance:"Contact your workspace admin with this error code. This connection cannot be completed until setup is finished."};case"internal_error":return{title:"Gateway error",guidance:"Try again later from your MCP client. If this keeps happening, contact your gateway administrator with this error code."};case"authorization_failed":return{title:"Authorization failed",guidance:"Return to your MCP client and start authorization again. If this keeps happening, contact your gateway administrator with this error code."}}}n(nb,"readBrowserErrorPagePresentation");function ob(e){switch(e){case"upstream_oauth_discovery_unavailable":return"upstream_oauth_discovery";case"upstream_client_registration_required":return"upstream_oauth_client_registration";case"upstream_provider_access_denied":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"upstream_token_exchange";case"provider_access_denied":return"upstream_oauth_callback";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"upstream_oauth_state";case"browser_login_verification_failed":return"downstream_browser_login";case"authentication_required":case"identity_context_missing":return"downstream_auth";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"gateway_configuration";case"server_error":case"internal_server_error":return"gateway_internal";default:return"gateway_request"}}n(ob,"readBrowserErrorStage");function ib(e){switch(e){case"upstream_oauth_discovery_unavailable":return"Confirm the upstream MCP URL and OAuth protected resource metadata. If the provider requires approval, configure the provider app or contact the provider.";case"upstream_client_registration_required":return"Register an OAuth client with the upstream provider, then configure the gateway to use that client before retrying.";case"upstream_provider_access_denied":return"Confirm the provider allows this gateway, OAuth client, and upstream MCP URL, then retry the connection.";case"upstream_token_exchange_failed":return"Retry the connection. If it repeats, verify the upstream OAuth client, redirect URI, token endpoint, and provider allowlist.";case"upstream_token_response_invalid":return"Verify the upstream token endpoint returns a valid OAuth token response for this gateway client.";case"provider_access_denied":return"Start the connection again if access was denied by mistake. Otherwise, grant the requested upstream provider access.";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"Start a new connection from the MCP client. The previous browser authorization request cannot be resumed.";case"browser_login_verification_failed":return"Retry the browser login flow. If it repeats, verify the downstream login callback configuration.";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"Check the MCP route, upstream server, and auth profile entries in the gateway configuration.";case"authentication_required":case"identity_context_missing":return"Verify the normal Zuplo auth policy runs before the MCP gateway policy and sets request.user.";case"server_error":case"internal_server_error":return"Retry later and check gateway logs with the request ID.";default:return"Check the gateway configuration and request details associated with this error code."}}n(ib,"readBrowserErrorSuggestedFix");function sb(e){return e===void 0?Ae:B`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(sb,"renderAction");function ab(e){let t=[["Error code",e.code],["Stage",e.stage],["Request ID",e.requestId],["Time",e.timestamp],["Gateway route",e.routePath],["Operation ID",e.operationId],["Upstream",e.upstreamServerId],["Auth profile",e.authProfileId],["Upstream URL",e.upstreamUrl],["Metadata URL",e.metadataUrl],["HTTP status",e.httpStatus],["Content type",e.contentType],["Provider error",e.providerError],["Provider error description",e.providerErrorDescription],["Suggested fix",e.suggestedFix],["Underlying error",e.underlyingError]].filter(r=>r[1]!==void 0).map(([r,o])=>`${r}: ${o}`).join(`