lurqrun 0.1.6 → 0.1.7

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 (206) hide show
  1. package/README.md +18 -10
  2. package/dist/auditHandler-JCOJSUYW.js +23 -0
  3. package/dist/bin/lurq.js +3090 -23306
  4. package/dist/browserAuth-B6G27USY.js +95 -0
  5. package/dist/cache-DKI34SVS.js +12 -0
  6. package/dist/check-2FDGUOV7.js +192 -0
  7. package/dist/checkUpgrade-F2WESBPM.js +103 -0
  8. package/dist/chunk-2VMOWSRY.js +300 -0
  9. package/dist/chunk-3GHJR7XR.js +2049 -0
  10. package/dist/chunk-3N3Q3DSW.js +214 -0
  11. package/dist/chunk-4ESO33J6.js +34 -0
  12. package/dist/chunk-4F7ZESPO.js +132 -0
  13. package/dist/chunk-4KCPOMG6.js +68 -0
  14. package/dist/chunk-4ZYCIMY4.js +155 -0
  15. package/dist/chunk-63MUJNZL.js +318 -0
  16. package/dist/chunk-6AAEVQ7I.js +6336 -0
  17. package/dist/chunk-6EQ3ARXA.js +304 -0
  18. package/dist/chunk-6L3U7DZ5.js +23 -0
  19. package/dist/chunk-AHBP533R.js +220 -0
  20. package/dist/chunk-B43LCXBM.js +223 -0
  21. package/dist/chunk-BCANRN5B.js +33 -0
  22. package/dist/chunk-BUALU27S.js +123 -0
  23. package/dist/chunk-BULZAX2U.js +1554 -0
  24. package/dist/chunk-BV32UNLL.js +154 -0
  25. package/dist/chunk-C6GLE626.js +160 -0
  26. package/dist/chunk-CIDWNUAP.js +145 -0
  27. package/dist/chunk-CUP36ND3.js +2126 -0
  28. package/dist/chunk-CW5HJ3LX.js +96 -0
  29. package/dist/chunk-DB2VF5UD.js +315 -0
  30. package/dist/chunk-DWAGCNEL.js +210 -0
  31. package/dist/chunk-EA3DP5HG.js +293 -0
  32. package/dist/chunk-ELGCAM7P.js +184 -0
  33. package/dist/chunk-FW6BD2NO.js +1915 -0
  34. package/dist/chunk-GE37NVLN.js +15 -0
  35. package/dist/chunk-GPTKSNR6.js +171 -0
  36. package/dist/chunk-GRJXQBQZ.js +793 -0
  37. package/dist/chunk-HWBBVLOT.js +92 -0
  38. package/dist/chunk-I2JUKN6Z.js +24 -0
  39. package/dist/chunk-I3M2KJXB.js +56 -0
  40. package/dist/chunk-IQ4SDKKY.js +733 -0
  41. package/dist/chunk-J5FZYN4A.js +116 -0
  42. package/dist/chunk-L6N4JFW2.js +263 -0
  43. package/dist/chunk-LBFGSSF2.js +126 -0
  44. package/dist/chunk-LEGPB7DO.js +81 -0
  45. package/dist/chunk-LO35HLQZ.js +219 -0
  46. package/dist/chunk-LRD4GBYE.js +73 -0
  47. package/dist/chunk-LUAKDHLZ.js +40 -0
  48. package/dist/chunk-LYMPYETA.js +965 -0
  49. package/dist/chunk-M6NYEXCW.js +38 -0
  50. package/dist/chunk-MHUEVBVO.js +35 -0
  51. package/dist/chunk-MYGSLK44.js +37 -0
  52. package/dist/chunk-NH5I4KHH.js +201 -0
  53. package/dist/chunk-OQS4GUSI.js +1391 -0
  54. package/dist/chunk-PSX3GIAN.js +176 -0
  55. package/dist/chunk-Q5VPF4WI.js +26 -0
  56. package/dist/chunk-QKGYDMWB.js +7409 -0
  57. package/dist/chunk-QSL6QN5X.js +115 -0
  58. package/dist/chunk-SHCEBP3J.js +107 -0
  59. package/dist/chunk-SJOVFF7B.js +201 -0
  60. package/dist/chunk-ST2X2GYN.js +373 -0
  61. package/dist/chunk-TNTXWSYA.js +19 -0
  62. package/dist/chunk-U5AT3TD4.js +2128 -0
  63. package/dist/chunk-UDVNA7EA.js +483 -0
  64. package/dist/chunk-VL2E5T2A.js +109 -0
  65. package/dist/chunk-VLRHFMGJ.js +58 -0
  66. package/dist/chunk-WHX2ZFCG.js +4048 -0
  67. package/dist/chunk-WQ23REYT.js +37 -0
  68. package/dist/chunk-XBIDMHSK.js +15425 -0
  69. package/dist/chunk-Y5GI7RL3.js +66 -0
  70. package/dist/client-IRKAMDYZ.js +15 -0
  71. package/dist/commands-FIL5ET6P.js +911 -0
  72. package/dist/compat-R3UTFQ5Q.js +201 -0
  73. package/dist/dashboardIssue-WYYMBFIB.js +192 -0
  74. package/dist/diff-GZA2774U.js +13 -0
  75. package/dist/dist-4XXIXHHZ.js +12945 -0
  76. package/dist/e2b-FVPHDULZ.js +172 -0
  77. package/dist/extract-NKGKLIVT.js +444 -0
  78. package/dist/fetch-QYTUJVG2.js +22 -0
  79. package/dist/firstTouch-QQTJH4QX.js +55 -0
  80. package/dist/handlers-GEJAVZDK.js +53 -0
  81. package/dist/http-ETPYMBGD.js +5360 -0
  82. package/dist/ingestQueue-VKN4KBIF.js +35 -0
  83. package/dist/install-EK3W2COX.js +20 -0
  84. package/dist/installSkill-VQJWJVCL.js +52 -0
  85. package/dist/inventory-5AWSLJYU.js +31 -0
  86. package/dist/local-XPZMRH5R.js +13 -0
  87. package/dist/mcp-3JHD5SUZ.js +472 -0
  88. package/dist/mcpHandlers-QFN4MCFL.js +22 -0
  89. package/dist/mcpScan-QZHWENIP.js +1871 -0
  90. package/dist/mcpScanWorkflow-JPYCBGC4.js +81 -0
  91. package/dist/mcpStack-BYJCZNIV.js +20 -0
  92. package/dist/packages-THVFMWFP.js +42 -0
  93. package/dist/plan-V4OEI3J4.js +463 -0
  94. package/dist/planView-JRXGCG2N.js +79 -0
  95. package/dist/policy-3P6BGRDN.js +115 -0
  96. package/dist/references-6N7VEPHT.js +14 -0
  97. package/dist/release-4U4ABNSJ.js +128 -0
  98. package/dist/remote-YGCXYI4V.js +32 -0
  99. package/dist/reportRuns-CKQQYLY4.js +64 -0
  100. package/dist/sandbox-MEZLAODF.js +39 -0
  101. package/dist/server-KFUD5X57.js +55 -0
  102. package/dist/surface-V62GE554.js +141 -0
  103. package/dist/surface-YL6O67W3.js +36 -0
  104. package/dist/surfaceHandlers-X2IZKA3E.js +20 -0
  105. package/dist/typecheck-X7U5ELMR.js +268 -0
  106. package/dist/types-M5JP2W3D.js +10 -0
  107. package/dist/uninstall-P7RGBX6G.js +174 -0
  108. package/dist/upgrade-NQ5IWFZB.js +596 -0
  109. package/dist/upgradePlan-A4LRKLEG.js +146 -0
  110. package/dist/userConfig-Z3GQE776.js +20 -0
  111. package/dist/watch-DGFMWUDL.js +214 -0
  112. package/package.json +26 -21
  113. package/templates/agent-rules.md +4 -4
  114. package/templates/skill-instructions.md +13 -14
  115. package/dist/bin/lurq.js.map +0 -1
  116. package/dist/index.d.ts +0 -805
  117. package/dist/index.js +0 -23570
  118. package/dist/index.js.map +0 -1
  119. package/drizzle/0000_confused_fabian_cortez.sql +0 -54
  120. package/drizzle/0001_aspiring_timeslip.sql +0 -15
  121. package/drizzle/0002_lyrical_lila_cheney.sql +0 -14
  122. package/drizzle/0003_violet_giant_girl.sql +0 -14
  123. package/drizzle/0004_slim_valeria_richards.sql +0 -15
  124. package/drizzle/0005_petite_luke_cage.sql +0 -12
  125. package/drizzle/0006_calm_nighthawk.sql +0 -3
  126. package/drizzle/0007_slimy_naoko.sql +0 -1
  127. package/drizzle/0008_peaceful_tigra.sql +0 -1
  128. package/drizzle/0009_smooth_harrier.sql +0 -10
  129. package/drizzle/0010_curved_amphibian.sql +0 -2
  130. package/drizzle/0011_compat_provenance_closures.sql +0 -11
  131. package/drizzle/0012_api_surfaces.sql +0 -9
  132. package/drizzle/0013_nice_thanos.sql +0 -1
  133. package/drizzle/0014_luxuriant_malcolm_colcord.sql +0 -10
  134. package/drizzle/0015_past_fat_cobra.sql +0 -11
  135. package/drizzle/0016_futuristic_junta.sql +0 -50
  136. package/drizzle/0017_absent_grandmaster.sql +0 -20
  137. package/drizzle/0018_rainy_proemial_gods.sql +0 -1
  138. package/drizzle/0019_dashing_korvac.sql +0 -11
  139. package/drizzle/0020_normal_vulture.sql +0 -3
  140. package/drizzle/0021_dazzling_blue_shield.sql +0 -17
  141. package/drizzle/0022_massive_ghost_rider.sql +0 -24
  142. package/drizzle/0023_next_shatterstar.sql +0 -1
  143. package/drizzle/0024_dusty_maelstrom.sql +0 -15
  144. package/drizzle/0025_gifted_harpoon.sql +0 -5
  145. package/drizzle/0026_awesome_mordo.sql +0 -1
  146. package/drizzle/0027_charming_ulik.sql +0 -2
  147. package/drizzle/0028_romantic_loners.sql +0 -2
  148. package/drizzle/0029_busy_korvac.sql +0 -16
  149. package/drizzle/0030_steady_mathemanic.sql +0 -6
  150. package/drizzle/0031_redundant_maginty.sql +0 -2
  151. package/drizzle/0032_stack_resolutions.sql +0 -14
  152. package/drizzle/0033_graceful_tyger_tiger.sql +0 -3
  153. package/drizzle/0034_uneven_thunderbird.sql +0 -1
  154. package/drizzle/0035_api_key_scopes.sql +0 -1
  155. package/drizzle/0036_policy_audit.sql +0 -21
  156. package/drizzle/0037_subscription_seats.sql +0 -1
  157. package/drizzle/0038_symbol_offsets.sql +0 -2
  158. package/drizzle/0039_mcp_runtime_scans.sql +0 -80
  159. package/drizzle/0040_subscription_overage_and_interval.sql +0 -4
  160. package/drizzle/0041_account_email.sql +0 -38
  161. package/drizzle/0042_alert_channels.sql +0 -21
  162. package/drizzle/meta/0000_snapshot.json +0 -370
  163. package/drizzle/meta/0001_snapshot.json +0 -482
  164. package/drizzle/meta/0002_snapshot.json +0 -575
  165. package/drizzle/meta/0003_snapshot.json +0 -667
  166. package/drizzle/meta/0004_snapshot.json +0 -769
  167. package/drizzle/meta/0005_snapshot.json +0 -864
  168. package/drizzle/meta/0006_snapshot.json +0 -882
  169. package/drizzle/meta/0007_snapshot.json +0 -876
  170. package/drizzle/meta/0008_snapshot.json +0 -882
  171. package/drizzle/meta/0009_snapshot.json +0 -948
  172. package/drizzle/meta/0010_snapshot.json +0 -969
  173. package/drizzle/meta/0011_snapshot.json +0 -1049
  174. package/drizzle/meta/0012_snapshot.json +0 -1115
  175. package/drizzle/meta/0013_snapshot.json +0 -1121
  176. package/drizzle/meta/0014_snapshot.json +0 -1190
  177. package/drizzle/meta/0015_snapshot.json +0 -1280
  178. package/drizzle/meta/0016_snapshot.json +0 -1683
  179. package/drizzle/meta/0017_snapshot.json +0 -1834
  180. package/drizzle/meta/0018_snapshot.json +0 -1834
  181. package/drizzle/meta/0019_snapshot.json +0 -1909
  182. package/drizzle/meta/0020_snapshot.json +0 -1921
  183. package/drizzle/meta/0021_snapshot.json +0 -2045
  184. package/drizzle/meta/0022_snapshot.json +0 -2246
  185. package/drizzle/meta/0023_snapshot.json +0 -2252
  186. package/drizzle/meta/0024_snapshot.json +0 -2375
  187. package/drizzle/meta/0025_snapshot.json +0 -2407
  188. package/drizzle/meta/0026_snapshot.json +0 -2413
  189. package/drizzle/meta/0027_snapshot.json +0 -2425
  190. package/drizzle/meta/0028_snapshot.json +0 -2438
  191. package/drizzle/meta/0029_snapshot.json +0 -2546
  192. package/drizzle/meta/0030_snapshot.json +0 -2586
  193. package/drizzle/meta/0031_snapshot.json +0 -2598
  194. package/drizzle/meta/0032_snapshot.json +0 -2699
  195. package/drizzle/meta/0033_snapshot.json +0 -2712
  196. package/drizzle/meta/0034_snapshot.json +0 -2719
  197. package/drizzle/meta/0035_snapshot.json +0 -2726
  198. package/drizzle/meta/0036_snapshot.json +0 -2876
  199. package/drizzle/meta/0037_snapshot.json +0 -2883
  200. package/drizzle/meta/0038_snapshot.json +0 -2895
  201. package/drizzle/meta/0039_snapshot.json +0 -3501
  202. package/drizzle/meta/0040_snapshot.json +0 -3527
  203. package/drizzle/meta/0041_snapshot.json +0 -3824
  204. package/drizzle/meta/0042_snapshot.json +0 -3960
  205. package/drizzle/meta/_journal.json +0 -307
  206. package/src/data/seed.json +0 -253
@@ -0,0 +1,2128 @@
1
+ import { createRequire as __lurqCreateRequire } from 'node:module'; const require = __lurqCreateRequire(import.meta.url);
2
+ import {
3
+ ErrorCode,
4
+ JSONRPCMessageSchema,
5
+ LATEST_PROTOCOL_VERSION,
6
+ McpError,
7
+ NEVER,
8
+ ZodIssueCode,
9
+ any,
10
+ array,
11
+ boolean,
12
+ coerce_exports,
13
+ isInitializedNotification,
14
+ isJSONRPCRequest,
15
+ isJSONRPCResultResponse,
16
+ literal,
17
+ looseObject,
18
+ number,
19
+ object,
20
+ string,
21
+ url
22
+ } from "./chunk-6AAEVQ7I.js";
23
+ import {
24
+ init_esm_shims
25
+ } from "./chunk-I3M2KJXB.js";
26
+
27
+ // src/mcpScan/errors.ts
28
+ init_esm_shims();
29
+
30
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
31
+ init_esm_shims();
32
+
33
+ // node_modules/pkce-challenge/dist/index.node.js
34
+ init_esm_shims();
35
+ var crypto;
36
+ crypto = globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL
37
+ globalThis.crypto ?? // Node.js >18
38
+ import("crypto").then((m) => m.webcrypto);
39
+ async function getRandomValues(size) {
40
+ return (await crypto).getRandomValues(new Uint8Array(size));
41
+ }
42
+ async function random(size) {
43
+ const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
44
+ const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;
45
+ let result = "";
46
+ while (result.length < size) {
47
+ const randomBytes = await getRandomValues(size - result.length);
48
+ for (const randomByte of randomBytes) {
49
+ if (randomByte < evenDistCutoff) {
50
+ result += mask[randomByte % mask.length];
51
+ }
52
+ }
53
+ }
54
+ return result;
55
+ }
56
+ async function generateVerifier(length) {
57
+ return await random(length);
58
+ }
59
+ async function generateChallenge(code_verifier) {
60
+ const buffer = await (await crypto).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier));
61
+ return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "");
62
+ }
63
+ async function pkceChallenge(length) {
64
+ if (!length)
65
+ length = 43;
66
+ if (length < 43 || length > 128) {
67
+ throw `Expected a length between 43 and 128. Received ${length}.`;
68
+ }
69
+ const verifier = await generateVerifier(length);
70
+ const challenge = await generateChallenge(verifier);
71
+ return {
72
+ code_verifier: verifier,
73
+ code_challenge: challenge
74
+ };
75
+ }
76
+
77
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
78
+ init_esm_shims();
79
+ var SafeUrlSchema = url().superRefine((val, ctx) => {
80
+ if (!URL.canParse(val)) {
81
+ ctx.addIssue({
82
+ code: ZodIssueCode.custom,
83
+ message: "URL must be parseable",
84
+ fatal: true
85
+ });
86
+ return NEVER;
87
+ }
88
+ }).refine((url2) => {
89
+ const u = new URL(url2);
90
+ return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:";
91
+ }, { message: "URL cannot use javascript:, data:, or vbscript: scheme" });
92
+ var OAuthProtectedResourceMetadataSchema = looseObject({
93
+ resource: string().url(),
94
+ authorization_servers: array(SafeUrlSchema).optional(),
95
+ jwks_uri: string().url().optional(),
96
+ scopes_supported: array(string()).optional(),
97
+ bearer_methods_supported: array(string()).optional(),
98
+ resource_signing_alg_values_supported: array(string()).optional(),
99
+ resource_name: string().optional(),
100
+ resource_documentation: string().optional(),
101
+ resource_policy_uri: string().url().optional(),
102
+ resource_tos_uri: string().url().optional(),
103
+ tls_client_certificate_bound_access_tokens: boolean().optional(),
104
+ authorization_details_types_supported: array(string()).optional(),
105
+ dpop_signing_alg_values_supported: array(string()).optional(),
106
+ dpop_bound_access_tokens_required: boolean().optional()
107
+ });
108
+ var OAuthMetadataSchema = looseObject({
109
+ issuer: string(),
110
+ authorization_endpoint: SafeUrlSchema,
111
+ token_endpoint: SafeUrlSchema,
112
+ registration_endpoint: SafeUrlSchema.optional(),
113
+ scopes_supported: array(string()).optional(),
114
+ response_types_supported: array(string()),
115
+ response_modes_supported: array(string()).optional(),
116
+ grant_types_supported: array(string()).optional(),
117
+ token_endpoint_auth_methods_supported: array(string()).optional(),
118
+ token_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
119
+ service_documentation: SafeUrlSchema.optional(),
120
+ revocation_endpoint: SafeUrlSchema.optional(),
121
+ revocation_endpoint_auth_methods_supported: array(string()).optional(),
122
+ revocation_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
123
+ introspection_endpoint: string().optional(),
124
+ introspection_endpoint_auth_methods_supported: array(string()).optional(),
125
+ introspection_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
126
+ code_challenge_methods_supported: array(string()).optional(),
127
+ client_id_metadata_document_supported: boolean().optional()
128
+ });
129
+ var OpenIdProviderMetadataSchema = looseObject({
130
+ issuer: string(),
131
+ authorization_endpoint: SafeUrlSchema,
132
+ token_endpoint: SafeUrlSchema,
133
+ userinfo_endpoint: SafeUrlSchema.optional(),
134
+ jwks_uri: SafeUrlSchema,
135
+ registration_endpoint: SafeUrlSchema.optional(),
136
+ scopes_supported: array(string()).optional(),
137
+ response_types_supported: array(string()),
138
+ response_modes_supported: array(string()).optional(),
139
+ grant_types_supported: array(string()).optional(),
140
+ acr_values_supported: array(string()).optional(),
141
+ subject_types_supported: array(string()),
142
+ id_token_signing_alg_values_supported: array(string()),
143
+ id_token_encryption_alg_values_supported: array(string()).optional(),
144
+ id_token_encryption_enc_values_supported: array(string()).optional(),
145
+ userinfo_signing_alg_values_supported: array(string()).optional(),
146
+ userinfo_encryption_alg_values_supported: array(string()).optional(),
147
+ userinfo_encryption_enc_values_supported: array(string()).optional(),
148
+ request_object_signing_alg_values_supported: array(string()).optional(),
149
+ request_object_encryption_alg_values_supported: array(string()).optional(),
150
+ request_object_encryption_enc_values_supported: array(string()).optional(),
151
+ token_endpoint_auth_methods_supported: array(string()).optional(),
152
+ token_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
153
+ display_values_supported: array(string()).optional(),
154
+ claim_types_supported: array(string()).optional(),
155
+ claims_supported: array(string()).optional(),
156
+ service_documentation: string().optional(),
157
+ claims_locales_supported: array(string()).optional(),
158
+ ui_locales_supported: array(string()).optional(),
159
+ claims_parameter_supported: boolean().optional(),
160
+ request_parameter_supported: boolean().optional(),
161
+ request_uri_parameter_supported: boolean().optional(),
162
+ require_request_uri_registration: boolean().optional(),
163
+ op_policy_uri: SafeUrlSchema.optional(),
164
+ op_tos_uri: SafeUrlSchema.optional(),
165
+ client_id_metadata_document_supported: boolean().optional()
166
+ });
167
+ var OpenIdProviderDiscoveryMetadataSchema = object({
168
+ ...OpenIdProviderMetadataSchema.shape,
169
+ ...OAuthMetadataSchema.pick({
170
+ code_challenge_methods_supported: true
171
+ }).shape
172
+ });
173
+ var OAuthTokensSchema = object({
174
+ access_token: string(),
175
+ id_token: string().optional(),
176
+ // Optional for OAuth 2.1, but necessary in OpenID Connect
177
+ token_type: string(),
178
+ expires_in: coerce_exports.number().optional(),
179
+ scope: string().optional(),
180
+ refresh_token: string().optional()
181
+ }).strip();
182
+ var OAuthErrorResponseSchema = object({
183
+ error: string(),
184
+ error_description: string().optional(),
185
+ error_uri: string().optional()
186
+ });
187
+ var OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0));
188
+ var OAuthClientMetadataSchema = object({
189
+ redirect_uris: array(SafeUrlSchema),
190
+ token_endpoint_auth_method: string().optional(),
191
+ grant_types: array(string()).optional(),
192
+ response_types: array(string()).optional(),
193
+ client_name: string().optional(),
194
+ client_uri: SafeUrlSchema.optional(),
195
+ logo_uri: OptionalSafeUrlSchema,
196
+ scope: string().optional(),
197
+ contacts: array(string()).optional(),
198
+ tos_uri: OptionalSafeUrlSchema,
199
+ policy_uri: string().optional(),
200
+ jwks_uri: SafeUrlSchema.optional(),
201
+ jwks: any().optional(),
202
+ software_id: string().optional(),
203
+ software_version: string().optional(),
204
+ software_statement: string().optional()
205
+ }).strip();
206
+ var OAuthClientInformationSchema = object({
207
+ client_id: string(),
208
+ client_secret: string().optional(),
209
+ client_id_issued_at: number().optional(),
210
+ client_secret_expires_at: number().optional()
211
+ }).strip();
212
+ var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
213
+ var OAuthClientRegistrationErrorSchema = object({
214
+ error: string(),
215
+ error_description: string().optional()
216
+ }).strip();
217
+ var OAuthTokenRevocationRequestSchema = object({
218
+ token: string(),
219
+ token_type_hint: string().optional()
220
+ }).strip();
221
+
222
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js
223
+ init_esm_shims();
224
+ function resourceUrlFromServerUrl(url2) {
225
+ const resourceURL = typeof url2 === "string" ? new URL(url2) : new URL(url2.href);
226
+ resourceURL.hash = "";
227
+ return resourceURL;
228
+ }
229
+ function checkResourceAllowed({ requestedResource, configuredResource }) {
230
+ const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href);
231
+ const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href);
232
+ if (requested.origin !== configured.origin) {
233
+ return false;
234
+ }
235
+ if (requested.pathname.length < configured.pathname.length) {
236
+ return false;
237
+ }
238
+ const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/";
239
+ const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/";
240
+ return requestedPath.startsWith(configuredPath);
241
+ }
242
+
243
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js
244
+ init_esm_shims();
245
+ var OAuthError = class extends Error {
246
+ constructor(message, errorUri) {
247
+ super(message);
248
+ this.errorUri = errorUri;
249
+ this.name = this.constructor.name;
250
+ }
251
+ /**
252
+ * Converts the error to a standard OAuth error response object
253
+ */
254
+ toResponseObject() {
255
+ const response = {
256
+ error: this.errorCode,
257
+ error_description: this.message
258
+ };
259
+ if (this.errorUri) {
260
+ response.error_uri = this.errorUri;
261
+ }
262
+ return response;
263
+ }
264
+ get errorCode() {
265
+ return this.constructor.errorCode;
266
+ }
267
+ };
268
+ var InvalidRequestError = class extends OAuthError {
269
+ };
270
+ InvalidRequestError.errorCode = "invalid_request";
271
+ var InvalidClientError = class extends OAuthError {
272
+ };
273
+ InvalidClientError.errorCode = "invalid_client";
274
+ var InvalidGrantError = class extends OAuthError {
275
+ };
276
+ InvalidGrantError.errorCode = "invalid_grant";
277
+ var UnauthorizedClientError = class extends OAuthError {
278
+ };
279
+ UnauthorizedClientError.errorCode = "unauthorized_client";
280
+ var UnsupportedGrantTypeError = class extends OAuthError {
281
+ };
282
+ UnsupportedGrantTypeError.errorCode = "unsupported_grant_type";
283
+ var InvalidScopeError = class extends OAuthError {
284
+ };
285
+ InvalidScopeError.errorCode = "invalid_scope";
286
+ var AccessDeniedError = class extends OAuthError {
287
+ };
288
+ AccessDeniedError.errorCode = "access_denied";
289
+ var ServerError = class extends OAuthError {
290
+ };
291
+ ServerError.errorCode = "server_error";
292
+ var TemporarilyUnavailableError = class extends OAuthError {
293
+ };
294
+ TemporarilyUnavailableError.errorCode = "temporarily_unavailable";
295
+ var UnsupportedResponseTypeError = class extends OAuthError {
296
+ };
297
+ UnsupportedResponseTypeError.errorCode = "unsupported_response_type";
298
+ var UnsupportedTokenTypeError = class extends OAuthError {
299
+ };
300
+ UnsupportedTokenTypeError.errorCode = "unsupported_token_type";
301
+ var InvalidTokenError = class extends OAuthError {
302
+ };
303
+ InvalidTokenError.errorCode = "invalid_token";
304
+ var MethodNotAllowedError = class extends OAuthError {
305
+ };
306
+ MethodNotAllowedError.errorCode = "method_not_allowed";
307
+ var TooManyRequestsError = class extends OAuthError {
308
+ };
309
+ TooManyRequestsError.errorCode = "too_many_requests";
310
+ var InvalidClientMetadataError = class extends OAuthError {
311
+ };
312
+ InvalidClientMetadataError.errorCode = "invalid_client_metadata";
313
+ var InsufficientScopeError = class extends OAuthError {
314
+ };
315
+ InsufficientScopeError.errorCode = "insufficient_scope";
316
+ var InvalidTargetError = class extends OAuthError {
317
+ };
318
+ InvalidTargetError.errorCode = "invalid_target";
319
+ var OAUTH_ERRORS = {
320
+ [InvalidRequestError.errorCode]: InvalidRequestError,
321
+ [InvalidClientError.errorCode]: InvalidClientError,
322
+ [InvalidGrantError.errorCode]: InvalidGrantError,
323
+ [UnauthorizedClientError.errorCode]: UnauthorizedClientError,
324
+ [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError,
325
+ [InvalidScopeError.errorCode]: InvalidScopeError,
326
+ [AccessDeniedError.errorCode]: AccessDeniedError,
327
+ [ServerError.errorCode]: ServerError,
328
+ [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError,
329
+ [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError,
330
+ [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError,
331
+ [InvalidTokenError.errorCode]: InvalidTokenError,
332
+ [MethodNotAllowedError.errorCode]: MethodNotAllowedError,
333
+ [TooManyRequestsError.errorCode]: TooManyRequestsError,
334
+ [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,
335
+ [InsufficientScopeError.errorCode]: InsufficientScopeError,
336
+ [InvalidTargetError.errorCode]: InvalidTargetError
337
+ };
338
+
339
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
340
+ var UnauthorizedError = class extends Error {
341
+ constructor(message) {
342
+ super(message ?? "Unauthorized");
343
+ }
344
+ };
345
+ function isClientAuthMethod(method) {
346
+ return ["client_secret_basic", "client_secret_post", "none"].includes(method);
347
+ }
348
+ var AUTHORIZATION_CODE_RESPONSE_TYPE = "code";
349
+ var AUTHORIZATION_CODE_CHALLENGE_METHOD = "S256";
350
+ function selectClientAuthMethod(clientInformation, supportedMethods) {
351
+ const hasClientSecret = clientInformation.client_secret !== void 0;
352
+ if ("token_endpoint_auth_method" in clientInformation && clientInformation.token_endpoint_auth_method && isClientAuthMethod(clientInformation.token_endpoint_auth_method) && (supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method))) {
353
+ return clientInformation.token_endpoint_auth_method;
354
+ }
355
+ if (supportedMethods.length === 0) {
356
+ return hasClientSecret ? "client_secret_basic" : "none";
357
+ }
358
+ if (hasClientSecret && supportedMethods.includes("client_secret_basic")) {
359
+ return "client_secret_basic";
360
+ }
361
+ if (hasClientSecret && supportedMethods.includes("client_secret_post")) {
362
+ return "client_secret_post";
363
+ }
364
+ if (supportedMethods.includes("none")) {
365
+ return "none";
366
+ }
367
+ return hasClientSecret ? "client_secret_post" : "none";
368
+ }
369
+ function applyClientAuthentication(method, clientInformation, headers, params) {
370
+ const { client_id, client_secret } = clientInformation;
371
+ switch (method) {
372
+ case "client_secret_basic":
373
+ applyBasicAuth(client_id, client_secret, headers);
374
+ return;
375
+ case "client_secret_post":
376
+ applyPostAuth(client_id, client_secret, params);
377
+ return;
378
+ case "none":
379
+ applyPublicAuth(client_id, params);
380
+ return;
381
+ default:
382
+ throw new Error(`Unsupported client authentication method: ${method}`);
383
+ }
384
+ }
385
+ function applyBasicAuth(clientId, clientSecret, headers) {
386
+ if (!clientSecret) {
387
+ throw new Error("client_secret_basic authentication requires a client_secret");
388
+ }
389
+ const credentials = btoa(`${clientId}:${clientSecret}`);
390
+ headers.set("Authorization", `Basic ${credentials}`);
391
+ }
392
+ function applyPostAuth(clientId, clientSecret, params) {
393
+ params.set("client_id", clientId);
394
+ if (clientSecret) {
395
+ params.set("client_secret", clientSecret);
396
+ }
397
+ }
398
+ function applyPublicAuth(clientId, params) {
399
+ params.set("client_id", clientId);
400
+ }
401
+ async function parseErrorResponse(input) {
402
+ const statusCode = input instanceof Response ? input.status : void 0;
403
+ const body = input instanceof Response ? await input.text() : input;
404
+ try {
405
+ const result = OAuthErrorResponseSchema.parse(JSON.parse(body));
406
+ const { error, error_description, error_uri } = result;
407
+ const errorClass = OAUTH_ERRORS[error] || ServerError;
408
+ return new errorClass(error_description || "", error_uri);
409
+ } catch (error) {
410
+ const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`;
411
+ return new ServerError(errorMessage);
412
+ }
413
+ }
414
+ async function auth(provider, options) {
415
+ try {
416
+ return await authInternal(provider, options);
417
+ } catch (error) {
418
+ if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) {
419
+ await provider.invalidateCredentials?.("all");
420
+ return await authInternal(provider, options);
421
+ } else if (error instanceof InvalidGrantError) {
422
+ await provider.invalidateCredentials?.("tokens");
423
+ return await authInternal(provider, options);
424
+ }
425
+ throw error;
426
+ }
427
+ }
428
+ async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {
429
+ const cachedState = await provider.discoveryState?.();
430
+ let resourceMetadata;
431
+ let authorizationServerUrl;
432
+ let metadata;
433
+ let effectiveResourceMetadataUrl = resourceMetadataUrl;
434
+ if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) {
435
+ effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl);
436
+ }
437
+ if (cachedState?.authorizationServerUrl) {
438
+ authorizationServerUrl = cachedState.authorizationServerUrl;
439
+ resourceMetadata = cachedState.resourceMetadata;
440
+ metadata = cachedState.authorizationServerMetadata ?? await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn });
441
+ if (!resourceMetadata) {
442
+ try {
443
+ resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn);
444
+ } catch {
445
+ }
446
+ }
447
+ if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) {
448
+ await provider.saveDiscoveryState?.({
449
+ authorizationServerUrl: String(authorizationServerUrl),
450
+ resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
451
+ resourceMetadata,
452
+ authorizationServerMetadata: metadata
453
+ });
454
+ }
455
+ } else {
456
+ const serverInfo = await discoverOAuthServerInfo(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl, fetchFn });
457
+ authorizationServerUrl = serverInfo.authorizationServerUrl;
458
+ metadata = serverInfo.authorizationServerMetadata;
459
+ resourceMetadata = serverInfo.resourceMetadata;
460
+ await provider.saveDiscoveryState?.({
461
+ authorizationServerUrl: String(authorizationServerUrl),
462
+ resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
463
+ resourceMetadata,
464
+ authorizationServerMetadata: metadata
465
+ });
466
+ }
467
+ const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
468
+ const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
469
+ let clientInformation = await Promise.resolve(provider.clientInformation());
470
+ if (!clientInformation) {
471
+ if (authorizationCode !== void 0) {
472
+ throw new Error("Existing OAuth client information is required when exchanging an authorization code");
473
+ }
474
+ const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true;
475
+ const clientMetadataUrl = provider.clientMetadataUrl;
476
+ if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) {
477
+ throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);
478
+ }
479
+ const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;
480
+ if (shouldUseUrlBasedClientId) {
481
+ clientInformation = {
482
+ client_id: clientMetadataUrl
483
+ };
484
+ await provider.saveClientInformation?.(clientInformation);
485
+ } else {
486
+ if (!provider.saveClientInformation) {
487
+ throw new Error("OAuth client information must be saveable for dynamic registration");
488
+ }
489
+ const fullInformation = await registerClient(authorizationServerUrl, {
490
+ metadata,
491
+ clientMetadata: provider.clientMetadata,
492
+ scope: resolvedScope,
493
+ fetchFn
494
+ });
495
+ await provider.saveClientInformation(fullInformation);
496
+ clientInformation = fullInformation;
497
+ }
498
+ }
499
+ const nonInteractiveFlow = !provider.redirectUrl;
500
+ if (authorizationCode !== void 0 || nonInteractiveFlow) {
501
+ const tokens2 = await fetchToken(provider, authorizationServerUrl, {
502
+ metadata,
503
+ resource,
504
+ authorizationCode,
505
+ fetchFn
506
+ });
507
+ await provider.saveTokens(tokens2);
508
+ return "AUTHORIZED";
509
+ }
510
+ const tokens = await provider.tokens();
511
+ if (tokens?.refresh_token) {
512
+ try {
513
+ const newTokens = await refreshAuthorization(authorizationServerUrl, {
514
+ metadata,
515
+ clientInformation,
516
+ refreshToken: tokens.refresh_token,
517
+ resource,
518
+ addClientAuthentication: provider.addClientAuthentication,
519
+ fetchFn
520
+ });
521
+ await provider.saveTokens(newTokens);
522
+ return "AUTHORIZED";
523
+ } catch (error) {
524
+ if (!(error instanceof OAuthError) || error instanceof ServerError) {
525
+ } else {
526
+ throw error;
527
+ }
528
+ }
529
+ }
530
+ const state = provider.state ? await provider.state() : void 0;
531
+ const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {
532
+ metadata,
533
+ clientInformation,
534
+ state,
535
+ redirectUrl: provider.redirectUrl,
536
+ scope: resolvedScope,
537
+ resource
538
+ });
539
+ await provider.saveCodeVerifier(codeVerifier);
540
+ await provider.redirectToAuthorization(authorizationUrl);
541
+ return "REDIRECT";
542
+ }
543
+ function isHttpsUrl(value) {
544
+ if (!value)
545
+ return false;
546
+ try {
547
+ const url2 = new URL(value);
548
+ return url2.protocol === "https:" && url2.pathname !== "/";
549
+ } catch {
550
+ return false;
551
+ }
552
+ }
553
+ async function selectResourceURL(serverUrl, provider, resourceMetadata) {
554
+ const defaultResource = resourceUrlFromServerUrl(serverUrl);
555
+ if (provider.validateResourceURL) {
556
+ return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource);
557
+ }
558
+ if (!resourceMetadata) {
559
+ return void 0;
560
+ }
561
+ if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) {
562
+ throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);
563
+ }
564
+ return new URL(resourceMetadata.resource);
565
+ }
566
+ function extractWWWAuthenticateParams(res) {
567
+ const authenticateHeader = res.headers.get("WWW-Authenticate");
568
+ if (!authenticateHeader) {
569
+ return {};
570
+ }
571
+ const [type, scheme] = authenticateHeader.split(" ");
572
+ if (type.toLowerCase() !== "bearer" || !scheme) {
573
+ return {};
574
+ }
575
+ const resourceMetadataMatch = extractFieldFromWwwAuth(res, "resource_metadata") || void 0;
576
+ let resourceMetadataUrl;
577
+ if (resourceMetadataMatch) {
578
+ try {
579
+ resourceMetadataUrl = new URL(resourceMetadataMatch);
580
+ } catch {
581
+ }
582
+ }
583
+ const scope = extractFieldFromWwwAuth(res, "scope") || void 0;
584
+ const error = extractFieldFromWwwAuth(res, "error") || void 0;
585
+ return {
586
+ resourceMetadataUrl,
587
+ scope,
588
+ error
589
+ };
590
+ }
591
+ function extractFieldFromWwwAuth(response, fieldName) {
592
+ const wwwAuthHeader = response.headers.get("WWW-Authenticate");
593
+ if (!wwwAuthHeader) {
594
+ return null;
595
+ }
596
+ const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`);
597
+ const match = wwwAuthHeader.match(pattern);
598
+ if (match) {
599
+ return match[1] || match[2];
600
+ }
601
+ return null;
602
+ }
603
+ async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
604
+ const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, {
605
+ protocolVersion: opts?.protocolVersion,
606
+ metadataUrl: opts?.resourceMetadataUrl
607
+ });
608
+ if (!response || response.status === 404) {
609
+ await response?.body?.cancel();
610
+ throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);
611
+ }
612
+ if (!response.ok) {
613
+ await response.body?.cancel();
614
+ throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);
615
+ }
616
+ return OAuthProtectedResourceMetadataSchema.parse(await response.json());
617
+ }
618
+ async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) {
619
+ try {
620
+ return await fetchFn(url2, { headers });
621
+ } catch (error) {
622
+ if (error instanceof TypeError) {
623
+ if (headers) {
624
+ return fetchWithCorsRetry(url2, void 0, fetchFn);
625
+ } else {
626
+ return void 0;
627
+ }
628
+ }
629
+ throw error;
630
+ }
631
+ }
632
+ function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) {
633
+ if (pathname.endsWith("/")) {
634
+ pathname = pathname.slice(0, -1);
635
+ }
636
+ return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;
637
+ }
638
+ async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) {
639
+ const headers = {
640
+ "MCP-Protocol-Version": protocolVersion
641
+ };
642
+ return await fetchWithCorsRetry(url2, headers, fetchFn);
643
+ }
644
+ function shouldAttemptFallback(response, pathname) {
645
+ return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
646
+ }
647
+ async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
648
+ const issuer = new URL(serverUrl);
649
+ const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION;
650
+ let url2;
651
+ if (opts?.metadataUrl) {
652
+ url2 = new URL(opts.metadataUrl);
653
+ } else {
654
+ const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
655
+ url2 = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer);
656
+ url2.search = issuer.search;
657
+ }
658
+ let response = await tryMetadataDiscovery(url2, protocolVersion, fetchFn);
659
+ if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) {
660
+ const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);
661
+ response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);
662
+ }
663
+ return response;
664
+ }
665
+ function buildDiscoveryUrls(authorizationServerUrl) {
666
+ const url2 = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl;
667
+ const hasPath = url2.pathname !== "/";
668
+ const urlsToTry = [];
669
+ if (!hasPath) {
670
+ urlsToTry.push({
671
+ url: new URL("/.well-known/oauth-authorization-server", url2.origin),
672
+ type: "oauth"
673
+ });
674
+ urlsToTry.push({
675
+ url: new URL(`/.well-known/openid-configuration`, url2.origin),
676
+ type: "oidc"
677
+ });
678
+ return urlsToTry;
679
+ }
680
+ let pathname = url2.pathname;
681
+ if (pathname.endsWith("/")) {
682
+ pathname = pathname.slice(0, -1);
683
+ }
684
+ urlsToTry.push({
685
+ url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url2.origin),
686
+ type: "oauth"
687
+ });
688
+ urlsToTry.push({
689
+ url: new URL(`/.well-known/openid-configuration${pathname}`, url2.origin),
690
+ type: "oidc"
691
+ });
692
+ urlsToTry.push({
693
+ url: new URL(`${pathname}/.well-known/openid-configuration`, url2.origin),
694
+ type: "oidc"
695
+ });
696
+ return urlsToTry;
697
+ }
698
+ async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) {
699
+ const headers = {
700
+ "MCP-Protocol-Version": protocolVersion,
701
+ Accept: "application/json"
702
+ };
703
+ const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);
704
+ for (const { url: endpointUrl, type } of urlsToTry) {
705
+ const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);
706
+ if (!response) {
707
+ continue;
708
+ }
709
+ if (!response.ok) {
710
+ await response.body?.cancel();
711
+ if (response.status >= 400 && response.status < 500) {
712
+ continue;
713
+ }
714
+ throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
715
+ }
716
+ if (type === "oauth") {
717
+ return OAuthMetadataSchema.parse(await response.json());
718
+ } else {
719
+ return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());
720
+ }
721
+ }
722
+ return void 0;
723
+ }
724
+ async function discoverOAuthServerInfo(serverUrl, opts) {
725
+ let resourceMetadata;
726
+ let authorizationServerUrl;
727
+ try {
728
+ resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn);
729
+ if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {
730
+ authorizationServerUrl = resourceMetadata.authorization_servers[0];
731
+ }
732
+ } catch {
733
+ }
734
+ if (!authorizationServerUrl) {
735
+ authorizationServerUrl = String(new URL("/", serverUrl));
736
+ }
737
+ const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts?.fetchFn });
738
+ return {
739
+ authorizationServerUrl,
740
+ authorizationServerMetadata,
741
+ resourceMetadata
742
+ };
743
+ }
744
+ async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {
745
+ let authorizationUrl;
746
+ if (metadata) {
747
+ authorizationUrl = new URL(metadata.authorization_endpoint);
748
+ if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) {
749
+ throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);
750
+ }
751
+ if (metadata.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) {
752
+ throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`);
753
+ }
754
+ } else {
755
+ authorizationUrl = new URL("/authorize", authorizationServerUrl);
756
+ }
757
+ const challenge = await pkceChallenge();
758
+ const codeVerifier = challenge.code_verifier;
759
+ const codeChallenge = challenge.code_challenge;
760
+ authorizationUrl.searchParams.set("response_type", AUTHORIZATION_CODE_RESPONSE_TYPE);
761
+ authorizationUrl.searchParams.set("client_id", clientInformation.client_id);
762
+ authorizationUrl.searchParams.set("code_challenge", codeChallenge);
763
+ authorizationUrl.searchParams.set("code_challenge_method", AUTHORIZATION_CODE_CHALLENGE_METHOD);
764
+ authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl));
765
+ if (state) {
766
+ authorizationUrl.searchParams.set("state", state);
767
+ }
768
+ if (scope) {
769
+ authorizationUrl.searchParams.set("scope", scope);
770
+ }
771
+ if (scope?.includes("offline_access")) {
772
+ authorizationUrl.searchParams.append("prompt", "consent");
773
+ }
774
+ if (resource) {
775
+ authorizationUrl.searchParams.set("resource", resource.href);
776
+ }
777
+ return { authorizationUrl, codeVerifier };
778
+ }
779
+ function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {
780
+ return new URLSearchParams({
781
+ grant_type: "authorization_code",
782
+ code: authorizationCode,
783
+ code_verifier: codeVerifier,
784
+ redirect_uri: String(redirectUri)
785
+ });
786
+ }
787
+ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {
788
+ const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl);
789
+ const headers = new Headers({
790
+ "Content-Type": "application/x-www-form-urlencoded",
791
+ Accept: "application/json"
792
+ });
793
+ if (resource) {
794
+ tokenRequestParams.set("resource", resource.href);
795
+ }
796
+ if (addClientAuthentication) {
797
+ await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
798
+ } else if (clientInformation) {
799
+ const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? [];
800
+ const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
801
+ applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);
802
+ }
803
+ const response = await (fetchFn ?? fetch)(tokenUrl, {
804
+ method: "POST",
805
+ headers,
806
+ body: tokenRequestParams
807
+ });
808
+ if (!response.ok) {
809
+ throw await parseErrorResponse(response);
810
+ }
811
+ return OAuthTokensSchema.parse(await response.json());
812
+ }
813
+ async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
814
+ const tokenRequestParams = new URLSearchParams({
815
+ grant_type: "refresh_token",
816
+ refresh_token: refreshToken
817
+ });
818
+ const tokens = await executeTokenRequest(authorizationServerUrl, {
819
+ metadata,
820
+ tokenRequestParams,
821
+ clientInformation,
822
+ addClientAuthentication,
823
+ resource,
824
+ fetchFn
825
+ });
826
+ return { refresh_token: refreshToken, ...tokens };
827
+ }
828
+ async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
829
+ const scope = provider.clientMetadata.scope;
830
+ let tokenRequestParams;
831
+ if (provider.prepareTokenRequest) {
832
+ tokenRequestParams = await provider.prepareTokenRequest(scope);
833
+ }
834
+ if (!tokenRequestParams) {
835
+ if (!authorizationCode) {
836
+ throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");
837
+ }
838
+ if (!provider.redirectUrl) {
839
+ throw new Error("redirectUrl is required for authorization_code flow");
840
+ }
841
+ const codeVerifier = await provider.codeVerifier();
842
+ tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);
843
+ }
844
+ const clientInformation = await provider.clientInformation();
845
+ return executeTokenRequest(authorizationServerUrl, {
846
+ metadata,
847
+ tokenRequestParams,
848
+ clientInformation: clientInformation ?? void 0,
849
+ addClientAuthentication: provider.addClientAuthentication,
850
+ resource,
851
+ fetchFn
852
+ });
853
+ }
854
+ async function registerClient(authorizationServerUrl, { metadata, clientMetadata, scope, fetchFn }) {
855
+ let registrationUrl;
856
+ if (metadata) {
857
+ if (!metadata.registration_endpoint) {
858
+ throw new Error("Incompatible auth server: does not support dynamic client registration");
859
+ }
860
+ registrationUrl = new URL(metadata.registration_endpoint);
861
+ } else {
862
+ registrationUrl = new URL("/register", authorizationServerUrl);
863
+ }
864
+ const response = await (fetchFn ?? fetch)(registrationUrl, {
865
+ method: "POST",
866
+ headers: {
867
+ "Content-Type": "application/json"
868
+ },
869
+ body: JSON.stringify({
870
+ ...clientMetadata,
871
+ ...scope !== void 0 ? { scope } : {}
872
+ })
873
+ });
874
+ if (!response.ok) {
875
+ throw await parseErrorResponse(response);
876
+ }
877
+ return OAuthClientInformationFullSchema.parse(await response.json());
878
+ }
879
+
880
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
881
+ init_esm_shims();
882
+
883
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js
884
+ init_esm_shims();
885
+ function normalizeHeaders(headers) {
886
+ if (!headers)
887
+ return {};
888
+ if (headers instanceof Headers) {
889
+ return Object.fromEntries(headers.entries());
890
+ }
891
+ if (Array.isArray(headers)) {
892
+ return Object.fromEntries(headers);
893
+ }
894
+ return { ...headers };
895
+ }
896
+ function createFetchWithInit(baseFetch = fetch, baseInit) {
897
+ if (!baseInit) {
898
+ return baseFetch;
899
+ }
900
+ return async (url2, init) => {
901
+ const mergedInit = {
902
+ ...baseInit,
903
+ ...init,
904
+ // Headers need special handling - merge instead of replace
905
+ headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers
906
+ };
907
+ return baseFetch(url2, mergedInit);
908
+ };
909
+ }
910
+
911
+ // node_modules/eventsource-parser/dist/stream.js
912
+ init_esm_shims();
913
+
914
+ // node_modules/eventsource-parser/dist/index.js
915
+ init_esm_shims();
916
+ var ParseError = class extends Error {
917
+ constructor(message, options) {
918
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
919
+ }
920
+ };
921
+ var LF = 10;
922
+ var CR = 13;
923
+ var SPACE = 32;
924
+ function noop(_arg) {
925
+ }
926
+ function createParser(config) {
927
+ if (typeof config == "function")
928
+ throw new TypeError(
929
+ "`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?"
930
+ );
931
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config, pendingFragments = [];
932
+ let pendingFragmentsLength = 0, isFirstChunk = true, id, data = "", dataLines = 0, eventType, terminated = false;
933
+ function feed(chunk) {
934
+ if (terminated)
935
+ throw new Error(
936
+ "Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing."
937
+ );
938
+ if (isFirstChunk && (isFirstChunk = false, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
939
+ const trailing2 = processLines(chunk);
940
+ trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
941
+ return;
942
+ }
943
+ if (chunk.indexOf(`
944
+ `) === -1 && chunk.indexOf("\r") === -1) {
945
+ pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
946
+ return;
947
+ }
948
+ pendingFragments.push(chunk);
949
+ const input = pendingFragments.join("");
950
+ pendingFragments.length = 0, pendingFragmentsLength = 0;
951
+ const trailing = processLines(input);
952
+ trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
953
+ }
954
+ function checkBufferSize() {
955
+ maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = true, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError(
956
+ new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {
957
+ type: "max-buffer-size-exceeded"
958
+ })
959
+ )));
960
+ }
961
+ function processLines(chunk) {
962
+ let searchIndex = 0;
963
+ if (chunk.indexOf("\r") === -1) {
964
+ let lfIndex = chunk.indexOf(`
965
+ `, searchIndex);
966
+ for (; lfIndex !== -1; ) {
967
+ if (searchIndex === lfIndex) {
968
+ dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
969
+ `, searchIndex);
970
+ continue;
971
+ }
972
+ const firstCharCode = chunk.charCodeAt(searchIndex);
973
+ if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
974
+ const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
975
+ if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
976
+ onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
977
+ `, searchIndex);
978
+ continue;
979
+ }
980
+ data = dataLines === 0 ? value : `${data}
981
+ ${value}`, dataLines++;
982
+ } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
983
+ chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
984
+ lfIndex
985
+ ) || void 0 : parseLine(chunk, searchIndex, lfIndex);
986
+ searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
987
+ `, searchIndex);
988
+ }
989
+ return chunk.slice(searchIndex);
990
+ }
991
+ for (; searchIndex < chunk.length; ) {
992
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
993
+ `, searchIndex);
994
+ let lineEnd = -1;
995
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)
996
+ break;
997
+ parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
998
+ }
999
+ return chunk.slice(searchIndex);
1000
+ }
1001
+ function parseLine(chunk, start, end) {
1002
+ if (start === end) {
1003
+ dispatchEvent();
1004
+ return;
1005
+ }
1006
+ const firstCharCode = chunk.charCodeAt(start);
1007
+ if (isDataPrefix(chunk, start, firstCharCode)) {
1008
+ const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
1009
+ data = dataLines === 0 ? value2 : `${data}
1010
+ ${value2}`, dataLines++;
1011
+ return;
1012
+ }
1013
+ if (isEventPrefix(chunk, start, firstCharCode)) {
1014
+ eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
1015
+ return;
1016
+ }
1017
+ if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
1018
+ const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
1019
+ id = value2.includes("\0") ? void 0 : value2;
1020
+ return;
1021
+ }
1022
+ if (firstCharCode === 58) {
1023
+ if (onComment) {
1024
+ const line2 = chunk.slice(start, end);
1025
+ onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
1026
+ }
1027
+ return;
1028
+ }
1029
+ const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
1030
+ if (fieldSeparatorIndex === -1) {
1031
+ processField(line, "", line);
1032
+ return;
1033
+ }
1034
+ const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
1035
+ processField(field, value, line);
1036
+ }
1037
+ function processField(field, value, line) {
1038
+ switch (field) {
1039
+ case "event":
1040
+ eventType = value || void 0;
1041
+ break;
1042
+ case "data":
1043
+ data = dataLines === 0 ? value : `${data}
1044
+ ${value}`, dataLines++;
1045
+ break;
1046
+ case "id":
1047
+ id = value.includes("\0") ? void 0 : value;
1048
+ break;
1049
+ case "retry":
1050
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
1051
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
1052
+ type: "invalid-retry",
1053
+ value,
1054
+ line
1055
+ })
1056
+ );
1057
+ break;
1058
+ default:
1059
+ onError(
1060
+ new ParseError(
1061
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
1062
+ { type: "unknown-field", field, value, line }
1063
+ )
1064
+ );
1065
+ break;
1066
+ }
1067
+ }
1068
+ function dispatchEvent() {
1069
+ dataLines > 0 && onEvent({
1070
+ id,
1071
+ event: eventType,
1072
+ data
1073
+ }), id = void 0, data = "", dataLines = 0, eventType = void 0;
1074
+ }
1075
+ function reset(options = {}) {
1076
+ if (options.consume && pendingFragments.length > 0) {
1077
+ const incompleteLine = pendingFragments.join("");
1078
+ parseLine(incompleteLine, 0, incompleteLine.length);
1079
+ }
1080
+ isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = false;
1081
+ }
1082
+ return { feed, reset };
1083
+ }
1084
+ function isDataPrefix(chunk, i, firstCharCode) {
1085
+ return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
1086
+ }
1087
+ function isEventPrefix(chunk, i, firstCharCode) {
1088
+ return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
1089
+ }
1090
+
1091
+ // node_modules/eventsource-parser/dist/stream.js
1092
+ var EventSourceParserStream = class extends TransformStream {
1093
+ constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {
1094
+ let parser;
1095
+ super({
1096
+ start(controller) {
1097
+ parser = createParser({
1098
+ onEvent: (event) => {
1099
+ controller.enqueue(event);
1100
+ },
1101
+ onError(error) {
1102
+ typeof onError == "function" && onError(error), (onError === "terminate" || error.type === "max-buffer-size-exceeded") && controller.error(error);
1103
+ },
1104
+ onRetry,
1105
+ onComment,
1106
+ maxBufferSize
1107
+ });
1108
+ },
1109
+ transform(chunk) {
1110
+ parser.feed(chunk);
1111
+ }
1112
+ });
1113
+ }
1114
+ };
1115
+
1116
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
1117
+ var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
1118
+ initialReconnectionDelay: 1e3,
1119
+ maxReconnectionDelay: 3e4,
1120
+ reconnectionDelayGrowFactor: 1.5,
1121
+ maxRetries: 2
1122
+ };
1123
+ var StreamableHTTPError = class extends Error {
1124
+ constructor(code, message) {
1125
+ super(`Streamable HTTP error: ${message}`);
1126
+ this.code = code;
1127
+ }
1128
+ };
1129
+ var StreamableHTTPClientTransport = class {
1130
+ constructor(url2, opts) {
1131
+ this._hasCompletedAuthFlow = false;
1132
+ this._url = url2;
1133
+ this._resourceMetadataUrl = void 0;
1134
+ this._scope = void 0;
1135
+ this._requestInit = opts?.requestInit;
1136
+ this._authProvider = opts?.authProvider;
1137
+ this._fetch = opts?.fetch;
1138
+ this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
1139
+ this._sessionId = opts?.sessionId;
1140
+ this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
1141
+ }
1142
+ async _authThenStart() {
1143
+ if (!this._authProvider) {
1144
+ throw new UnauthorizedError("No auth provider");
1145
+ }
1146
+ let result;
1147
+ try {
1148
+ result = await auth(this._authProvider, {
1149
+ serverUrl: this._url,
1150
+ resourceMetadataUrl: this._resourceMetadataUrl,
1151
+ scope: this._scope,
1152
+ fetchFn: this._fetchWithInit
1153
+ });
1154
+ } catch (error) {
1155
+ this.onerror?.(error);
1156
+ throw error;
1157
+ }
1158
+ if (result !== "AUTHORIZED") {
1159
+ throw new UnauthorizedError();
1160
+ }
1161
+ return await this._startOrAuthSse({ resumptionToken: void 0 });
1162
+ }
1163
+ async _commonHeaders() {
1164
+ const headers = {};
1165
+ if (this._authProvider) {
1166
+ const tokens = await this._authProvider.tokens();
1167
+ if (tokens) {
1168
+ headers["Authorization"] = `Bearer ${tokens.access_token}`;
1169
+ }
1170
+ }
1171
+ if (this._sessionId) {
1172
+ headers["mcp-session-id"] = this._sessionId;
1173
+ }
1174
+ if (this._protocolVersion) {
1175
+ headers["mcp-protocol-version"] = this._protocolVersion;
1176
+ }
1177
+ const extraHeaders = normalizeHeaders(this._requestInit?.headers);
1178
+ return new Headers({
1179
+ ...headers,
1180
+ ...extraHeaders
1181
+ });
1182
+ }
1183
+ async _startOrAuthSse(options) {
1184
+ const { resumptionToken } = options;
1185
+ try {
1186
+ const headers = await this._commonHeaders();
1187
+ headers.set("Accept", "text/event-stream");
1188
+ if (resumptionToken) {
1189
+ headers.set("last-event-id", resumptionToken);
1190
+ }
1191
+ const response = await (this._fetch ?? fetch)(this._url, {
1192
+ method: "GET",
1193
+ headers,
1194
+ signal: this._abortController?.signal
1195
+ });
1196
+ if (!response.ok) {
1197
+ await response.body?.cancel();
1198
+ if (response.status === 401 && this._authProvider) {
1199
+ return await this._authThenStart();
1200
+ }
1201
+ if (response.status === 405) {
1202
+ return;
1203
+ }
1204
+ throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`);
1205
+ }
1206
+ this._handleSseStream(response.body, options, true);
1207
+ } catch (error) {
1208
+ this.onerror?.(error);
1209
+ throw error;
1210
+ }
1211
+ }
1212
+ /**
1213
+ * Calculates the next reconnection delay using backoff algorithm
1214
+ *
1215
+ * @param attempt Current reconnection attempt count for the specific stream
1216
+ * @returns Time to wait in milliseconds before next reconnection attempt
1217
+ */
1218
+ _getNextReconnectionDelay(attempt) {
1219
+ if (this._serverRetryMs !== void 0) {
1220
+ return this._serverRetryMs;
1221
+ }
1222
+ const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
1223
+ const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
1224
+ const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
1225
+ return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
1226
+ }
1227
+ /**
1228
+ * Schedule a reconnection attempt using server-provided retry interval or backoff
1229
+ *
1230
+ * @param lastEventId The ID of the last received event for resumability
1231
+ * @param attemptCount Current reconnection attempt count for this specific stream
1232
+ */
1233
+ _scheduleReconnection(options, attemptCount = 0) {
1234
+ const maxRetries = this._reconnectionOptions.maxRetries;
1235
+ if (attemptCount >= maxRetries) {
1236
+ this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
1237
+ return;
1238
+ }
1239
+ const delay = this._getNextReconnectionDelay(attemptCount);
1240
+ this._reconnectionTimeout = setTimeout(() => {
1241
+ this._startOrAuthSse(options).catch((error) => {
1242
+ this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));
1243
+ this._scheduleReconnection(options, attemptCount + 1);
1244
+ });
1245
+ }, delay);
1246
+ }
1247
+ _handleSseStream(stream, options, isReconnectable) {
1248
+ if (!stream) {
1249
+ return;
1250
+ }
1251
+ const { onresumptiontoken, replayMessageId } = options;
1252
+ let lastEventId;
1253
+ let hasPrimingEvent = false;
1254
+ let receivedResponse = false;
1255
+ const processStream = async () => {
1256
+ try {
1257
+ const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({
1258
+ onRetry: (retryMs) => {
1259
+ this._serverRetryMs = retryMs;
1260
+ }
1261
+ })).getReader();
1262
+ while (true) {
1263
+ const { value: event, done } = await reader.read();
1264
+ if (done) {
1265
+ break;
1266
+ }
1267
+ if (event.id) {
1268
+ lastEventId = event.id;
1269
+ hasPrimingEvent = true;
1270
+ onresumptiontoken?.(event.id);
1271
+ }
1272
+ if (!event.data) {
1273
+ continue;
1274
+ }
1275
+ if (!event.event || event.event === "message") {
1276
+ try {
1277
+ const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
1278
+ if (isJSONRPCResultResponse(message)) {
1279
+ receivedResponse = true;
1280
+ if (replayMessageId !== void 0) {
1281
+ message.id = replayMessageId;
1282
+ }
1283
+ }
1284
+ this.onmessage?.(message);
1285
+ } catch (error) {
1286
+ this.onerror?.(error);
1287
+ }
1288
+ }
1289
+ }
1290
+ const canResume = isReconnectable || hasPrimingEvent;
1291
+ const needsReconnect = canResume && !receivedResponse;
1292
+ if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
1293
+ this._scheduleReconnection({
1294
+ resumptionToken: lastEventId,
1295
+ onresumptiontoken,
1296
+ replayMessageId
1297
+ }, 0);
1298
+ }
1299
+ } catch (error) {
1300
+ this.onerror?.(new Error(`SSE stream disconnected: ${error}`));
1301
+ const canResume = isReconnectable || hasPrimingEvent;
1302
+ const needsReconnect = canResume && !receivedResponse;
1303
+ if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
1304
+ try {
1305
+ this._scheduleReconnection({
1306
+ resumptionToken: lastEventId,
1307
+ onresumptiontoken,
1308
+ replayMessageId
1309
+ }, 0);
1310
+ } catch (error2) {
1311
+ this.onerror?.(new Error(`Failed to reconnect: ${error2 instanceof Error ? error2.message : String(error2)}`));
1312
+ }
1313
+ }
1314
+ }
1315
+ };
1316
+ processStream();
1317
+ }
1318
+ async start() {
1319
+ if (this._abortController) {
1320
+ throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");
1321
+ }
1322
+ this._abortController = new AbortController();
1323
+ }
1324
+ /**
1325
+ * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
1326
+ */
1327
+ async finishAuth(authorizationCode) {
1328
+ if (!this._authProvider) {
1329
+ throw new UnauthorizedError("No auth provider");
1330
+ }
1331
+ const result = await auth(this._authProvider, {
1332
+ serverUrl: this._url,
1333
+ authorizationCode,
1334
+ resourceMetadataUrl: this._resourceMetadataUrl,
1335
+ scope: this._scope,
1336
+ fetchFn: this._fetchWithInit
1337
+ });
1338
+ if (result !== "AUTHORIZED") {
1339
+ throw new UnauthorizedError("Failed to authorize");
1340
+ }
1341
+ }
1342
+ async close() {
1343
+ if (this._reconnectionTimeout) {
1344
+ clearTimeout(this._reconnectionTimeout);
1345
+ this._reconnectionTimeout = void 0;
1346
+ }
1347
+ this._abortController?.abort();
1348
+ this.onclose?.();
1349
+ }
1350
+ async send(message, options) {
1351
+ try {
1352
+ const { resumptionToken, onresumptiontoken } = options || {};
1353
+ if (resumptionToken) {
1354
+ this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : void 0 }).catch((err) => this.onerror?.(err));
1355
+ return;
1356
+ }
1357
+ const headers = await this._commonHeaders();
1358
+ headers.set("content-type", "application/json");
1359
+ headers.set("accept", "application/json, text/event-stream");
1360
+ const init = {
1361
+ ...this._requestInit,
1362
+ method: "POST",
1363
+ headers,
1364
+ body: JSON.stringify(message),
1365
+ signal: this._abortController?.signal
1366
+ };
1367
+ const response = await (this._fetch ?? fetch)(this._url, init);
1368
+ const sessionId = response.headers.get("mcp-session-id");
1369
+ if (sessionId) {
1370
+ this._sessionId = sessionId;
1371
+ }
1372
+ if (!response.ok) {
1373
+ const text = await response.text().catch(() => null);
1374
+ if (response.status === 401 && this._authProvider) {
1375
+ if (this._hasCompletedAuthFlow) {
1376
+ throw new StreamableHTTPError(401, "Server returned 401 after successful authentication");
1377
+ }
1378
+ const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
1379
+ this._resourceMetadataUrl = resourceMetadataUrl;
1380
+ this._scope = scope;
1381
+ const result = await auth(this._authProvider, {
1382
+ serverUrl: this._url,
1383
+ resourceMetadataUrl: this._resourceMetadataUrl,
1384
+ scope: this._scope,
1385
+ fetchFn: this._fetchWithInit
1386
+ });
1387
+ if (result !== "AUTHORIZED") {
1388
+ throw new UnauthorizedError();
1389
+ }
1390
+ this._hasCompletedAuthFlow = true;
1391
+ return this.send(message);
1392
+ }
1393
+ if (response.status === 403 && this._authProvider) {
1394
+ const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response);
1395
+ if (error === "insufficient_scope") {
1396
+ const wwwAuthHeader = response.headers.get("WWW-Authenticate");
1397
+ if (this._lastUpscopingHeader === wwwAuthHeader) {
1398
+ throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping");
1399
+ }
1400
+ if (scope) {
1401
+ this._scope = scope;
1402
+ }
1403
+ if (resourceMetadataUrl) {
1404
+ this._resourceMetadataUrl = resourceMetadataUrl;
1405
+ }
1406
+ this._lastUpscopingHeader = wwwAuthHeader ?? void 0;
1407
+ const result = await auth(this._authProvider, {
1408
+ serverUrl: this._url,
1409
+ resourceMetadataUrl: this._resourceMetadataUrl,
1410
+ scope: this._scope,
1411
+ fetchFn: this._fetch
1412
+ });
1413
+ if (result !== "AUTHORIZED") {
1414
+ throw new UnauthorizedError();
1415
+ }
1416
+ return this.send(message);
1417
+ }
1418
+ }
1419
+ throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);
1420
+ }
1421
+ this._hasCompletedAuthFlow = false;
1422
+ this._lastUpscopingHeader = void 0;
1423
+ if (response.status === 202) {
1424
+ await response.body?.cancel();
1425
+ if (isInitializedNotification(message)) {
1426
+ this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => this.onerror?.(err));
1427
+ }
1428
+ return;
1429
+ }
1430
+ const messages = Array.isArray(message) ? message : [message];
1431
+ const hasRequests = messages.filter((msg2) => "method" in msg2 && "id" in msg2 && msg2.id !== void 0).length > 0;
1432
+ const contentType = response.headers.get("content-type");
1433
+ if (hasRequests) {
1434
+ if (contentType?.includes("text/event-stream")) {
1435
+ this._handleSseStream(response.body, { onresumptiontoken }, false);
1436
+ } else if (contentType?.includes("application/json")) {
1437
+ const data = await response.json();
1438
+ const responseMessages = Array.isArray(data) ? data.map((msg2) => JSONRPCMessageSchema.parse(msg2)) : [JSONRPCMessageSchema.parse(data)];
1439
+ for (const msg2 of responseMessages) {
1440
+ this.onmessage?.(msg2);
1441
+ }
1442
+ } else {
1443
+ await response.body?.cancel();
1444
+ throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);
1445
+ }
1446
+ } else {
1447
+ await response.body?.cancel();
1448
+ }
1449
+ } catch (error) {
1450
+ this.onerror?.(error);
1451
+ throw error;
1452
+ }
1453
+ }
1454
+ get sessionId() {
1455
+ return this._sessionId;
1456
+ }
1457
+ /**
1458
+ * Terminates the current session by sending a DELETE request to the server.
1459
+ *
1460
+ * Clients that no longer need a particular session
1461
+ * (e.g., because the user is leaving the client application) SHOULD send an
1462
+ * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
1463
+ * terminate the session.
1464
+ *
1465
+ * The server MAY respond with HTTP 405 Method Not Allowed, indicating that
1466
+ * the server does not allow clients to terminate sessions.
1467
+ */
1468
+ async terminateSession() {
1469
+ if (!this._sessionId) {
1470
+ return;
1471
+ }
1472
+ try {
1473
+ const headers = await this._commonHeaders();
1474
+ const init = {
1475
+ ...this._requestInit,
1476
+ method: "DELETE",
1477
+ headers,
1478
+ signal: this._abortController?.signal
1479
+ };
1480
+ const response = await (this._fetch ?? fetch)(this._url, init);
1481
+ await response.body?.cancel();
1482
+ if (!response.ok && response.status !== 405) {
1483
+ throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);
1484
+ }
1485
+ this._sessionId = void 0;
1486
+ } catch (error) {
1487
+ this.onerror?.(error);
1488
+ throw error;
1489
+ }
1490
+ }
1491
+ setProtocolVersion(version) {
1492
+ this._protocolVersion = version;
1493
+ }
1494
+ get protocolVersion() {
1495
+ return this._protocolVersion;
1496
+ }
1497
+ /**
1498
+ * Resume an SSE stream from a previous event ID.
1499
+ * Opens a GET SSE connection with Last-Event-ID header to replay missed events.
1500
+ *
1501
+ * @param lastEventId The event ID to resume from
1502
+ * @param options Optional callback to receive new resumption tokens
1503
+ */
1504
+ async resumeStream(lastEventId, options) {
1505
+ await this._startOrAuthSse({
1506
+ resumptionToken: lastEventId,
1507
+ onresumptiontoken: options?.onresumptiontoken
1508
+ });
1509
+ }
1510
+ };
1511
+
1512
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
1513
+ init_esm_shims();
1514
+
1515
+ // node_modules/eventsource/dist/index.js
1516
+ init_esm_shims();
1517
+ var ErrorEvent = class extends Event {
1518
+ /**
1519
+ * Constructs a new `ErrorEvent` instance. This is typically not called directly,
1520
+ * but rather emitted by the `EventSource` object when an error occurs.
1521
+ *
1522
+ * @param type - The type of the event (should be "error")
1523
+ * @param errorEventInitDict - Optional properties to include in the error event
1524
+ */
1525
+ constructor(type, errorEventInitDict) {
1526
+ var _a, _b;
1527
+ super(type), this.code = (_a = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a : void 0, this.message = (_b = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b : void 0;
1528
+ }
1529
+ /**
1530
+ * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
1531
+ * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
1532
+ * we explicitly include the properties in the `inspect` method.
1533
+ *
1534
+ * This is automatically called by Node.js when you `console.log` an instance of this class.
1535
+ *
1536
+ * @param _depth - The current depth
1537
+ * @param options - The options passed to `util.inspect`
1538
+ * @param inspect - The inspect function to use (prevents having to import it from `util`)
1539
+ * @returns A string representation of the error
1540
+ */
1541
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) {
1542
+ return inspect(inspectableError(this), options);
1543
+ }
1544
+ /**
1545
+ * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
1546
+ * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
1547
+ * we explicitly include the properties in the `inspect` method.
1548
+ *
1549
+ * This is automatically called by Deno when you `console.log` an instance of this class.
1550
+ *
1551
+ * @param inspect - The inspect function to use (prevents having to import it from `util`)
1552
+ * @param options - The options passed to `Deno.inspect`
1553
+ * @returns A string representation of the error
1554
+ */
1555
+ [/* @__PURE__ */ Symbol.for("Deno.customInspect")](inspect, options) {
1556
+ return inspect(inspectableError(this), options);
1557
+ }
1558
+ };
1559
+ function syntaxError(message) {
1560
+ const DomException = globalThis.DOMException;
1561
+ return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message);
1562
+ }
1563
+ function flattenError(err) {
1564
+ return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError(err.cause)}` : err.message : `${err}`;
1565
+ }
1566
+ function inspectableError(err) {
1567
+ return {
1568
+ type: err.type,
1569
+ message: err.message,
1570
+ code: err.code,
1571
+ defaultPrevented: err.defaultPrevented,
1572
+ cancelable: err.cancelable,
1573
+ timeStamp: err.timeStamp
1574
+ };
1575
+ }
1576
+ var __typeError = (msg2) => {
1577
+ throw TypeError(msg2);
1578
+ };
1579
+ var __accessCheck = (obj, member, msg2) => member.has(obj) || __typeError("Cannot " + msg2);
1580
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
1581
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1582
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
1583
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
1584
+ var _readyState;
1585
+ var _url;
1586
+ var _redirectUrl;
1587
+ var _withCredentials;
1588
+ var _fetch;
1589
+ var _reconnectInterval;
1590
+ var _reconnectTimer;
1591
+ var _lastEventId;
1592
+ var _controller;
1593
+ var _parser;
1594
+ var _onError;
1595
+ var _onMessage;
1596
+ var _onOpen;
1597
+ var _EventSource_instances;
1598
+ var connect_fn;
1599
+ var _onFetchResponse;
1600
+ var _onFetchError;
1601
+ var getRequestOptions_fn;
1602
+ var _onEvent;
1603
+ var _onRetryChange;
1604
+ var failConnection_fn;
1605
+ var scheduleReconnect_fn;
1606
+ var _reconnect;
1607
+ var EventSource = class extends EventTarget {
1608
+ constructor(url2, eventSourceInitDict) {
1609
+ var _a, _b;
1610
+ super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => {
1611
+ var _a2;
1612
+ __privateGet(this, _parser).reset();
1613
+ const { body, redirected, status, headers } = response;
1614
+ if (status === 204) {
1615
+ __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
1616
+ return;
1617
+ }
1618
+ if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) {
1619
+ __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status);
1620
+ return;
1621
+ }
1622
+ if (!(headers.get("content-type") || "").startsWith("text/event-stream")) {
1623
+ __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected "text/event-stream"', status);
1624
+ return;
1625
+ }
1626
+ if (__privateGet(this, _readyState) === this.CLOSED)
1627
+ return;
1628
+ __privateSet(this, _readyState, this.OPEN);
1629
+ const openEvent = new Event("open");
1630
+ if ((_a2 = __privateGet(this, _onOpen)) == null || _a2.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) {
1631
+ __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close();
1632
+ return;
1633
+ }
1634
+ const decoder = new TextDecoder(), reader = body.getReader();
1635
+ let open = true;
1636
+ do {
1637
+ const { done, value } = await reader.read();
1638
+ value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open = false, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));
1639
+ } while (open);
1640
+ }), __privateAdd(this, _onFetchError, (err) => {
1641
+ __privateSet(this, _controller, void 0), !(err.name === "AbortError" || err.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError(err));
1642
+ }), __privateAdd(this, _onEvent, (event) => {
1643
+ typeof event.id == "string" && __privateSet(this, _lastEventId, event.id);
1644
+ const messageEvent = new MessageEvent(event.event || "message", {
1645
+ data: event.data,
1646
+ origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url).origin,
1647
+ lastEventId: event.id || ""
1648
+ });
1649
+ __privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent);
1650
+ }), __privateAdd(this, _onRetryChange, (value) => {
1651
+ __privateSet(this, _reconnectInterval, value);
1652
+ }), __privateAdd(this, _reconnect, () => {
1653
+ __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this);
1654
+ });
1655
+ try {
1656
+ if (url2 instanceof URL)
1657
+ __privateSet(this, _url, url2);
1658
+ else if (typeof url2 == "string")
1659
+ __privateSet(this, _url, new URL(url2, getBaseURL()));
1660
+ else
1661
+ throw new Error("Invalid URL");
1662
+ } catch {
1663
+ throw syntaxError("An invalid or illegal string was specified");
1664
+ }
1665
+ __privateSet(this, _parser, createParser({
1666
+ onEvent: __privateGet(this, _onEvent),
1667
+ onRetry: __privateGet(this, _onRetryChange)
1668
+ })), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a : globalThis.fetch), __privateSet(this, _withCredentials, (_b = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b : false), __privateMethod(this, _EventSource_instances, connect_fn).call(this);
1669
+ }
1670
+ /**
1671
+ * Returns the state of this EventSource object's connection. It can have the values described below.
1672
+ *
1673
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
1674
+ *
1675
+ * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
1676
+ * defined in the TypeScript `dom` library.
1677
+ *
1678
+ * @public
1679
+ */
1680
+ get readyState() {
1681
+ return __privateGet(this, _readyState);
1682
+ }
1683
+ /**
1684
+ * Returns the URL providing the event stream.
1685
+ *
1686
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
1687
+ *
1688
+ * @public
1689
+ */
1690
+ get url() {
1691
+ return __privateGet(this, _url).href;
1692
+ }
1693
+ /**
1694
+ * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
1695
+ *
1696
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
1697
+ */
1698
+ get withCredentials() {
1699
+ return __privateGet(this, _withCredentials);
1700
+ }
1701
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
1702
+ get onerror() {
1703
+ return __privateGet(this, _onError);
1704
+ }
1705
+ set onerror(value) {
1706
+ __privateSet(this, _onError, value);
1707
+ }
1708
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
1709
+ get onmessage() {
1710
+ return __privateGet(this, _onMessage);
1711
+ }
1712
+ set onmessage(value) {
1713
+ __privateSet(this, _onMessage, value);
1714
+ }
1715
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
1716
+ get onopen() {
1717
+ return __privateGet(this, _onOpen);
1718
+ }
1719
+ set onopen(value) {
1720
+ __privateSet(this, _onOpen, value);
1721
+ }
1722
+ addEventListener(type, listener, options) {
1723
+ const listen = listener;
1724
+ super.addEventListener(type, listen, options);
1725
+ }
1726
+ removeEventListener(type, listener, options) {
1727
+ const listen = listener;
1728
+ super.removeEventListener(type, listen, options);
1729
+ }
1730
+ /**
1731
+ * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
1732
+ *
1733
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
1734
+ *
1735
+ * @public
1736
+ */
1737
+ close() {
1738
+ __privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0));
1739
+ }
1740
+ };
1741
+ _readyState = /* @__PURE__ */ new WeakMap(), _url = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), /**
1742
+ * Connect to the given URL and start receiving events
1743
+ *
1744
+ * @internal
1745
+ */
1746
+ connect_fn = function() {
1747
+ __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError));
1748
+ }, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /**
1749
+ * Get request options for the `fetch()` request
1750
+ *
1751
+ * @returns The request options
1752
+ * @internal
1753
+ */
1754
+ getRequestOptions_fn = function() {
1755
+ var _a;
1756
+ const init = {
1757
+ // [spec] Let `corsAttributeState` be `Anonymous`…
1758
+ // [spec] …will have their mode set to "cors"…
1759
+ mode: "cors",
1760
+ redirect: "follow",
1761
+ headers: { Accept: "text/event-stream", ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0 },
1762
+ cache: "no-store",
1763
+ signal: (_a = __privateGet(this, _controller)) == null ? void 0 : _a.signal
1764
+ };
1765
+ return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init;
1766
+ }, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /**
1767
+ * Handles the process referred to in the EventSource specification as "failing a connection".
1768
+ *
1769
+ * @param error - The error causing the connection to fail
1770
+ * @param code - The HTTP status code, if available
1771
+ * @internal
1772
+ */
1773
+ failConnection_fn = function(message, code) {
1774
+ var _a;
1775
+ __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED);
1776
+ const errorEvent = new ErrorEvent("error", { code, message });
1777
+ (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent);
1778
+ }, /**
1779
+ * Schedules a reconnection attempt against the EventSource endpoint.
1780
+ *
1781
+ * @param message - The error causing the connection to fail
1782
+ * @param code - The HTTP status code, if available
1783
+ * @internal
1784
+ */
1785
+ scheduleReconnect_fn = function(message, code) {
1786
+ var _a;
1787
+ if (__privateGet(this, _readyState) === this.CLOSED)
1788
+ return;
1789
+ __privateSet(this, _readyState, this.CONNECTING);
1790
+ const errorEvent = new ErrorEvent("error", { code, message });
1791
+ (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval)));
1792
+ }, _reconnect = /* @__PURE__ */ new WeakMap(), /**
1793
+ * ReadyState representing an EventSource currently trying to connect
1794
+ *
1795
+ * @public
1796
+ */
1797
+ EventSource.CONNECTING = 0, /**
1798
+ * ReadyState representing an EventSource connection that is open (eg connected)
1799
+ *
1800
+ * @public
1801
+ */
1802
+ EventSource.OPEN = 1, /**
1803
+ * ReadyState representing an EventSource connection that is closed (eg disconnected)
1804
+ *
1805
+ * @public
1806
+ */
1807
+ EventSource.CLOSED = 2;
1808
+ function getBaseURL() {
1809
+ const doc = "document" in globalThis ? globalThis.document : void 0;
1810
+ return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0;
1811
+ }
1812
+
1813
+ // node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
1814
+ var SseError = class extends Error {
1815
+ constructor(code, message, event) {
1816
+ super(`SSE error: ${message}`);
1817
+ this.code = code;
1818
+ this.event = event;
1819
+ }
1820
+ };
1821
+ var SSEClientTransport = class {
1822
+ constructor(url2, opts) {
1823
+ this._url = url2;
1824
+ this._resourceMetadataUrl = void 0;
1825
+ this._scope = void 0;
1826
+ this._eventSourceInit = opts?.eventSourceInit;
1827
+ this._requestInit = opts?.requestInit;
1828
+ this._authProvider = opts?.authProvider;
1829
+ this._fetch = opts?.fetch;
1830
+ this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
1831
+ }
1832
+ async _authThenStart() {
1833
+ if (!this._authProvider) {
1834
+ throw new UnauthorizedError("No auth provider");
1835
+ }
1836
+ let result;
1837
+ try {
1838
+ result = await auth(this._authProvider, {
1839
+ serverUrl: this._url,
1840
+ resourceMetadataUrl: this._resourceMetadataUrl,
1841
+ scope: this._scope,
1842
+ fetchFn: this._fetchWithInit
1843
+ });
1844
+ } catch (error) {
1845
+ this.onerror?.(error);
1846
+ throw error;
1847
+ }
1848
+ if (result !== "AUTHORIZED") {
1849
+ throw new UnauthorizedError();
1850
+ }
1851
+ return await this._startOrAuth();
1852
+ }
1853
+ async _commonHeaders() {
1854
+ const headers = {};
1855
+ if (this._authProvider) {
1856
+ const tokens = await this._authProvider.tokens();
1857
+ if (tokens) {
1858
+ headers["Authorization"] = `Bearer ${tokens.access_token}`;
1859
+ }
1860
+ }
1861
+ if (this._protocolVersion) {
1862
+ headers["mcp-protocol-version"] = this._protocolVersion;
1863
+ }
1864
+ const extraHeaders = normalizeHeaders(this._requestInit?.headers);
1865
+ return new Headers({
1866
+ ...headers,
1867
+ ...extraHeaders
1868
+ });
1869
+ }
1870
+ _startOrAuth() {
1871
+ const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
1872
+ return new Promise((resolve, reject) => {
1873
+ this._eventSource = new EventSource(this._url.href, {
1874
+ ...this._eventSourceInit,
1875
+ fetch: async (url2, init) => {
1876
+ const headers = await this._commonHeaders();
1877
+ headers.set("Accept", "text/event-stream");
1878
+ const response = await fetchImpl(url2, {
1879
+ ...init,
1880
+ headers
1881
+ });
1882
+ if (response.status === 401 && response.headers.has("www-authenticate")) {
1883
+ const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
1884
+ this._resourceMetadataUrl = resourceMetadataUrl;
1885
+ this._scope = scope;
1886
+ }
1887
+ return response;
1888
+ }
1889
+ });
1890
+ this._abortController = new AbortController();
1891
+ this._eventSource.onerror = (event) => {
1892
+ if (event.code === 401 && this._authProvider) {
1893
+ this._authThenStart().then(resolve, reject);
1894
+ return;
1895
+ }
1896
+ const error = new SseError(event.code, event.message, event);
1897
+ reject(error);
1898
+ this.onerror?.(error);
1899
+ };
1900
+ this._eventSource.onopen = () => {
1901
+ };
1902
+ this._eventSource.addEventListener("endpoint", (event) => {
1903
+ const messageEvent = event;
1904
+ try {
1905
+ this._endpoint = new URL(messageEvent.data, this._url);
1906
+ if (this._endpoint.origin !== this._url.origin) {
1907
+ throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);
1908
+ }
1909
+ } catch (error) {
1910
+ reject(error);
1911
+ this.onerror?.(error);
1912
+ void this.close();
1913
+ return;
1914
+ }
1915
+ resolve();
1916
+ });
1917
+ this._eventSource.onmessage = (event) => {
1918
+ const messageEvent = event;
1919
+ let message;
1920
+ try {
1921
+ message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
1922
+ } catch (error) {
1923
+ this.onerror?.(error);
1924
+ return;
1925
+ }
1926
+ this.onmessage?.(message);
1927
+ };
1928
+ });
1929
+ }
1930
+ async start() {
1931
+ if (this._eventSource) {
1932
+ throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");
1933
+ }
1934
+ return await this._startOrAuth();
1935
+ }
1936
+ /**
1937
+ * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
1938
+ */
1939
+ async finishAuth(authorizationCode) {
1940
+ if (!this._authProvider) {
1941
+ throw new UnauthorizedError("No auth provider");
1942
+ }
1943
+ const result = await auth(this._authProvider, {
1944
+ serverUrl: this._url,
1945
+ authorizationCode,
1946
+ resourceMetadataUrl: this._resourceMetadataUrl,
1947
+ scope: this._scope,
1948
+ fetchFn: this._fetchWithInit
1949
+ });
1950
+ if (result !== "AUTHORIZED") {
1951
+ throw new UnauthorizedError("Failed to authorize");
1952
+ }
1953
+ }
1954
+ async close() {
1955
+ this._abortController?.abort();
1956
+ this._eventSource?.close();
1957
+ this.onclose?.();
1958
+ }
1959
+ async send(message) {
1960
+ if (!this._endpoint) {
1961
+ throw new Error("Not connected");
1962
+ }
1963
+ try {
1964
+ const headers = await this._commonHeaders();
1965
+ headers.set("content-type", "application/json");
1966
+ const init = {
1967
+ ...this._requestInit,
1968
+ method: "POST",
1969
+ headers,
1970
+ body: JSON.stringify(message),
1971
+ signal: this._abortController?.signal
1972
+ };
1973
+ const response = await (this._fetch ?? fetch)(this._endpoint, init);
1974
+ if (!response.ok) {
1975
+ const text = await response.text().catch(() => null);
1976
+ if (response.status === 401 && this._authProvider) {
1977
+ const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
1978
+ this._resourceMetadataUrl = resourceMetadataUrl;
1979
+ this._scope = scope;
1980
+ const result = await auth(this._authProvider, {
1981
+ serverUrl: this._url,
1982
+ resourceMetadataUrl: this._resourceMetadataUrl,
1983
+ scope: this._scope,
1984
+ fetchFn: this._fetchWithInit
1985
+ });
1986
+ if (result !== "AUTHORIZED") {
1987
+ throw new UnauthorizedError();
1988
+ }
1989
+ return this.send(message);
1990
+ }
1991
+ throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
1992
+ }
1993
+ await response.body?.cancel();
1994
+ } catch (error) {
1995
+ this.onerror?.(error);
1996
+ throw error;
1997
+ }
1998
+ }
1999
+ setProtocolVersion(version) {
2000
+ this._protocolVersion = version;
2001
+ }
2002
+ };
2003
+
2004
+ // src/mcpScan/errors.ts
2005
+ var ENV_COMPLAINT = /\b([A-Z][A-Z0-9]{2,}(?:_[A-Z0-9]+)+)\b[^.\n]{0,60}?\b(required|must be set|not set|missing|is not defined)\b|\b(required|must be set|missing)\b[^.\n]{0,60}?\b([A-Z][A-Z0-9]{2,}(?:_[A-Z0-9]+)+)\b/;
2006
+ function sniffMissingEnv(text) {
2007
+ const m = ENV_COMPLAINT.exec(text);
2008
+ return m ? m[1] ?? m[4] ?? null : null;
2009
+ }
2010
+ var NETWORK_CODES = /* @__PURE__ */ new Set([
2011
+ "ECONNREFUSED",
2012
+ "ENOTFOUND",
2013
+ "EAI_AGAIN",
2014
+ "ECONNRESET",
2015
+ "ETIMEDOUT",
2016
+ "EHOSTUNREACH",
2017
+ "ENETUNREACH",
2018
+ "UND_ERR_CONNECT_TIMEOUT",
2019
+ "UND_ERR_SOCKET",
2020
+ "CERT_HAS_EXPIRED",
2021
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
2022
+ "SELF_SIGNED_CERT_IN_CHAIN",
2023
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
2024
+ "ERR_TLS_CERT_ALTNAME_INVALID"
2025
+ ]);
2026
+ function causeCode(err) {
2027
+ let cur = err;
2028
+ for (let i = 0; i < 5 && cur; i++) {
2029
+ const code = cur.code;
2030
+ if (typeof code === "string") return code;
2031
+ cur = cur.cause;
2032
+ }
2033
+ return null;
2034
+ }
2035
+ var msg = (err) => err instanceof Error ? err.message : String(err);
2036
+ function classifyError(err, ctx) {
2037
+ const message = msg(err).slice(0, 500);
2038
+ if (err instanceof UnauthorizedError) {
2039
+ return {
2040
+ status: "auth_required",
2041
+ error: message || "the server requires authorization",
2042
+ hint: "this server signs in with OAuth, and lurq cannot reuse the token your agent holds; ask your agent to pass its tool list to the mcp_stack tool instead"
2043
+ };
2044
+ }
2045
+ const httpCode = err instanceof StreamableHTTPError || err instanceof SseError ? err.code : void 0;
2046
+ if (httpCode === 401 || httpCode === 403) {
2047
+ return {
2048
+ status: "auth_required",
2049
+ error: `HTTP ${httpCode}`,
2050
+ hint: "the server rejected the credentials in this config; check the Authorization header or token it is given"
2051
+ };
2052
+ }
2053
+ if (typeof httpCode === "number" && httpCode > 0) {
2054
+ return {
2055
+ status: "unreachable",
2056
+ error: `HTTP ${httpCode}: ${message}`,
2057
+ hint: httpCode === 404 ? "nothing answers MCP at this url; check the path" : null
2058
+ };
2059
+ }
2060
+ if (err instanceof McpError && err.code === ErrorCode.RequestTimeout) {
2061
+ return {
2062
+ status: "timeout",
2063
+ error: message,
2064
+ hint: ctx.transport === "stdio" ? "the server did not answer in time; a first run of npx/uvx downloads the package, so try again with a longer --timeout" : null
2065
+ };
2066
+ }
2067
+ const code = causeCode(err);
2068
+ if (code === "ENOENT" && ctx.transport === "stdio") {
2069
+ return {
2070
+ status: "spawn_failed",
2071
+ error: `command not found: ${ctx.command ?? "(none)"}`,
2072
+ hint: "install it, or use an absolute path in the config"
2073
+ };
2074
+ }
2075
+ if (code && NETWORK_CODES.has(code)) {
2076
+ return { status: "unreachable", error: `${code}: ${message}`, hint: null };
2077
+ }
2078
+ if (err instanceof TypeError && /fetch failed/i.test(message)) {
2079
+ const cause = err.cause;
2080
+ return { status: "unreachable", error: cause ? `fetch failed: ${msg(cause).slice(0, 300)}` : message, hint: null };
2081
+ }
2082
+ const closed = err instanceof McpError && err.code === ErrorCode.ConnectionClosed || /connection closed/i.test(message);
2083
+ if (closed && ctx.transport === "stdio") {
2084
+ const missing = sniffMissingEnv(ctx.stderrTail);
2085
+ if (missing) {
2086
+ return {
2087
+ status: "needs_config",
2088
+ error: `the server exited, and its output names ${missing} as required`,
2089
+ hint: `set ${missing} in this server's env block`
2090
+ };
2091
+ }
2092
+ if (ctx.stdoutNoise > 0 && !ctx.stderrTail.trim()) {
2093
+ return {
2094
+ status: "protocol_error",
2095
+ error: "the server wrote non-protocol output to stdout and then closed",
2096
+ hint: "stdio servers must log to stderr; stdout is reserved for JSON-RPC"
2097
+ };
2098
+ }
2099
+ return {
2100
+ status: "spawn_failed",
2101
+ error: ctx.stderrTail.trim() ? `exited before completing the handshake: ${ctx.stderrTail.trim().split("\n").slice(-3).join(" | ")}` : "exited before completing the handshake",
2102
+ hint: null
2103
+ };
2104
+ }
2105
+ if (/protocol version is not supported/i.test(message)) {
2106
+ return {
2107
+ status: "protocol_error",
2108
+ error: message,
2109
+ hint: "the server speaks a protocol revision this lurq version does not; upgrade lurq"
2110
+ };
2111
+ }
2112
+ if (ctx.stdoutNoise > 0) {
2113
+ return {
2114
+ status: "protocol_error",
2115
+ error: `${message} (the server also wrote ${ctx.stdoutNoise} non-protocol line(s) to stdout)`,
2116
+ hint: "stdio servers must log to stderr; stdout is reserved for JSON-RPC"
2117
+ };
2118
+ }
2119
+ return { status: "protocol_error", error: message || "unknown error", hint: null };
2120
+ }
2121
+
2122
+ export {
2123
+ StreamableHTTPError,
2124
+ StreamableHTTPClientTransport,
2125
+ SSEClientTransport,
2126
+ sniffMissingEnv,
2127
+ classifyError
2128
+ };