@mcp-use/inspector 0.9.0-canary.2 → 0.9.0-canary.3

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.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/winston-nzaZqgVL.js","assets/util-D59LNlyU.js","assets/__vite-browser-external-CHS79mP1.js","assets/index-DX0TIfSM.js","assets/path-QsnVvLoj.js","assets/index-DoWSnGj3.js","assets/index-B8yt0GKw.js","assets/index-BLXuIjh0.js","assets/embeddings-CF86nH4i.js","assets/index-BCYl76Jb.js","assets/index-CV9pPOH9.js","assets/browser-B7TIAiNJ.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/winston-wqn-wtrj.js","assets/util-D59LNlyU.js","assets/__vite-browser-external-CHS79mP1.js","assets/index-DX0TIfSM.js","assets/path-QsnVvLoj.js","assets/index-mu626HD_.js","assets/index-DPaWbs8Z.js","assets/index-DGNqjnfM.js","assets/embeddings-DWZf9aOm.js","assets/index-C9SmrfBE.js","assets/index-CvbM0GyZ.js","assets/browser-BxSiNtQZ.js"])))=>i.map(i=>d[i]);
2
2
  var __defProp = Object.defineProperty;
3
3
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
4
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
@@ -186,26 +186,6 @@ var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? requir
186
186
  throw Error('Dynamic require of "' + x2 + '" is not supported');
187
187
  });
188
188
  var define_process_env_default$2 = {};
189
- var isDeno = typeof globalThis.Deno !== "undefined";
190
- function getEnv(key) {
191
- if (isDeno) {
192
- return globalThis.Deno.env.get(key);
193
- }
194
- return define_process_env_default$2[key];
195
- }
196
- __name(getEnv, "getEnv");
197
- function getCwd() {
198
- if (isDeno) {
199
- return globalThis.Deno.cwd();
200
- }
201
- return process.cwd();
202
- }
203
- __name(getCwd, "getCwd");
204
- function generateUUID() {
205
- return globalThis.crypto.randomUUID();
206
- }
207
- __name(generateUUID, "generateUUID");
208
- var define_process_env_default$1 = {};
209
189
  async function getNodeModules() {
210
190
  if (typeof process !== "undefined" && "browser") {
211
191
  try {
@@ -231,7 +211,7 @@ function loadWinstonSync() {
231
211
  __name(loadWinstonSync, "loadWinstonSync");
232
212
  async function getWinston() {
233
213
  if (!winston) {
234
- winston = await __vitePreload(() => import("./winston-nzaZqgVL.js").then((n2) => n2.w), true ? __vite__mapDeps([0,1,2,3,4]) : void 0);
214
+ winston = await __vitePreload(() => import("./winston-wqn-wtrj.js").then((n2) => n2.w), true ? __vite__mapDeps([0,1,2,3,4]) : void 0);
235
215
  }
236
216
  return winston;
237
217
  }
@@ -321,7 +301,7 @@ var SimpleConsoleLogger = (_a2 = class {
321
301
  }
322
302
  }, __name(_a2, "SimpleConsoleLogger"), _a2);
323
303
  function resolveLevel(env) {
324
- const envValue = typeof process !== "undefined" && define_process_env_default$1 ? env : void 0;
304
+ const envValue = typeof process !== "undefined" && define_process_env_default$2 ? env : void 0;
325
305
  switch (envValue?.trim()) {
326
306
  case "2":
327
307
  return "debug";
@@ -336,7 +316,7 @@ var Logger = (_b = class {
336
316
  static get(name = DEFAULT_LOGGER_NAME) {
337
317
  if (!isNodeJSEnvironment()) {
338
318
  if (!this.simpleInstances[name]) {
339
- const debugEnv = typeof process !== "undefined" && define_process_env_default$1?.DEBUG || void 0;
319
+ const debugEnv = typeof process !== "undefined" && define_process_env_default$2?.DEBUG || void 0;
340
320
  this.simpleInstances[name] = new SimpleConsoleLogger(
341
321
  name,
342
322
  resolveLevel(debugEnv)
@@ -351,7 +331,7 @@ var Logger = (_b = class {
351
331
  const { createLogger, format: format2 } = winston;
352
332
  const { combine, timestamp, label, colorize, splat } = format2;
353
333
  this.instances[name] = createLogger({
354
- level: resolveLevel(define_process_env_default$1.DEBUG),
334
+ level: resolveLevel(define_process_env_default$2.DEBUG),
355
335
  format: combine(
356
336
  colorize(),
357
337
  splat(),
@@ -392,7 +372,7 @@ var Logger = (_b = class {
392
372
  }
393
373
  static async configure(options = {}) {
394
374
  const { level, console: console2 = true, file, format: format2 = "minimal" } = options;
395
- const debugEnv = typeof process !== "undefined" && define_process_env_default$1?.DEBUG || void 0;
375
+ const debugEnv = typeof process !== "undefined" && define_process_env_default$2?.DEBUG || void 0;
396
376
  const resolvedLevel = level ?? resolveLevel(debugEnv);
397
377
  this.currentFormat = format2;
398
378
  if (!isNodeJSEnvironment()) {
@@ -450,8 +430,8 @@ var Logger = (_b = class {
450
430
  logger2.level = level;
451
431
  }
452
432
  });
453
- if (typeof process !== "undefined" && define_process_env_default$1) {
454
- define_process_env_default$1.DEBUG = enabled ? enabled === true ? "2" : String(enabled) : "0";
433
+ if (typeof process !== "undefined" && define_process_env_default$2) {
434
+ define_process_env_default$2.DEBUG = enabled ? enabled === true ? "2" : String(enabled) : "0";
455
435
  }
456
436
  }
457
437
  static setFormat(format2) {
@@ -1051,7 +1031,7 @@ const _safeParse = (_Err) => (schema2, value, _ctx) => {
1051
1031
  error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
1052
1032
  } : { success: true, data: result.value };
1053
1033
  };
1054
- const safeParse$1 = /* @__PURE__ */ _safeParse($ZodRealError);
1034
+ const safeParse$2 = /* @__PURE__ */ _safeParse($ZodRealError);
1055
1035
  const _safeParseAsync = (_Err) => async (schema2, value, _ctx) => {
1056
1036
  const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
1057
1037
  let result = schema2._zod.run({ value, issues: [] }, ctx);
@@ -1668,7 +1648,7 @@ const $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
1668
1648
  inst["~standard"] = {
1669
1649
  validate: (value) => {
1670
1650
  try {
1671
- const r2 = safeParse$1(inst, value);
1651
+ const r2 = safeParse$2(inst, value);
1672
1652
  return r2.success ? { value: r2.data } : { issues: r2.error?.issues };
1673
1653
  } catch (_2) {
1674
1654
  return safeParseAsync$1(inst, value).then((r2) => r2.success ? { value: r2.data } : { issues: r2.error?.issues });
@@ -1735,10 +1715,10 @@ const $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
1735
1715
  inst._zod.check = (payload) => {
1736
1716
  try {
1737
1717
  const trimmed = payload.value.trim();
1738
- const url = new URL(trimmed);
1718
+ const url2 = new URL(trimmed);
1739
1719
  if (def.hostname) {
1740
1720
  def.hostname.lastIndex = 0;
1741
- if (!def.hostname.test(url.hostname)) {
1721
+ if (!def.hostname.test(url2.hostname)) {
1742
1722
  payload.issues.push({
1743
1723
  code: "invalid_format",
1744
1724
  format: "url",
@@ -1752,7 +1732,7 @@ const $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
1752
1732
  }
1753
1733
  if (def.protocol) {
1754
1734
  def.protocol.lastIndex = 0;
1755
- if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) {
1735
+ if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) {
1756
1736
  payload.issues.push({
1757
1737
  code: "invalid_format",
1758
1738
  format: "url",
@@ -1765,7 +1745,7 @@ const $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
1765
1745
  }
1766
1746
  }
1767
1747
  if (def.normalize) {
1768
- payload.value = url.href;
1748
+ payload.value = url2.href;
1769
1749
  } else {
1770
1750
  payload.value = trimmed;
1771
1751
  }
@@ -3479,7 +3459,7 @@ const ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer, {
3479
3459
  });
3480
3460
  const parse$1 = /* @__PURE__ */ _parse(ZodRealError);
3481
3461
  const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
3482
- const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
3462
+ const safeParse$1 = /* @__PURE__ */ _safeParse(ZodRealError);
3483
3463
  const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
3484
3464
  const encode$1 = /* @__PURE__ */ _encode(ZodRealError);
3485
3465
  const decode$1 = /* @__PURE__ */ _decode(ZodRealError);
@@ -3509,7 +3489,7 @@ const ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
3509
3489
  return inst;
3510
3490
  });
3511
3491
  inst.parse = (data2, params) => parse$1(inst, data2, params, { callee: inst.parse });
3512
- inst.safeParse = (data2, params) => safeParse(inst, data2, params);
3492
+ inst.safeParse = (data2, params) => safeParse$1(inst, data2, params);
3513
3493
  inst.parseAsync = async (data2, params) => parseAsync(inst, data2, params, { callee: inst.parseAsync });
3514
3494
  inst.safeParseAsync = async (data2, params) => safeParseAsync(inst, data2, params);
3515
3495
  inst.spa = inst.safeParseAsync;
@@ -3637,6 +3617,9 @@ const ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
3637
3617
  $ZodURL.init(inst, def);
3638
3618
  ZodStringFormat.init(inst, def);
3639
3619
  });
3620
+ function url(params) {
3621
+ return _url$1(ZodURL, params);
3622
+ }
3640
3623
  const ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
3641
3624
  $ZodEmoji.init(inst, def);
3642
3625
  ZodStringFormat.init(inst, def);
@@ -3812,6 +3795,14 @@ function object(shape, params) {
3812
3795
  };
3813
3796
  return new ZodObject(def);
3814
3797
  }
3798
+ function looseObject(shape, params) {
3799
+ return new ZodObject({
3800
+ type: "object",
3801
+ shape,
3802
+ catchall: unknown(),
3803
+ ...normalizeParams(params)
3804
+ });
3805
+ }
3815
3806
  const ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
3816
3807
  $ZodUnion.init(inst, def);
3817
3808
  ZodType.init(inst, def);
@@ -4077,6 +4068,9 @@ function refine(fn, _params = {}) {
4077
4068
  function superRefine(fn) {
4078
4069
  return _superRefine(fn);
4079
4070
  }
4071
+ function preprocess(fn, schema2) {
4072
+ return pipe$1(transform(fn), schema2);
4073
+ }
4080
4074
  const ZodIssueCode = {
4081
4075
  custom: "custom"
4082
4076
  };
@@ -4086,13 +4080,13 @@ const JSONRPC_VERSION = "2.0";
4086
4080
  const AssertObjectSchema = custom((v2) => v2 !== null && (typeof v2 === "object" || typeof v2 === "function"));
4087
4081
  const ProgressTokenSchema = union([string(), number$1().int()]);
4088
4082
  const CursorSchema = string();
4089
- const RequestMetaSchema = object({
4083
+ const RequestMetaSchema = looseObject({
4090
4084
  /**
4091
4085
  * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.
4092
4086
  */
4093
4087
  progressToken: ProgressTokenSchema.optional()
4094
- }).passthrough();
4095
- const BaseRequestParamsSchema = object({
4088
+ });
4089
+ const BaseRequestParamsSchema = looseObject({
4096
4090
  /**
4097
4091
  * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.
4098
4092
  */
@@ -4100,9 +4094,9 @@ const BaseRequestParamsSchema = object({
4100
4094
  });
4101
4095
  const RequestSchema = object({
4102
4096
  method: string(),
4103
- params: BaseRequestParamsSchema.passthrough().optional()
4097
+ params: BaseRequestParamsSchema.optional()
4104
4098
  });
4105
- const NotificationsParamsSchema = object({
4099
+ const NotificationsParamsSchema = looseObject({
4106
4100
  /**
4107
4101
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4108
4102
  * for notes on _meta usage.
@@ -4111,24 +4105,26 @@ const NotificationsParamsSchema = object({
4111
4105
  });
4112
4106
  const NotificationSchema = object({
4113
4107
  method: string(),
4114
- params: NotificationsParamsSchema.passthrough().optional()
4108
+ params: NotificationsParamsSchema.optional()
4115
4109
  });
4116
- const ResultSchema = object({
4110
+ const ResultSchema = looseObject({
4117
4111
  /**
4118
4112
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4119
4113
  * for notes on _meta usage.
4120
4114
  */
4121
4115
  _meta: record(string(), unknown()).optional()
4122
- }).passthrough();
4116
+ });
4123
4117
  const RequestIdSchema = union([string(), number$1().int()]);
4124
4118
  const JSONRPCRequestSchema = object({
4125
4119
  jsonrpc: literal(JSONRPC_VERSION),
4126
- id: RequestIdSchema
4127
- }).merge(RequestSchema).strict();
4120
+ id: RequestIdSchema,
4121
+ ...RequestSchema.shape
4122
+ }).strict();
4128
4123
  const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;
4129
4124
  const JSONRPCNotificationSchema = object({
4130
- jsonrpc: literal(JSONRPC_VERSION)
4131
- }).merge(NotificationSchema).strict();
4125
+ jsonrpc: literal(JSONRPC_VERSION),
4126
+ ...NotificationSchema.shape
4127
+ }).strict();
4132
4128
  const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;
4133
4129
  const JSONRPCResponseSchema = object({
4134
4130
  jsonrpc: literal(JSONRPC_VERSION),
@@ -4145,6 +4141,7 @@ var ErrorCode;
4145
4141
  ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound";
4146
4142
  ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams";
4147
4143
  ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError";
4144
+ ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
4148
4145
  })(ErrorCode || (ErrorCode = {}));
4149
4146
  const JSONRPCErrorSchema = object({
4150
4147
  jsonrpc: literal(JSONRPC_VERSION),
@@ -4228,12 +4225,28 @@ const BaseMetadataSchema = object({
4228
4225
  title: string().optional()
4229
4226
  });
4230
4227
  const ImplementationSchema = BaseMetadataSchema.extend({
4228
+ ...BaseMetadataSchema.shape,
4229
+ ...IconsSchema.shape,
4231
4230
  version: string(),
4232
4231
  /**
4233
4232
  * An optional URL of the website for this implementation.
4234
4233
  */
4235
4234
  websiteUrl: string().optional()
4236
- }).merge(IconsSchema);
4235
+ });
4236
+ const FormElicitationCapabilitySchema = intersection(object({
4237
+ applyDefaults: boolean().optional()
4238
+ }), record(string(), unknown()));
4239
+ const ElicitationCapabilitySchema = preprocess((value) => {
4240
+ if (value && typeof value === "object" && !Array.isArray(value)) {
4241
+ if (Object.keys(value).length === 0) {
4242
+ return { form: {} };
4243
+ }
4244
+ }
4245
+ return value;
4246
+ }, intersection(object({
4247
+ form: FormElicitationCapabilitySchema.optional(),
4248
+ url: AssertObjectSchema.optional()
4249
+ }), record(string(), unknown()).optional()));
4237
4250
  const ClientCapabilitiesSchema = object({
4238
4251
  /**
4239
4252
  * Experimental, non-standard capabilities that the client supports.
@@ -4242,16 +4255,21 @@ const ClientCapabilitiesSchema = object({
4242
4255
  /**
4243
4256
  * Present if the client supports sampling from an LLM.
4244
4257
  */
4245
- sampling: AssertObjectSchema.optional(),
4258
+ sampling: object({
4259
+ /**
4260
+ * Present if the client supports context inclusion via includeContext parameter.
4261
+ * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it).
4262
+ */
4263
+ context: AssertObjectSchema.optional(),
4264
+ /**
4265
+ * Present if the client supports tool use via tools and toolChoice parameters.
4266
+ */
4267
+ tools: AssertObjectSchema.optional()
4268
+ }).optional(),
4246
4269
  /**
4247
4270
  * Present if the client supports eliciting user input.
4248
4271
  */
4249
- elicitation: intersection(object({
4250
- /**
4251
- * Whether the client should apply defaults to the user input.
4252
- */
4253
- applyDefaults: boolean().optional()
4254
- }).optional(), record(string(), unknown()).optional()),
4272
+ elicitation: ElicitationCapabilitySchema.optional(),
4255
4273
  /**
4256
4274
  * Present if the client supports listing roots.
4257
4275
  */
@@ -4354,7 +4372,9 @@ const ProgressSchema = object({
4354
4372
  */
4355
4373
  message: optional(string())
4356
4374
  });
4357
- const ProgressNotificationParamsSchema = NotificationsParamsSchema.merge(ProgressSchema).extend({
4375
+ const ProgressNotificationParamsSchema = object({
4376
+ ...NotificationsParamsSchema.shape,
4377
+ ...ProgressSchema.shape,
4358
4378
  /**
4359
4379
  * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
4360
4380
  */
@@ -4416,7 +4436,9 @@ const BlobResourceContentsSchema = ResourceContentsSchema.extend({
4416
4436
  */
4417
4437
  blob: Base64Schema
4418
4438
  });
4419
- const ResourceSchema = BaseMetadataSchema.extend({
4439
+ const ResourceSchema = object({
4440
+ ...BaseMetadataSchema.shape,
4441
+ ...IconsSchema.shape,
4420
4442
  /**
4421
4443
  * The URI of this resource.
4422
4444
  */
@@ -4435,9 +4457,11 @@ const ResourceSchema = BaseMetadataSchema.extend({
4435
4457
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4436
4458
  * for notes on _meta usage.
4437
4459
  */
4438
- _meta: optional(object({}).passthrough())
4439
- }).merge(IconsSchema);
4440
- const ResourceTemplateSchema = BaseMetadataSchema.extend({
4460
+ _meta: optional(looseObject({}))
4461
+ });
4462
+ const ResourceTemplateSchema = object({
4463
+ ...BaseMetadataSchema.shape,
4464
+ ...IconsSchema.shape,
4441
4465
  /**
4442
4466
  * A URI template (according to RFC 6570) that can be used to construct resource URIs.
4443
4467
  */
@@ -4456,8 +4480,8 @@ const ResourceTemplateSchema = BaseMetadataSchema.extend({
4456
4480
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4457
4481
  * for notes on _meta usage.
4458
4482
  */
4459
- _meta: optional(object({}).passthrough())
4460
- }).merge(IconsSchema);
4483
+ _meta: optional(looseObject({}))
4484
+ });
4461
4485
  const ListResourcesRequestSchema = PaginatedRequestSchema.extend({
4462
4486
  method: literal("resources/list")
4463
4487
  });
@@ -4523,7 +4547,9 @@ const PromptArgumentSchema = object({
4523
4547
  */
4524
4548
  required: optional(boolean())
4525
4549
  });
4526
- const PromptSchema = BaseMetadataSchema.extend({
4550
+ const PromptSchema = object({
4551
+ ...BaseMetadataSchema.shape,
4552
+ ...IconsSchema.shape,
4527
4553
  /**
4528
4554
  * An optional description of what this prompt provides
4529
4555
  */
@@ -4536,8 +4562,8 @@ const PromptSchema = BaseMetadataSchema.extend({
4536
4562
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4537
4563
  * for notes on _meta usage.
4538
4564
  */
4539
- _meta: optional(object({}).passthrough())
4540
- }).merge(IconsSchema);
4565
+ _meta: optional(looseObject({}))
4566
+ });
4541
4567
  const ListPromptsRequestSchema = PaginatedRequestSchema.extend({
4542
4568
  method: literal("prompts/list")
4543
4569
  });
@@ -4602,6 +4628,29 @@ const AudioContentSchema = object({
4602
4628
  */
4603
4629
  _meta: record(string(), unknown()).optional()
4604
4630
  });
4631
+ const ToolUseContentSchema = object({
4632
+ type: literal("tool_use"),
4633
+ /**
4634
+ * The name of the tool to invoke.
4635
+ * Must match a tool name from the request's tools array.
4636
+ */
4637
+ name: string(),
4638
+ /**
4639
+ * Unique identifier for this tool call.
4640
+ * Used to correlate with ToolResultContent in subsequent messages.
4641
+ */
4642
+ id: string(),
4643
+ /**
4644
+ * Arguments to pass to the tool.
4645
+ * Must conform to the tool's inputSchema.
4646
+ */
4647
+ input: object({}).passthrough(),
4648
+ /**
4649
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4650
+ * for notes on _meta usage.
4651
+ */
4652
+ _meta: optional(object({}).passthrough())
4653
+ }).passthrough();
4605
4654
  const EmbeddedResourceSchema = object({
4606
4655
  type: literal("resource"),
4607
4656
  resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
@@ -4674,32 +4723,32 @@ const ToolAnnotationsSchema = object({
4674
4723
  */
4675
4724
  openWorldHint: boolean().optional()
4676
4725
  });
4677
- const ToolSchema = BaseMetadataSchema.extend({
4726
+ const ToolSchema = object({
4727
+ ...BaseMetadataSchema.shape,
4728
+ ...IconsSchema.shape,
4678
4729
  /**
4679
4730
  * A human-readable description of the tool.
4680
4731
  */
4681
4732
  description: string().optional(),
4682
4733
  /**
4683
- * A JSON Schema object defining the expected parameters for the tool.
4734
+ * A JSON Schema 2020-12 object defining the expected parameters for the tool.
4735
+ * Must have type: 'object' at the root level per MCP spec.
4684
4736
  */
4685
4737
  inputSchema: object({
4686
4738
  type: literal("object"),
4687
4739
  properties: record(string(), AssertObjectSchema).optional(),
4688
- required: optional(array(string()))
4689
- }),
4740
+ required: array(string()).optional()
4741
+ }).catchall(unknown()),
4690
4742
  /**
4691
- * An optional JSON Schema object defining the structure of the tool's output returned in
4692
- * the structuredContent field of a CallToolResult.
4743
+ * An optional JSON Schema 2020-12 object defining the structure of the tool's output
4744
+ * returned in the structuredContent field of a CallToolResult.
4745
+ * Must have type: 'object' at the root level per MCP spec.
4693
4746
  */
4694
4747
  outputSchema: object({
4695
4748
  type: literal("object"),
4696
4749
  properties: record(string(), AssertObjectSchema).optional(),
4697
- required: optional(array(string())),
4698
- /**
4699
- * Not in the MCP specification, but added to support the Ajv validator while removing .passthrough() which previously allowed additionalProperties to be passed through.
4700
- */
4701
- additionalProperties: optional(boolean())
4702
- }).optional(),
4750
+ required: array(string()).optional()
4751
+ }).catchall(unknown()).optional(),
4703
4752
  /**
4704
4753
  * Optional additional tool information.
4705
4754
  */
@@ -4709,7 +4758,7 @@ const ToolSchema = BaseMetadataSchema.extend({
4709
4758
  * for notes on _meta usage.
4710
4759
  */
4711
4760
  _meta: record(string(), unknown()).optional()
4712
- }).merge(IconsSchema);
4761
+ });
4713
4762
  const ListToolsRequestSchema = PaginatedRequestSchema.extend({
4714
4763
  method: literal("tools/list")
4715
4764
  });
@@ -4819,10 +4868,43 @@ const ModelPreferencesSchema = object({
4819
4868
  */
4820
4869
  intelligencePriority: optional(number$1().min(0).max(1))
4821
4870
  });
4871
+ const ToolChoiceSchema = object({
4872
+ /**
4873
+ * Controls when tools are used:
4874
+ * - "auto": Model decides whether to use tools (default)
4875
+ * - "required": Model MUST use at least one tool before completing
4876
+ * - "none": Model MUST NOT use any tools
4877
+ */
4878
+ mode: optional(_enum$1(["auto", "required", "none"]))
4879
+ });
4880
+ const ToolResultContentSchema = object({
4881
+ type: literal("tool_result"),
4882
+ toolUseId: string().describe("The unique identifier for the corresponding tool call."),
4883
+ content: array(ContentBlockSchema).default([]),
4884
+ structuredContent: object({}).passthrough().optional(),
4885
+ isError: optional(boolean()),
4886
+ /**
4887
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4888
+ * for notes on _meta usage.
4889
+ */
4890
+ _meta: optional(object({}).passthrough())
4891
+ }).passthrough();
4892
+ const SamplingMessageContentBlockSchema = discriminatedUnion("type", [
4893
+ TextContentSchema,
4894
+ ImageContentSchema,
4895
+ AudioContentSchema,
4896
+ ToolUseContentSchema,
4897
+ ToolResultContentSchema
4898
+ ]);
4822
4899
  const SamplingMessageSchema = object({
4823
4900
  role: _enum$1(["user", "assistant"]),
4824
- content: union([TextContentSchema, ImageContentSchema, AudioContentSchema])
4825
- });
4901
+ content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),
4902
+ /**
4903
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
4904
+ * for notes on _meta usage.
4905
+ */
4906
+ _meta: optional(object({}).passthrough())
4907
+ }).passthrough();
4826
4908
  const CreateMessageRequestParamsSchema = BaseRequestParamsSchema.extend({
4827
4909
  messages: array(SamplingMessageSchema),
4828
4910
  /**
@@ -4834,7 +4916,11 @@ const CreateMessageRequestParamsSchema = BaseRequestParamsSchema.extend({
4834
4916
  */
4835
4917
  systemPrompt: string().optional(),
4836
4918
  /**
4837
- * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request.
4919
+ * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.
4920
+ * The client MAY ignore this request.
4921
+ *
4922
+ * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client
4923
+ * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.
4838
4924
  */
4839
4925
  includeContext: _enum$1(["none", "thisServer", "allServers"]).optional(),
4840
4926
  temperature: number$1().optional(),
@@ -4848,7 +4934,18 @@ const CreateMessageRequestParamsSchema = BaseRequestParamsSchema.extend({
4848
4934
  /**
4849
4935
  * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
4850
4936
  */
4851
- metadata: AssertObjectSchema.optional()
4937
+ metadata: AssertObjectSchema.optional(),
4938
+ /**
4939
+ * Tools that the model may use during generation.
4940
+ * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
4941
+ */
4942
+ tools: optional(array(ToolSchema)),
4943
+ /**
4944
+ * Controls how the model uses tools.
4945
+ * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
4946
+ * Default is `{ mode: "auto" }`.
4947
+ */
4948
+ toolChoice: optional(ToolChoiceSchema)
4852
4949
  });
4853
4950
  const CreateMessageRequestSchema = RequestSchema.extend({
4854
4951
  method: literal("sampling/createMessage"),
@@ -4860,11 +4957,22 @@ const CreateMessageResultSchema = ResultSchema.extend({
4860
4957
  */
4861
4958
  model: string(),
4862
4959
  /**
4863
- * The reason why sampling stopped.
4960
+ * The reason why sampling stopped, if known.
4961
+ *
4962
+ * Standard values:
4963
+ * - "endTurn": Natural end of the assistant's turn
4964
+ * - "stopSequence": A stop sequence was encountered
4965
+ * - "maxTokens": Maximum token limit was reached
4966
+ * - "toolUse": The model wants to use one or more tools
4967
+ *
4968
+ * This field is an open string to allow for provider-specific stop reasons.
4864
4969
  */
4865
- stopReason: optional(_enum$1(["endTurn", "stopSequence", "maxTokens"]).or(string())),
4970
+ stopReason: optional(_enum$1(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string())),
4866
4971
  role: _enum$1(["user", "assistant"]),
4867
- content: discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema])
4972
+ /**
4973
+ * Response content. May be ToolUseContent if stopReason is "toolUse".
4974
+ */
4975
+ content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])
4868
4976
  });
4869
4977
  const BooleanSchemaSchema = object({
4870
4978
  type: literal("boolean"),
@@ -4944,9 +5052,15 @@ const TitledMultiSelectEnumSchemaSchema = object({
4944
5052
  const MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
4945
5053
  const EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
4946
5054
  const PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
4947
- const ElicitRequestParamsSchema = BaseRequestParamsSchema.extend({
5055
+ const ElicitRequestFormParamsSchema = BaseRequestParamsSchema.extend({
4948
5056
  /**
4949
- * The message to present to the user.
5057
+ * The elicitation mode.
5058
+ *
5059
+ * Optional for backward compatibility. Clients MUST treat missing mode as "form".
5060
+ */
5061
+ mode: literal("form").optional(),
5062
+ /**
5063
+ * The message to present to the user describing what information is being requested.
4950
5064
  */
4951
5065
  message: string(),
4952
5066
  /**
@@ -4959,10 +5073,40 @@ const ElicitRequestParamsSchema = BaseRequestParamsSchema.extend({
4959
5073
  required: array(string()).optional()
4960
5074
  })
4961
5075
  });
5076
+ const ElicitRequestURLParamsSchema = BaseRequestParamsSchema.extend({
5077
+ /**
5078
+ * The elicitation mode.
5079
+ */
5080
+ mode: literal("url"),
5081
+ /**
5082
+ * The message to present to the user explaining why the interaction is needed.
5083
+ */
5084
+ message: string(),
5085
+ /**
5086
+ * The ID of the elicitation, which must be unique within the context of the server.
5087
+ * The client MUST treat this ID as an opaque value.
5088
+ */
5089
+ elicitationId: string(),
5090
+ /**
5091
+ * The URL that the user should navigate to.
5092
+ */
5093
+ url: string().url()
5094
+ });
5095
+ const ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
4962
5096
  const ElicitRequestSchema = RequestSchema.extend({
4963
5097
  method: literal("elicitation/create"),
4964
5098
  params: ElicitRequestParamsSchema
4965
5099
  });
5100
+ const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({
5101
+ /**
5102
+ * The ID of the elicitation that completed.
5103
+ */
5104
+ elicitationId: string()
5105
+ });
5106
+ const ElicitationCompleteNotificationSchema = NotificationSchema.extend({
5107
+ method: literal("notifications/elicitation/complete"),
5108
+ params: ElicitationCompleteNotificationParamsSchema
5109
+ });
4966
5110
  const ElicitResultSchema = ResultSchema.extend({
4967
5111
  /**
4968
5112
  * The user action in response to the elicitation.
@@ -4975,7 +5119,7 @@ const ElicitResultSchema = ResultSchema.extend({
4975
5119
  * The submitted form data, only present when action is "accept".
4976
5120
  * Contains values matching the requested schema.
4977
5121
  */
4978
- content: record(union([string(), number$1(), boolean(), array(string())])).optional()
5122
+ content: record(string(), union([string(), number$1(), boolean(), array(string())])).optional()
4979
5123
  });
4980
5124
  const ResourceTemplateReferenceSchema = object({
4981
5125
  type: literal("ref/resource"),
@@ -5018,7 +5162,7 @@ const CompleteRequestSchema = RequestSchema.extend({
5018
5162
  params: CompleteRequestParamsSchema
5019
5163
  });
5020
5164
  const CompleteResultSchema = ResultSchema.extend({
5021
- completion: object({
5165
+ completion: looseObject({
5022
5166
  /**
5023
5167
  * An array of completion values. Must not exceed 100 items.
5024
5168
  */
@@ -5031,7 +5175,7 @@ const CompleteResultSchema = ResultSchema.extend({
5031
5175
  * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
5032
5176
  */
5033
5177
  hasMore: optional(boolean())
5034
- }).passthrough()
5178
+ })
5035
5179
  });
5036
5180
  const RootSchema = object({
5037
5181
  /**
@@ -5087,7 +5231,8 @@ union([
5087
5231
  ResourceUpdatedNotificationSchema,
5088
5232
  ResourceListChangedNotificationSchema,
5089
5233
  ToolListChangedNotificationSchema,
5090
- PromptListChangedNotificationSchema
5234
+ PromptListChangedNotificationSchema,
5235
+ ElicitationCompleteNotificationSchema
5091
5236
  ]);
5092
5237
  union([
5093
5238
  EmptyResultSchema,
@@ -5108,6 +5253,29 @@ class McpError extends Error {
5108
5253
  this.data = data2;
5109
5254
  this.name = "McpError";
5110
5255
  }
5256
+ /**
5257
+ * Factory method to create the appropriate error type based on the error code and data
5258
+ */
5259
+ static fromError(code2, message, data2) {
5260
+ if (code2 === ErrorCode.UrlElicitationRequired && data2) {
5261
+ const errorData = data2;
5262
+ if (errorData.elicitations) {
5263
+ return new UrlElicitationRequiredError(errorData.elicitations, message);
5264
+ }
5265
+ }
5266
+ return new McpError(code2, message, data2);
5267
+ }
5268
+ }
5269
+ class UrlElicitationRequiredError extends McpError {
5270
+ constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {
5271
+ super(ErrorCode.UrlElicitationRequired, message, {
5272
+ elicitations
5273
+ });
5274
+ }
5275
+ get elicitations() {
5276
+ var _a3, _b2;
5277
+ return (_b2 = (_a3 = this.data) === null || _a3 === void 0 ? void 0 : _a3.elicitations) !== null && _b2 !== void 0 ? _b2 : [];
5278
+ }
5111
5279
  }
5112
5280
  var BaseConnector = (_c = class {
5113
5281
  client = null;
@@ -5503,6 +5671,109 @@ var BaseConnector = (_c = class {
5503
5671
  }
5504
5672
  }
5505
5673
  }, __name(_c, "BaseConnector"), _c);
5674
+ var define_process_env_default$1 = {};
5675
+ var isDeno = typeof globalThis.Deno !== "undefined";
5676
+ function getEnv(key) {
5677
+ if (isDeno) {
5678
+ return globalThis.Deno.env.get(key);
5679
+ }
5680
+ return define_process_env_default$1[key];
5681
+ }
5682
+ __name(getEnv, "getEnv");
5683
+ function getCwd() {
5684
+ if (isDeno) {
5685
+ return globalThis.Deno.cwd();
5686
+ }
5687
+ return process.cwd();
5688
+ }
5689
+ __name(getCwd, "getCwd");
5690
+ function generateUUID() {
5691
+ return globalThis.crypto.randomUUID();
5692
+ }
5693
+ __name(generateUUID, "generateUUID");
5694
+ function isZ4Schema(s2) {
5695
+ const schema2 = s2;
5696
+ return !!schema2._zod;
5697
+ }
5698
+ function safeParse(schema2, data2) {
5699
+ if (isZ4Schema(schema2)) {
5700
+ const result2 = safeParse$2(schema2, data2);
5701
+ return result2;
5702
+ }
5703
+ const v3Schema = schema2;
5704
+ const result = v3Schema.safeParse(data2);
5705
+ return result;
5706
+ }
5707
+ function getObjectShape(schema2) {
5708
+ var _a3, _b2;
5709
+ if (!schema2)
5710
+ return void 0;
5711
+ let rawShape;
5712
+ if (isZ4Schema(schema2)) {
5713
+ const v4Schema = schema2;
5714
+ rawShape = (_b2 = (_a3 = v4Schema._zod) === null || _a3 === void 0 ? void 0 : _a3.def) === null || _b2 === void 0 ? void 0 : _b2.shape;
5715
+ } else {
5716
+ const v3Schema = schema2;
5717
+ rawShape = v3Schema.shape;
5718
+ }
5719
+ if (!rawShape)
5720
+ return void 0;
5721
+ if (typeof rawShape === "function") {
5722
+ try {
5723
+ return rawShape();
5724
+ } catch (_c2) {
5725
+ return void 0;
5726
+ }
5727
+ }
5728
+ return rawShape;
5729
+ }
5730
+ function getLiteralValue(schema2) {
5731
+ var _a3;
5732
+ if (isZ4Schema(schema2)) {
5733
+ const v4Schema = schema2;
5734
+ const def2 = (_a3 = v4Schema._zod) === null || _a3 === void 0 ? void 0 : _a3.def;
5735
+ if (def2) {
5736
+ if (def2.value !== void 0)
5737
+ return def2.value;
5738
+ if (Array.isArray(def2.values) && def2.values.length > 0) {
5739
+ return def2.values[0];
5740
+ }
5741
+ }
5742
+ }
5743
+ const v3Schema = schema2;
5744
+ const def = v3Schema._def;
5745
+ if (def) {
5746
+ if (def.value !== void 0)
5747
+ return def.value;
5748
+ if (Array.isArray(def.values) && def.values.length > 0) {
5749
+ return def.values[0];
5750
+ }
5751
+ }
5752
+ const directValue = schema2.value;
5753
+ if (directValue !== void 0)
5754
+ return directValue;
5755
+ return void 0;
5756
+ }
5757
+ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
5758
+ function getMethodLiteral(schema2) {
5759
+ const shape = getObjectShape(schema2);
5760
+ const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method;
5761
+ if (!methodSchema) {
5762
+ throw new Error("Schema is missing a method literal");
5763
+ }
5764
+ const value = getLiteralValue(methodSchema);
5765
+ if (typeof value !== "string") {
5766
+ throw new Error("Schema method literal must be a string");
5767
+ }
5768
+ return value;
5769
+ }
5770
+ function parseWithCompat(schema2, data2) {
5771
+ const result = safeParse(schema2, data2);
5772
+ if (!result.success) {
5773
+ throw result.error;
5774
+ }
5775
+ return result.data;
5776
+ }
5506
5777
  const DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4;
5507
5778
  class Protocol {
5508
5779
  constructor(_options) {
@@ -5545,7 +5816,7 @@ class Protocol {
5545
5816
  const totalElapsed = Date.now() - info2.startTime;
5546
5817
  if (info2.maxTotalTimeout && totalElapsed >= info2.maxTotalTimeout) {
5547
5818
  this._timeoutInfo.delete(messageId);
5548
- throw new McpError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", {
5819
+ throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", {
5549
5820
  maxTotalTimeout: info2.maxTotalTimeout,
5550
5821
  totalElapsed
5551
5822
  });
@@ -5602,7 +5873,7 @@ class Protocol {
5602
5873
  this._pendingDebouncedNotifications.clear();
5603
5874
  this._transport = void 0;
5604
5875
  (_a3 = this.onclose) === null || _a3 === void 0 ? void 0 : _a3.call(this);
5605
- const error = new McpError(ErrorCode.ConnectionClosed, "Connection closed");
5876
+ const error = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");
5606
5877
  for (const handler of responseHandlers.values()) {
5607
5878
  handler(error);
5608
5879
  }
@@ -5665,7 +5936,8 @@ class Protocol {
5665
5936
  id: request.id,
5666
5937
  error: {
5667
5938
  code: Number.isSafeInteger(error["code"]) ? error["code"] : ErrorCode.InternalError,
5668
- message: (_a4 = error.message) !== null && _a4 !== void 0 ? _a4 : "Internal error"
5939
+ message: (_a4 = error.message) !== null && _a4 !== void 0 ? _a4 : "Internal error",
5940
+ ...error["data"] !== void 0 && { data: error["data"] }
5669
5941
  }
5670
5942
  });
5671
5943
  }).catch((error) => this._onerror(new Error(`Failed to send response: ${error}`))).finally(() => {
@@ -5705,7 +5977,7 @@ class Protocol {
5705
5977
  if (isJSONRPCResponse(response)) {
5706
5978
  handler(response);
5707
5979
  } else {
5708
- const error = new McpError(response.error.code, response.error.message, response.error.data);
5980
+ const error = McpError.fromError(response.error.code, response.error.message, response.error.data);
5709
5981
  handler(error);
5710
5982
  }
5711
5983
  }
@@ -5776,8 +6048,12 @@ class Protocol {
5776
6048
  return reject(response);
5777
6049
  }
5778
6050
  try {
5779
- const result = resultSchema.parse(response.result);
5780
- resolve2(result);
6051
+ const parseResult = safeParse(resultSchema, response.result);
6052
+ if (!parseResult.success) {
6053
+ reject(parseResult.error);
6054
+ } else {
6055
+ resolve2(parseResult.data);
6056
+ }
5781
6057
  } catch (error) {
5782
6058
  reject(error);
5783
6059
  }
@@ -5787,7 +6063,7 @@ class Protocol {
5787
6063
  cancel((_a4 = options === null || options === void 0 ? void 0 : options.signal) === null || _a4 === void 0 ? void 0 : _a4.reason);
5788
6064
  });
5789
6065
  const timeout = (_e3 = options === null || options === void 0 ? void 0 : options.timeout) !== null && _e3 !== void 0 ? _e3 : DEFAULT_REQUEST_TIMEOUT_MSEC;
5790
- const timeoutHandler = () => cancel(new McpError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));
6066
+ const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));
5791
6067
  this._setupTimeout(messageId, timeout, options === null || options === void 0 ? void 0 : options.maxTotalTimeout, timeoutHandler, (_f2 = options === null || options === void 0 ? void 0 : options.resetTimeoutOnProgress) !== null && _f2 !== void 0 ? _f2 : false);
5792
6068
  this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => {
5793
6069
  this._cleanupTimeout(messageId);
@@ -5837,10 +6113,11 @@ class Protocol {
5837
6113
  * Note that this will replace any previous request handler for the same method.
5838
6114
  */
5839
6115
  setRequestHandler(requestSchema, handler) {
5840
- const method = requestSchema.shape.method.value;
6116
+ const method = getMethodLiteral(requestSchema);
5841
6117
  this.assertRequestHandlerCapability(method);
5842
6118
  this._requestHandlers.set(method, (request, extra) => {
5843
- return Promise.resolve(handler(requestSchema.parse(request), extra));
6119
+ const parsed = parseWithCompat(requestSchema, request);
6120
+ return Promise.resolve(handler(parsed, extra));
5844
6121
  });
5845
6122
  }
5846
6123
  /**
@@ -5863,7 +6140,11 @@ class Protocol {
5863
6140
  * Note that this will replace any previous notification handler for the same method.
5864
6141
  */
5865
6142
  setNotificationHandler(notificationSchema, handler) {
5866
- this._notificationHandlers.set(notificationSchema.shape.method.value, (notification) => Promise.resolve(handler(notificationSchema.parse(notification))));
6143
+ const method = getMethodLiteral(notificationSchema);
6144
+ this._notificationHandlers.set(method, (notification) => {
6145
+ const parsed = parseWithCompat(notificationSchema, notification);
6146
+ return Promise.resolve(handler(parsed));
6147
+ });
5867
6148
  }
5868
6149
  /**
5869
6150
  * Removes the notification handler for the given method.
@@ -12618,6 +12899,16 @@ function applyElicitationDefaults(schema2, data2) {
12618
12899
  }
12619
12900
  }
12620
12901
  }
12902
+ function getSupportedElicitationModes(capabilities) {
12903
+ if (!capabilities) {
12904
+ return { supportsFormMode: false, supportsUrlMode: false };
12905
+ }
12906
+ const hasFormCapability = capabilities.form !== void 0;
12907
+ const hasUrlCapability = capabilities.url !== void 0;
12908
+ const supportsFormMode = hasFormCapability || !hasFormCapability && !hasUrlCapability;
12909
+ const supportsUrlMode = hasUrlCapability;
12910
+ return { supportsFormMode, supportsUrlMode };
12911
+ }
12621
12912
  class Client extends Protocol {
12622
12913
  /**
12623
12914
  * Initializes this client with the given name and version information.
@@ -12645,24 +12936,57 @@ class Client extends Protocol {
12645
12936
  * Override request handler registration to enforce client-side validation for elicitation.
12646
12937
  */
12647
12938
  setRequestHandler(requestSchema, handler) {
12648
- const method = requestSchema.shape.method.value;
12939
+ var _a3, _b2, _c2;
12940
+ const shape = getObjectShape(requestSchema);
12941
+ const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method;
12942
+ if (!methodSchema) {
12943
+ throw new Error("Schema is missing a method literal");
12944
+ }
12945
+ let methodValue;
12946
+ if (isZ4Schema(methodSchema)) {
12947
+ const v4Schema = methodSchema;
12948
+ const v4Def = (_a3 = v4Schema._zod) === null || _a3 === void 0 ? void 0 : _a3.def;
12949
+ methodValue = (_b2 = v4Def === null || v4Def === void 0 ? void 0 : v4Def.value) !== null && _b2 !== void 0 ? _b2 : v4Schema.value;
12950
+ } else {
12951
+ const v3Schema = methodSchema;
12952
+ const legacyDef = v3Schema._def;
12953
+ methodValue = (_c2 = legacyDef === null || legacyDef === void 0 ? void 0 : legacyDef.value) !== null && _c2 !== void 0 ? _c2 : v3Schema.value;
12954
+ }
12955
+ if (typeof methodValue !== "string") {
12956
+ throw new Error("Schema method literal must be a string");
12957
+ }
12958
+ const method = methodValue;
12649
12959
  if (method === "elicitation/create") {
12650
12960
  const wrappedHandler = async (request, extra) => {
12651
- var _a3;
12652
- const validatedRequest = ElicitRequestSchema.safeParse(request);
12961
+ var _a4, _b3, _c3;
12962
+ const validatedRequest = safeParse(ElicitRequestSchema, request);
12653
12963
  if (!validatedRequest.success) {
12654
- throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${validatedRequest.error.message}`);
12964
+ const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
12965
+ throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);
12966
+ }
12967
+ const { params } = validatedRequest.data;
12968
+ const mode = (_a4 = params.mode) !== null && _a4 !== void 0 ? _a4 : "form";
12969
+ const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);
12970
+ if (mode === "form" && !supportsFormMode) {
12971
+ throw new McpError(ErrorCode.InvalidParams, "Client does not support form-mode elicitation requests");
12972
+ }
12973
+ if (mode === "url" && !supportsUrlMode) {
12974
+ throw new McpError(ErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests");
12655
12975
  }
12656
12976
  const result = await Promise.resolve(handler(request, extra));
12657
- const validationResult = ElicitResultSchema.safeParse(result);
12977
+ const validationResult = safeParse(ElicitResultSchema, result);
12658
12978
  if (!validationResult.success) {
12659
- throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${validationResult.error.message}`);
12979
+ const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
12980
+ throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);
12660
12981
  }
12661
12982
  const validatedResult = validationResult.data;
12662
- if (((_a3 = this._capabilities.elicitation) === null || _a3 === void 0 ? void 0 : _a3.applyDefaults) && validatedResult.action === "accept" && validatedResult.content && validatedRequest.data.params.requestedSchema) {
12663
- try {
12664
- applyElicitationDefaults(validatedRequest.data.params.requestedSchema, validatedResult.content);
12665
- } catch (_b2) {
12983
+ const requestedSchema = mode === "form" ? params.requestedSchema : void 0;
12984
+ if (mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) {
12985
+ if ((_c3 = (_b3 = this._capabilities.elicitation) === null || _b3 === void 0 ? void 0 : _b3.form) === null || _c3 === void 0 ? void 0 : _c3.applyDefaults) {
12986
+ try {
12987
+ applyElicitationDefaults(requestedSchema, validatedResult.content);
12988
+ } catch (_d2) {
12989
+ }
12666
12990
  }
12667
12991
  }
12668
12992
  return validatedResult;
@@ -12878,6 +13202,31 @@ class Client extends Protocol {
12878
13202
  return this.notification({ method: "notifications/roots/list_changed" });
12879
13203
  }
12880
13204
  }
13205
+ function normalizeHeaders(headers) {
13206
+ if (!headers)
13207
+ return {};
13208
+ if (headers instanceof Headers) {
13209
+ return Object.fromEntries(headers.entries());
13210
+ }
13211
+ if (Array.isArray(headers)) {
13212
+ return Object.fromEntries(headers);
13213
+ }
13214
+ return { ...headers };
13215
+ }
13216
+ function createFetchWithInit(baseFetch = fetch, baseInit) {
13217
+ if (!baseInit) {
13218
+ return baseFetch;
13219
+ }
13220
+ return async (url2, init) => {
13221
+ const mergedInit = {
13222
+ ...baseInit,
13223
+ ...init,
13224
+ // Headers need special handling - merge instead of replace
13225
+ headers: (init === null || init === void 0 ? void 0 : init.headers) ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers
13226
+ };
13227
+ return baseFetch(url2, mergedInit);
13228
+ };
13229
+ }
12881
13230
  let crypto$1;
12882
13231
  crypto$1 = globalThis.crypto;
12883
13232
  async function getRandomValues(size2) {
@@ -12913,7 +13262,7 @@ async function pkceChallenge(length) {
12913
13262
  code_challenge: challenge
12914
13263
  };
12915
13264
  }
12916
- const SafeUrlSchema = string().url().superRefine((val, ctx) => {
13265
+ const SafeUrlSchema = url().superRefine((val, ctx) => {
12917
13266
  if (!URL.canParse(val)) {
12918
13267
  ctx.addIssue({
12919
13268
  code: ZodIssueCode.custom,
@@ -12922,11 +13271,11 @@ const SafeUrlSchema = string().url().superRefine((val, ctx) => {
12922
13271
  });
12923
13272
  return NEVER;
12924
13273
  }
12925
- }).refine((url) => {
12926
- const u2 = new URL(url);
13274
+ }).refine((url2) => {
13275
+ const u2 = new URL(url2);
12927
13276
  return u2.protocol !== "javascript:" && u2.protocol !== "data:" && u2.protocol !== "vbscript:";
12928
13277
  }, { message: "URL cannot use javascript:, data:, or vbscript: scheme" });
12929
- const OAuthProtectedResourceMetadataSchema = object({
13278
+ const OAuthProtectedResourceMetadataSchema = looseObject({
12930
13279
  resource: string().url(),
12931
13280
  authorization_servers: array(SafeUrlSchema).optional(),
12932
13281
  jwks_uri: string().url().optional(),
@@ -12941,8 +13290,8 @@ const OAuthProtectedResourceMetadataSchema = object({
12941
13290
  authorization_details_types_supported: array(string()).optional(),
12942
13291
  dpop_signing_alg_values_supported: array(string()).optional(),
12943
13292
  dpop_bound_access_tokens_required: boolean().optional()
12944
- }).passthrough();
12945
- const OAuthMetadataSchema = object({
13293
+ });
13294
+ const OAuthMetadataSchema = looseObject({
12946
13295
  issuer: string(),
12947
13296
  authorization_endpoint: SafeUrlSchema,
12948
13297
  token_endpoint: SafeUrlSchema,
@@ -12960,9 +13309,10 @@ const OAuthMetadataSchema = object({
12960
13309
  introspection_endpoint: string().optional(),
12961
13310
  introspection_endpoint_auth_methods_supported: array(string()).optional(),
12962
13311
  introspection_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
12963
- code_challenge_methods_supported: array(string()).optional()
12964
- }).passthrough();
12965
- const OpenIdProviderMetadataSchema = object({
13312
+ code_challenge_methods_supported: array(string()).optional(),
13313
+ client_id_metadata_document_supported: boolean().optional()
13314
+ });
13315
+ const OpenIdProviderMetadataSchema = looseObject({
12966
13316
  issuer: string(),
12967
13317
  authorization_endpoint: SafeUrlSchema,
12968
13318
  token_endpoint: SafeUrlSchema,
@@ -12997,11 +13347,15 @@ const OpenIdProviderMetadataSchema = object({
12997
13347
  request_uri_parameter_supported: boolean().optional(),
12998
13348
  require_request_uri_registration: boolean().optional(),
12999
13349
  op_policy_uri: SafeUrlSchema.optional(),
13000
- op_tos_uri: SafeUrlSchema.optional()
13001
- }).passthrough();
13002
- const OpenIdProviderDiscoveryMetadataSchema = OpenIdProviderMetadataSchema.merge(OAuthMetadataSchema.pick({
13003
- code_challenge_methods_supported: true
13004
- }));
13350
+ op_tos_uri: SafeUrlSchema.optional(),
13351
+ client_id_metadata_document_supported: boolean().optional()
13352
+ });
13353
+ const OpenIdProviderDiscoveryMetadataSchema = object({
13354
+ ...OpenIdProviderMetadataSchema.shape,
13355
+ ...OAuthMetadataSchema.pick({
13356
+ code_challenge_methods_supported: true
13357
+ }).shape
13358
+ });
13005
13359
  const OAuthTokensSchema = object({
13006
13360
  access_token: string(),
13007
13361
  id_token: string().optional(),
@@ -13050,8 +13404,8 @@ object({
13050
13404
  token: string(),
13051
13405
  token_type_hint: string().optional()
13052
13406
  }).strip();
13053
- function resourceUrlFromServerUrl(url) {
13054
- const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href);
13407
+ function resourceUrlFromServerUrl(url2) {
13408
+ const resourceURL = typeof url2 === "string" ? new URL(url2) : new URL(url2.href);
13055
13409
  resourceURL.hash = "";
13056
13410
  return resourceURL;
13057
13411
  }
@@ -13247,6 +13601,7 @@ async function auth(provider, options) {
13247
13601
  }
13248
13602
  }
13249
13603
  async function authInternal(provider, { serverUrl, authorizationCode, scope: scope2, resourceMetadataUrl, fetchFn }) {
13604
+ var _a3, _b2;
13250
13605
  let resourceMetadata;
13251
13606
  let authorizationServerUrl;
13252
13607
  try {
@@ -13254,7 +13609,7 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope: sco
13254
13609
  if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {
13255
13610
  authorizationServerUrl = resourceMetadata.authorization_servers[0];
13256
13611
  }
13257
- } catch (_a3) {
13612
+ } catch (_c2) {
13258
13613
  }
13259
13614
  if (!authorizationServerUrl) {
13260
13615
  authorizationServerUrl = new URL("/", serverUrl);
@@ -13268,16 +13623,29 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope: sco
13268
13623
  if (authorizationCode !== void 0) {
13269
13624
  throw new Error("Existing OAuth client information is required when exchanging an authorization code");
13270
13625
  }
13271
- if (!provider.saveClientInformation) {
13272
- throw new Error("OAuth client information must be saveable for dynamic registration");
13626
+ const supportsUrlBasedClientId = (metadata2 === null || metadata2 === void 0 ? void 0 : metadata2.client_id_metadata_document_supported) === true;
13627
+ const clientMetadataUrl = provider.clientMetadataUrl;
13628
+ if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) {
13629
+ throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);
13630
+ }
13631
+ const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;
13632
+ if (shouldUseUrlBasedClientId) {
13633
+ clientInformation = {
13634
+ client_id: clientMetadataUrl
13635
+ };
13636
+ await ((_a3 = provider.saveClientInformation) === null || _a3 === void 0 ? void 0 : _a3.call(provider, clientInformation));
13637
+ } else {
13638
+ if (!provider.saveClientInformation) {
13639
+ throw new Error("OAuth client information must be saveable for dynamic registration");
13640
+ }
13641
+ const fullInformation = await registerClient(authorizationServerUrl, {
13642
+ metadata: metadata2,
13643
+ clientMetadata: provider.clientMetadata,
13644
+ fetchFn
13645
+ });
13646
+ await provider.saveClientInformation(fullInformation);
13647
+ clientInformation = fullInformation;
13273
13648
  }
13274
- const fullInformation = await registerClient(authorizationServerUrl, {
13275
- metadata: metadata2,
13276
- clientMetadata: provider.clientMetadata,
13277
- fetchFn
13278
- });
13279
- await provider.saveClientInformation(fullInformation);
13280
- clientInformation = fullInformation;
13281
13649
  }
13282
13650
  if (authorizationCode !== void 0) {
13283
13651
  const codeVerifier2 = await provider.codeVerifier();
@@ -13320,13 +13688,23 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope: sco
13320
13688
  clientInformation,
13321
13689
  state,
13322
13690
  redirectUrl: provider.redirectUrl,
13323
- scope: scope2 || provider.clientMetadata.scope,
13691
+ scope: scope2 || ((_b2 = resourceMetadata === null || resourceMetadata === void 0 ? void 0 : resourceMetadata.scopes_supported) === null || _b2 === void 0 ? void 0 : _b2.join(" ")) || provider.clientMetadata.scope,
13324
13692
  resource
13325
13693
  });
13326
13694
  await provider.saveCodeVerifier(codeVerifier);
13327
13695
  await provider.redirectToAuthorization(authorizationUrl);
13328
13696
  return "REDIRECT";
13329
13697
  }
13698
+ function isHttpsUrl(value) {
13699
+ if (!value)
13700
+ return false;
13701
+ try {
13702
+ const url2 = new URL(value);
13703
+ return url2.protocol === "https:" && url2.pathname !== "/";
13704
+ } catch (_a3) {
13705
+ return false;
13706
+ }
13707
+ }
13330
13708
  async function selectResourceURL(serverUrl, provider, resourceMetadata) {
13331
13709
  const defaultResource = resourceUrlFromServerUrl(serverUrl);
13332
13710
  if (provider.validateResourceURL) {
@@ -13349,23 +13727,34 @@ function extractWWWAuthenticateParams(res) {
13349
13727
  if (type2.toLowerCase() !== "bearer" || !scheme) {
13350
13728
  return {};
13351
13729
  }
13352
- const resourceMetadataRegex = /resource_metadata="([^"]*)"/;
13353
- const resourceMetadataMatch = resourceMetadataRegex.exec(authenticateHeader);
13354
- const scopeRegex = /scope="([^"]*)"/;
13355
- const scopeMatch = scopeRegex.exec(authenticateHeader);
13730
+ const resourceMetadataMatch = extractFieldFromWwwAuth(res, "resource_metadata") || void 0;
13356
13731
  let resourceMetadataUrl;
13357
13732
  if (resourceMetadataMatch) {
13358
13733
  try {
13359
- resourceMetadataUrl = new URL(resourceMetadataMatch[1]);
13734
+ resourceMetadataUrl = new URL(resourceMetadataMatch);
13360
13735
  } catch (_a3) {
13361
13736
  }
13362
13737
  }
13363
- const scope2 = (scopeMatch === null || scopeMatch === void 0 ? void 0 : scopeMatch[1]) || void 0;
13738
+ const scope2 = extractFieldFromWwwAuth(res, "scope") || void 0;
13739
+ const error = extractFieldFromWwwAuth(res, "error") || void 0;
13364
13740
  return {
13365
13741
  resourceMetadataUrl,
13366
- scope: scope2
13742
+ scope: scope2,
13743
+ error
13367
13744
  };
13368
13745
  }
13746
+ function extractFieldFromWwwAuth(response, fieldName) {
13747
+ const wwwAuthHeader = response.headers.get("WWW-Authenticate");
13748
+ if (!wwwAuthHeader) {
13749
+ return null;
13750
+ }
13751
+ const pattern2 = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`);
13752
+ const match = wwwAuthHeader.match(pattern2);
13753
+ if (match) {
13754
+ return match[1] || match[2];
13755
+ }
13756
+ return null;
13757
+ }
13369
13758
  async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
13370
13759
  const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, {
13371
13760
  protocolVersion: opts === null || opts === void 0 ? void 0 : opts.protocolVersion,
@@ -13379,13 +13768,13 @@ async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn =
13379
13768
  }
13380
13769
  return OAuthProtectedResourceMetadataSchema.parse(await response.json());
13381
13770
  }
13382
- async function fetchWithCorsRetry(url, headers, fetchFn = fetch) {
13771
+ async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) {
13383
13772
  try {
13384
- return await fetchFn(url, { headers });
13773
+ return await fetchFn(url2, { headers });
13385
13774
  } catch (error) {
13386
13775
  if (error instanceof TypeError) {
13387
13776
  if (headers) {
13388
- return fetchWithCorsRetry(url, void 0, fetchFn);
13777
+ return fetchWithCorsRetry(url2, void 0, fetchFn);
13389
13778
  } else {
13390
13779
  return void 0;
13391
13780
  }
@@ -13399,11 +13788,11 @@ function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) {
13399
13788
  }
13400
13789
  return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;
13401
13790
  }
13402
- async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) {
13791
+ async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) {
13403
13792
  const headers = {
13404
13793
  "MCP-Protocol-Version": protocolVersion
13405
13794
  };
13406
- return await fetchWithCorsRetry(url, headers, fetchFn);
13795
+ return await fetchWithCorsRetry(url2, headers, fetchFn);
13407
13796
  }
13408
13797
  function shouldAttemptFallback(response, pathname) {
13409
13798
  return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
@@ -13412,15 +13801,15 @@ async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, o
13412
13801
  var _a3, _b2;
13413
13802
  const issuer = new URL(serverUrl);
13414
13803
  const protocolVersion = (_a3 = opts === null || opts === void 0 ? void 0 : opts.protocolVersion) !== null && _a3 !== void 0 ? _a3 : LATEST_PROTOCOL_VERSION;
13415
- let url;
13804
+ let url2;
13416
13805
  if (opts === null || opts === void 0 ? void 0 : opts.metadataUrl) {
13417
- url = new URL(opts.metadataUrl);
13806
+ url2 = new URL(opts.metadataUrl);
13418
13807
  } else {
13419
13808
  const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
13420
- url = new URL(wellKnownPath, (_b2 = opts === null || opts === void 0 ? void 0 : opts.metadataServerUrl) !== null && _b2 !== void 0 ? _b2 : issuer);
13421
- url.search = issuer.search;
13809
+ url2 = new URL(wellKnownPath, (_b2 = opts === null || opts === void 0 ? void 0 : opts.metadataServerUrl) !== null && _b2 !== void 0 ? _b2 : issuer);
13810
+ url2.search = issuer.search;
13422
13811
  }
13423
- let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn);
13812
+ let response = await tryMetadataDiscovery(url2, protocolVersion, fetchFn);
13424
13813
  if (!(opts === null || opts === void 0 ? void 0 : opts.metadataUrl) && shouldAttemptFallback(response, issuer.pathname)) {
13425
13814
  const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);
13426
13815
  response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);
@@ -13428,34 +13817,34 @@ async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, o
13428
13817
  return response;
13429
13818
  }
13430
13819
  function buildDiscoveryUrls(authorizationServerUrl) {
13431
- const url = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl;
13432
- const hasPath = url.pathname !== "/";
13820
+ const url2 = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl;
13821
+ const hasPath = url2.pathname !== "/";
13433
13822
  const urlsToTry = [];
13434
13823
  if (!hasPath) {
13435
13824
  urlsToTry.push({
13436
- url: new URL("/.well-known/oauth-authorization-server", url.origin),
13825
+ url: new URL("/.well-known/oauth-authorization-server", url2.origin),
13437
13826
  type: "oauth"
13438
13827
  });
13439
13828
  urlsToTry.push({
13440
- url: new URL(`/.well-known/openid-configuration`, url.origin),
13829
+ url: new URL(`/.well-known/openid-configuration`, url2.origin),
13441
13830
  type: "oidc"
13442
13831
  });
13443
13832
  return urlsToTry;
13444
13833
  }
13445
- let pathname = url.pathname;
13834
+ let pathname = url2.pathname;
13446
13835
  if (pathname.endsWith("/")) {
13447
13836
  pathname = pathname.slice(0, -1);
13448
13837
  }
13449
13838
  urlsToTry.push({
13450
- url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin),
13839
+ url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url2.origin),
13451
13840
  type: "oauth"
13452
13841
  });
13453
13842
  urlsToTry.push({
13454
- url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin),
13843
+ url: new URL(`/.well-known/openid-configuration${pathname}`, url2.origin),
13455
13844
  type: "oidc"
13456
13845
  });
13457
13846
  urlsToTry.push({
13458
- url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin),
13847
+ url: new URL(`${pathname}/.well-known/openid-configuration`, url2.origin),
13459
13848
  type: "oidc"
13460
13849
  });
13461
13850
  return urlsToTry;
@@ -13627,6 +14016,7 @@ const auth$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProper
13627
14016
  discoverOAuthProtectedResourceMetadata,
13628
14017
  exchangeAuthorization,
13629
14018
  extractWWWAuthenticateParams,
14019
+ isHttpsUrl,
13630
14020
  parseErrorResponse,
13631
14021
  refreshAuthorization,
13632
14022
  registerClient,
@@ -13770,15 +14160,16 @@ class StreamableHTTPError extends Error {
13770
14160
  }
13771
14161
  }
13772
14162
  class StreamableHTTPClientTransport {
13773
- constructor(url, opts) {
14163
+ constructor(url2, opts) {
13774
14164
  var _a3;
13775
14165
  this._hasCompletedAuthFlow = false;
13776
- this._url = url;
14166
+ this._url = url2;
13777
14167
  this._resourceMetadataUrl = void 0;
13778
14168
  this._scope = void 0;
13779
14169
  this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit;
13780
14170
  this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider;
13781
14171
  this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch;
14172
+ this._fetchWithInit = createFetchWithInit(opts === null || opts === void 0 ? void 0 : opts.fetch, opts === null || opts === void 0 ? void 0 : opts.requestInit);
13782
14173
  this._sessionId = opts === null || opts === void 0 ? void 0 : opts.sessionId;
13783
14174
  this._reconnectionOptions = (_a3 = opts === null || opts === void 0 ? void 0 : opts.reconnectionOptions) !== null && _a3 !== void 0 ? _a3 : DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
13784
14175
  }
@@ -13793,7 +14184,7 @@ class StreamableHTTPClientTransport {
13793
14184
  serverUrl: this._url,
13794
14185
  resourceMetadataUrl: this._resourceMetadataUrl,
13795
14186
  scope: this._scope,
13796
- fetchFn: this._fetch
14187
+ fetchFn: this._fetchWithInit
13797
14188
  });
13798
14189
  } catch (error) {
13799
14190
  (_a3 = this.onerror) === null || _a3 === void 0 ? void 0 : _a3.call(this, error);
@@ -13819,7 +14210,7 @@ class StreamableHTTPClientTransport {
13819
14210
  if (this._protocolVersion) {
13820
14211
  headers["mcp-protocol-version"] = this._protocolVersion;
13821
14212
  }
13822
- const extraHeaders = this._normalizeHeaders((_a3 = this._requestInit) === null || _a3 === void 0 ? void 0 : _a3.headers);
14213
+ const extraHeaders = normalizeHeaders((_a3 = this._requestInit) === null || _a3 === void 0 ? void 0 : _a3.headers);
13823
14214
  return new Headers({
13824
14215
  ...headers,
13825
14216
  ...extraHeaders
@@ -13861,24 +14252,16 @@ class StreamableHTTPClientTransport {
13861
14252
  * @returns Time to wait in milliseconds before next reconnection attempt
13862
14253
  */
13863
14254
  _getNextReconnectionDelay(attempt) {
14255
+ if (this._serverRetryMs !== void 0) {
14256
+ return this._serverRetryMs;
14257
+ }
13864
14258
  const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
13865
14259
  const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
13866
14260
  const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
13867
14261
  return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
13868
14262
  }
13869
- _normalizeHeaders(headers) {
13870
- if (!headers)
13871
- return {};
13872
- if (headers instanceof Headers) {
13873
- return Object.fromEntries(headers.entries());
13874
- }
13875
- if (Array.isArray(headers)) {
13876
- return Object.fromEntries(headers);
13877
- }
13878
- return { ...headers };
13879
- }
13880
14263
  /**
13881
- * Schedule a reconnection attempt with exponential backoff
14264
+ * Schedule a reconnection attempt using server-provided retry interval or backoff
13882
14265
  *
13883
14266
  * @param lastEventId The ID of the last received event for resumability
13884
14267
  * @param attemptCount Current reconnection attempt count for this specific stream
@@ -13905,10 +14288,15 @@ class StreamableHTTPClientTransport {
13905
14288
  }
13906
14289
  const { onresumptiontoken, replayMessageId } = options;
13907
14290
  let lastEventId;
14291
+ let hasPrimingEvent = false;
13908
14292
  const processStream = async () => {
13909
14293
  var _a3, _b2, _c2, _d2;
13910
14294
  try {
13911
- const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).getReader();
14295
+ const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({
14296
+ onRetry: (retryMs) => {
14297
+ this._serverRetryMs = retryMs;
14298
+ }
14299
+ })).getReader();
13912
14300
  while (true) {
13913
14301
  const { value: event, done } = await reader.read();
13914
14302
  if (done) {
@@ -13916,6 +14304,7 @@ class StreamableHTTPClientTransport {
13916
14304
  }
13917
14305
  if (event.id) {
13918
14306
  lastEventId = event.id;
14307
+ hasPrimingEvent = true;
13919
14308
  onresumptiontoken === null || onresumptiontoken === void 0 ? void 0 : onresumptiontoken(event.id);
13920
14309
  }
13921
14310
  if (!event.event || event.event === "message") {
@@ -13930,9 +14319,18 @@ class StreamableHTTPClientTransport {
13930
14319
  }
13931
14320
  }
13932
14321
  }
14322
+ const canResume = isReconnectable || hasPrimingEvent;
14323
+ if (canResume && this._abortController && !this._abortController.signal.aborted) {
14324
+ this._scheduleReconnection({
14325
+ resumptionToken: lastEventId,
14326
+ onresumptiontoken,
14327
+ replayMessageId
14328
+ }, 0);
14329
+ }
13933
14330
  } catch (error) {
13934
14331
  (_c2 = this.onerror) === null || _c2 === void 0 ? void 0 : _c2.call(this, new Error(`SSE stream disconnected: ${error}`));
13935
- if (isReconnectable && this._abortController && !this._abortController.signal.aborted) {
14332
+ const canResume = isReconnectable || hasPrimingEvent;
14333
+ if (canResume && this._abortController && !this._abortController.signal.aborted) {
13936
14334
  try {
13937
14335
  this._scheduleReconnection({
13938
14336
  resumptionToken: lastEventId,
@@ -13965,7 +14363,7 @@ class StreamableHTTPClientTransport {
13965
14363
  authorizationCode,
13966
14364
  resourceMetadataUrl: this._resourceMetadataUrl,
13967
14365
  scope: this._scope,
13968
- fetchFn: this._fetch
14366
+ fetchFn: this._fetchWithInit
13969
14367
  });
13970
14368
  if (result !== "AUTHORIZED") {
13971
14369
  throw new UnauthorizedError("Failed to authorize");
@@ -14014,7 +14412,7 @@ class StreamableHTTPClientTransport {
14014
14412
  serverUrl: this._url,
14015
14413
  resourceMetadataUrl: this._resourceMetadataUrl,
14016
14414
  scope: this._scope,
14017
- fetchFn: this._fetch
14415
+ fetchFn: this._fetchWithInit
14018
14416
  });
14019
14417
  if (result !== "AUTHORIZED") {
14020
14418
  throw new UnauthorizedError();
@@ -14022,10 +14420,37 @@ class StreamableHTTPClientTransport {
14022
14420
  this._hasCompletedAuthFlow = true;
14023
14421
  return this.send(message);
14024
14422
  }
14423
+ if (response.status === 403 && this._authProvider) {
14424
+ const { resourceMetadataUrl, scope: scope2, error } = extractWWWAuthenticateParams(response);
14425
+ if (error === "insufficient_scope") {
14426
+ const wwwAuthHeader = response.headers.get("WWW-Authenticate");
14427
+ if (this._lastUpscopingHeader === wwwAuthHeader) {
14428
+ throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping");
14429
+ }
14430
+ if (scope2) {
14431
+ this._scope = scope2;
14432
+ }
14433
+ if (resourceMetadataUrl) {
14434
+ this._resourceMetadataUrl = resourceMetadataUrl;
14435
+ }
14436
+ this._lastUpscopingHeader = wwwAuthHeader !== null && wwwAuthHeader !== void 0 ? wwwAuthHeader : void 0;
14437
+ const result = await auth(this._authProvider, {
14438
+ serverUrl: this._url,
14439
+ resourceMetadataUrl: this._resourceMetadataUrl,
14440
+ scope: this._scope,
14441
+ fetchFn: this._fetch
14442
+ });
14443
+ if (result !== "AUTHORIZED") {
14444
+ throw new UnauthorizedError();
14445
+ }
14446
+ return this.send(message);
14447
+ }
14448
+ }
14025
14449
  const text = await response.text().catch(() => null);
14026
14450
  throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
14027
14451
  }
14028
14452
  this._hasCompletedAuthFlow = false;
14453
+ this._lastUpscopingHeader = void 0;
14029
14454
  if (response.status === 202) {
14030
14455
  if (isInitializedNotification(message)) {
14031
14456
  this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => {
@@ -14099,6 +14524,19 @@ class StreamableHTTPClientTransport {
14099
14524
  get protocolVersion() {
14100
14525
  return this._protocolVersion;
14101
14526
  }
14527
+ /**
14528
+ * Resume an SSE stream from a previous event ID.
14529
+ * Opens a GET SSE connection with Last-Event-ID header to replay missed events.
14530
+ *
14531
+ * @param lastEventId The event ID to resume from
14532
+ * @param options Optional callback to receive new resumption tokens
14533
+ */
14534
+ async resumeStream(lastEventId, options) {
14535
+ await this._startOrAuthSse({
14536
+ resumptionToken: lastEventId,
14537
+ onresumptiontoken: options === null || options === void 0 ? void 0 : options.onresumptiontoken
14538
+ });
14539
+ }
14102
14540
  }
14103
14541
  class ErrorEvent extends Event {
14104
14542
  /**
@@ -14163,7 +14601,7 @@ var __typeError$1 = (msg) => {
14163
14601
  throw TypeError(msg);
14164
14602
  }, __accessCheck$1 = (obj, member, msg) => member.has(obj) || __typeError$1("Cannot " + msg), __privateGet$1 = (obj, member, getter) => (__accessCheck$1(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd$1 = (obj, member, value) => member.has(obj) ? __typeError$1("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value), __privateSet = (obj, member, value, setter) => (__accessCheck$1(obj, member, "write to private field"), member.set(obj, value), value), __privateMethod = (obj, member, method) => (__accessCheck$1(obj, member, "access private method"), method), _readyState, _url, _redirectUrl, _withCredentials, _fetch, _reconnectInterval, _reconnectTimer, _lastEventId, _controller, _parser, _onError, _onMessage, _onOpen, _EventSource_instances, connect_fn, _onFetchResponse, _onFetchError, getRequestOptions_fn, _onEvent, _onRetryChange, failConnection_fn, scheduleReconnect_fn, _reconnect;
14165
14603
  class EventSource extends EventTarget {
14166
- constructor(url, eventSourceInitDict) {
14604
+ constructor(url2, eventSourceInitDict) {
14167
14605
  var _a3, _b2;
14168
14606
  super(), __privateAdd$1(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd$1(this, _readyState), __privateAdd$1(this, _url), __privateAdd$1(this, _redirectUrl), __privateAdd$1(this, _withCredentials), __privateAdd$1(this, _fetch), __privateAdd$1(this, _reconnectInterval), __privateAdd$1(this, _reconnectTimer), __privateAdd$1(this, _lastEventId, null), __privateAdd$1(this, _controller), __privateAdd$1(this, _parser), __privateAdd$1(this, _onError, null), __privateAdd$1(this, _onMessage, null), __privateAdd$1(this, _onOpen, null), __privateAdd$1(this, _onFetchResponse, async (response) => {
14169
14607
  var _a22;
@@ -14211,10 +14649,10 @@ class EventSource extends EventTarget {
14211
14649
  __privateSet(this, _reconnectTimer, void 0), __privateGet$1(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this);
14212
14650
  });
14213
14651
  try {
14214
- if (url instanceof URL)
14215
- __privateSet(this, _url, url);
14216
- else if (typeof url == "string")
14217
- __privateSet(this, _url, new URL(url, getBaseURL()));
14652
+ if (url2 instanceof URL)
14653
+ __privateSet(this, _url, url2);
14654
+ else if (typeof url2 == "string")
14655
+ __privateSet(this, _url, new URL(url2, getBaseURL()));
14218
14656
  else
14219
14657
  throw new Error("Invalid URL");
14220
14658
  } catch {
@@ -14375,14 +14813,15 @@ class SseError extends Error {
14375
14813
  }
14376
14814
  }
14377
14815
  class SSEClientTransport {
14378
- constructor(url, opts) {
14379
- this._url = url;
14816
+ constructor(url2, opts) {
14817
+ this._url = url2;
14380
14818
  this._resourceMetadataUrl = void 0;
14381
14819
  this._scope = void 0;
14382
14820
  this._eventSourceInit = opts === null || opts === void 0 ? void 0 : opts.eventSourceInit;
14383
14821
  this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit;
14384
14822
  this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider;
14385
14823
  this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch;
14824
+ this._fetchWithInit = createFetchWithInit(opts === null || opts === void 0 ? void 0 : opts.fetch, opts === null || opts === void 0 ? void 0 : opts.requestInit);
14386
14825
  }
14387
14826
  async _authThenStart() {
14388
14827
  var _a3;
@@ -14395,7 +14834,7 @@ class SSEClientTransport {
14395
14834
  serverUrl: this._url,
14396
14835
  resourceMetadataUrl: this._resourceMetadataUrl,
14397
14836
  scope: this._scope,
14398
- fetchFn: this._fetch
14837
+ fetchFn: this._fetchWithInit
14399
14838
  });
14400
14839
  } catch (error) {
14401
14840
  (_a3 = this.onerror) === null || _a3 === void 0 ? void 0 : _a3.call(this, error);
@@ -14426,10 +14865,10 @@ class SSEClientTransport {
14426
14865
  return new Promise((resolve2, reject) => {
14427
14866
  this._eventSource = new EventSource(this._url.href, {
14428
14867
  ...this._eventSourceInit,
14429
- fetch: async (url, init) => {
14868
+ fetch: async (url2, init) => {
14430
14869
  const headers = await this._commonHeaders();
14431
14870
  headers.set("Accept", "text/event-stream");
14432
- const response = await fetchImpl(url, {
14871
+ const response = await fetchImpl(url2, {
14433
14872
  ...init,
14434
14873
  headers
14435
14874
  });
@@ -14502,7 +14941,7 @@ class SSEClientTransport {
14502
14941
  authorizationCode,
14503
14942
  resourceMetadataUrl: this._resourceMetadataUrl,
14504
14943
  scope: this._scope,
14505
- fetchFn: this._fetch
14944
+ fetchFn: this._fetchWithInit
14506
14945
  });
14507
14946
  if (result !== "AUTHORIZED") {
14508
14947
  throw new UnauthorizedError("Failed to authorize");
@@ -14539,7 +14978,7 @@ class SSEClientTransport {
14539
14978
  serverUrl: this._url,
14540
14979
  resourceMetadataUrl: this._resourceMetadataUrl,
14541
14980
  scope: this._scope,
14542
- fetchFn: this._fetch
14981
+ fetchFn: this._fetchWithInit
14543
14982
  });
14544
14983
  if (result !== "AUTHORIZED") {
14545
14984
  throw new UnauthorizedError();
@@ -14762,9 +15201,9 @@ var SseConnectionManager = (_f = class extends ConnectionManager {
14762
15201
  * @param url The SSE endpoint URL.
14763
15202
  * @param opts Optional transport options (auth, headers, etc.).
14764
15203
  */
14765
- constructor(url, opts) {
15204
+ constructor(url2, opts) {
14766
15205
  super();
14767
- this.url = typeof url === "string" ? new URL(url) : url;
15206
+ this.url = typeof url2 === "string" ? new URL(url2) : url2;
14768
15207
  this.opts = opts;
14769
15208
  }
14770
15209
  /**
@@ -15051,9 +15490,9 @@ var WebSocketConnectionManager = (_h = class extends ConnectionManager {
15051
15490
  * @param url The WebSocket URL to connect to.
15052
15491
  * @param headers Optional headers to include in the connection handshake.
15053
15492
  */
15054
- constructor(url, headers = {}) {
15493
+ constructor(url2, headers = {}) {
15055
15494
  super();
15056
- this.url = url;
15495
+ this.url = url2;
15057
15496
  this.headers = headers;
15058
15497
  }
15059
15498
  /** Establish a WebSocket connection and wait until it is open. */
@@ -15113,9 +15552,9 @@ var WebSocketConnector = (_i = class extends BaseConnector {
15113
15552
  receiverTask = null;
15114
15553
  pending = /* @__PURE__ */ new Map();
15115
15554
  toolsCache = null;
15116
- constructor(url, opts = {}) {
15555
+ constructor(url2, opts = {}) {
15117
15556
  super();
15118
- this.url = url;
15557
+ this.url = url2;
15119
15558
  this.headers = { ...opts.headers ?? {} };
15120
15559
  if (opts.authToken) this.headers.Authorization = `Bearer ${opts.authToken}`;
15121
15560
  }
@@ -15428,7 +15867,7 @@ var BrowserMCPClient = (_k = class extends BaseMCPClient {
15428
15867
  */
15429
15868
  createConnectorFromConfig(serverConfig) {
15430
15869
  const {
15431
- url,
15870
+ url: url2,
15432
15871
  transport,
15433
15872
  headers,
15434
15873
  authToken,
@@ -15437,7 +15876,7 @@ var BrowserMCPClient = (_k = class extends BaseMCPClient {
15437
15876
  clientOptions,
15438
15877
  samplingCallback
15439
15878
  } = serverConfig;
15440
- if (!url) {
15879
+ if (!url2) {
15441
15880
  throw new Error("Server URL is required");
15442
15881
  }
15443
15882
  const connectorOptions = {
@@ -15462,12 +15901,12 @@ var BrowserMCPClient = (_k = class extends BaseMCPClient {
15462
15901
  "[BrowserMCPClient] No clientOptions provided to connector!"
15463
15902
  );
15464
15903
  }
15465
- if (transport === "websocket" || url.startsWith("ws://") || url.startsWith("wss://")) {
15466
- return new WebSocketConnector(url, connectorOptions);
15467
- } else if (transport === "http" || url.startsWith("http://") || url.startsWith("https://")) {
15468
- return new HttpConnector(url, connectorOptions);
15904
+ if (transport === "websocket" || url2.startsWith("ws://") || url2.startsWith("wss://")) {
15905
+ return new WebSocketConnector(url2, connectorOptions);
15906
+ } else if (transport === "http" || url2.startsWith("http://") || url2.startsWith("https://")) {
15907
+ return new HttpConnector(url2, connectorOptions);
15469
15908
  } else {
15470
- return new HttpConnector(url, connectorOptions);
15909
+ return new HttpConnector(url2, connectorOptions);
15471
15910
  }
15472
15911
  }
15473
15912
  }, __name(_k, "BrowserMCPClient"), _k);
@@ -15475,20 +15914,20 @@ function sanitizeUrl(raw) {
15475
15914
  const abort = /* @__PURE__ */ __name(() => {
15476
15915
  throw new Error(`Invalid url to pass to open(): ${raw}`);
15477
15916
  }, "abort");
15478
- let url;
15917
+ let url2;
15479
15918
  try {
15480
- url = new URL(raw);
15919
+ url2 = new URL(raw);
15481
15920
  } catch (_2) {
15482
15921
  abort();
15483
15922
  }
15484
- if (url.protocol !== "https:" && url.protocol !== "http:") abort();
15485
- if (url.hostname !== encodeURIComponent(url.hostname)) abort();
15486
- if (url.username) url.username = encodeURIComponent(url.username);
15487
- if (url.password) url.password = encodeURIComponent(url.password);
15488
- url.pathname = url.pathname.slice(0, 1) + encodeURIComponent(url.pathname.slice(1)).replace(/%2f/gi, "/");
15489
- url.search = url.search.slice(0, 1) + Array.from(url.searchParams.entries()).map(sanitizeParam).join("&");
15490
- url.hash = url.hash.slice(0, 1) + encodeURIComponent(url.hash.slice(1));
15491
- return url.href;
15923
+ if (url2.protocol !== "https:" && url2.protocol !== "http:") abort();
15924
+ if (url2.hostname !== encodeURIComponent(url2.hostname)) abort();
15925
+ if (url2.username) url2.username = encodeURIComponent(url2.username);
15926
+ if (url2.password) url2.password = encodeURIComponent(url2.password);
15927
+ url2.pathname = url2.pathname.slice(0, 1) + encodeURIComponent(url2.pathname.slice(1)).replace(/%2f/gi, "/");
15928
+ url2.search = url2.search.slice(0, 1) + Array.from(url2.searchParams.entries()).map(sanitizeParam).join("&");
15929
+ url2.hash = url2.hash.slice(0, 1) + encodeURIComponent(url2.hash.slice(1));
15930
+ return url2.href;
15492
15931
  }
15493
15932
  __name(sanitizeUrl, "sanitizeUrl");
15494
15933
  function sanitizeParam([k2, v2]) {
@@ -16306,7 +16745,7 @@ var DEFAULT_RECONNECT_DELAY = 3e3;
16306
16745
  var DEFAULT_RETRY_DELAY = 5e3;
16307
16746
  function useMcp(options) {
16308
16747
  const {
16309
- url,
16748
+ url: url2,
16310
16749
  enabled = true,
16311
16750
  clientName,
16312
16751
  clientUri,
@@ -16417,7 +16856,7 @@ function useMcp(options) {
16417
16856
  [addLog]
16418
16857
  );
16419
16858
  const connect = reactExports.useCallback(async () => {
16420
- if (!enabled || !url) {
16859
+ if (!enabled || !url2) {
16421
16860
  addLog(
16422
16861
  "debug",
16423
16862
  enabled ? "No server URL provided, skipping connection." : "Connection disabled via enabled flag."
@@ -16440,10 +16879,10 @@ function useMcp(options) {
16440
16879
  setState("discovering");
16441
16880
  addLog(
16442
16881
  "info",
16443
- `Connecting attempt #${connectAttemptRef.current} to ${url}...`
16882
+ `Connecting attempt #${connectAttemptRef.current} to ${url2}...`
16444
16883
  );
16445
16884
  if (!authProviderRef.current) {
16446
- authProviderRef.current = new BrowserOAuthClientProvider(url, {
16885
+ authProviderRef.current = new BrowserOAuthClientProvider(url2, {
16447
16886
  storageKeyPrefix,
16448
16887
  clientName,
16449
16888
  clientUri,
@@ -16466,7 +16905,7 @@ function useMcp(options) {
16466
16905
  try {
16467
16906
  const serverName = "inspector-server";
16468
16907
  const serverConfig = {
16469
- url,
16908
+ url: url2,
16470
16909
  transport: transportTypeParam === "sse" ? "http" : transportTypeParam
16471
16910
  };
16472
16911
  if (customHeaders && Object.keys(customHeaders).length > 0) {
@@ -16494,9 +16933,9 @@ function useMcp(options) {
16494
16933
  "[useMcp] Applying transport wrapper for server:",
16495
16934
  serverName,
16496
16935
  "url:",
16497
- url
16936
+ url2
16498
16937
  );
16499
- return wrapTransport(transport, url);
16938
+ return wrapTransport(transport, url2);
16500
16939
  } : void 0
16501
16940
  });
16502
16941
  const session = await clientRef.current.createSession(
@@ -16550,7 +16989,7 @@ function useMcp(options) {
16550
16989
  const { auth: auth3 } = await Promise.resolve().then(() => auth$1);
16551
16990
  return { auth: auth3 };
16552
16991
  }, true ? void 0 : void 0);
16553
- const baseUrl = new URL(url).origin;
16992
+ const baseUrl = new URL(url2).origin;
16554
16993
  auth2(authProviderRef.current, { serverUrl: baseUrl }).catch(
16555
16994
  () => {
16556
16995
  }
@@ -16620,7 +17059,7 @@ function useMcp(options) {
16620
17059
  addLog,
16621
17060
  failConnection,
16622
17061
  disconnect,
16623
- url,
17062
+ url2,
16624
17063
  storageKeyPrefix,
16625
17064
  clientName,
16626
17065
  clientUri,
@@ -16688,7 +17127,7 @@ function useMcp(options) {
16688
17127
  authProviderRef.current,
16689
17128
  "Auth Provider not available for manual auth"
16690
17129
  );
16691
- assert$1(url, "Server URL is required for authentication");
17130
+ assert$1(url2, "Server URL is required for authentication");
16692
17131
  addLog("info", "Clearing all OAuth state and initiating fresh flow...");
16693
17132
  const hashPrefix = `${storageKeyPrefix}:${authProviderRef.current.serverUrlHash}`;
16694
17133
  Object.keys(localStorage).forEach((key) => {
@@ -16702,7 +17141,7 @@ function useMcp(options) {
16702
17141
  }
16703
17142
  });
16704
17143
  setState("authenticating");
16705
- const freshAuthProvider = new BrowserOAuthClientProvider(url, {
17144
+ const freshAuthProvider = new BrowserOAuthClientProvider(url2, {
16706
17145
  storageKeyPrefix,
16707
17146
  clientName,
16708
17147
  clientUri,
@@ -16718,7 +17157,7 @@ function useMcp(options) {
16718
17157
  const { auth: auth3 } = await Promise.resolve().then(() => auth$1);
16719
17158
  return { auth: auth3 };
16720
17159
  }, true ? void 0 : void 0);
16721
- const baseUrl = new URL(url).origin;
17160
+ const baseUrl = new URL(url2).origin;
16722
17161
  auth2(freshAuthProvider, {
16723
17162
  serverUrl: baseUrl
16724
17163
  }).catch((err) => {
@@ -16756,7 +17195,7 @@ function useMcp(options) {
16756
17195
  addLog,
16757
17196
  retry,
16758
17197
  authUrl,
16759
- url,
17198
+ url2,
16760
17199
  useRedirectFlow,
16761
17200
  onPopupWindow,
16762
17201
  storageKeyPrefix,
@@ -16767,13 +17206,13 @@ function useMcp(options) {
16767
17206
  const clearStorage = reactExports.useCallback(() => {
16768
17207
  if (authProviderRef.current) {
16769
17208
  const count2 = authProviderRef.current.clearStorage();
16770
- addLog("info", `Cleared ${count2} item(s) from localStorage for ${url}.`);
17209
+ addLog("info", `Cleared ${count2} item(s) from localStorage for ${url2}.`);
16771
17210
  setAuthUrl(void 0);
16772
17211
  disconnect();
16773
17212
  } else {
16774
17213
  addLog("warn", "Auth provider not initialized, cannot clear storage.");
16775
17214
  }
16776
- }, [url, addLog, disconnect]);
17215
+ }, [url2, addLog, disconnect]);
16777
17216
  const listResources = reactExports.useCallback(async () => {
16778
17217
  if (stateRef.current !== "ready" || !clientRef.current) {
16779
17218
  throw new Error(
@@ -16915,7 +17354,7 @@ function useMcp(options) {
16915
17354
  }, [addLog]);
16916
17355
  reactExports.useEffect(() => {
16917
17356
  isMountedRef.current = true;
16918
- if (!enabled || !url) {
17357
+ if (!enabled || !url2) {
16919
17358
  addLog(
16920
17359
  "debug",
16921
17360
  enabled ? "No server URL provided, skipping connection." : "Connection disabled via enabled flag."
@@ -16927,8 +17366,8 @@ function useMcp(options) {
16927
17366
  }
16928
17367
  addLog("debug", "useMcp mounted, initiating connection.");
16929
17368
  connectAttemptRef.current = 0;
16930
- if (!authProviderRef.current || authProviderRef.current.serverUrl !== url) {
16931
- authProviderRef.current = new BrowserOAuthClientProvider(url, {
17369
+ if (!authProviderRef.current || authProviderRef.current.serverUrl !== url2) {
17370
+ authProviderRef.current = new BrowserOAuthClientProvider(url2, {
16932
17371
  storageKeyPrefix,
16933
17372
  clientName,
16934
17373
  clientUri,
@@ -16949,7 +17388,7 @@ function useMcp(options) {
16949
17388
  disconnect(true);
16950
17389
  };
16951
17390
  }, [
16952
- url,
17391
+ url2,
16953
17392
  enabled,
16954
17393
  storageKeyPrefix,
16955
17394
  callbackUrl,
@@ -17730,15 +18169,11 @@ function WidgetControls({
17730
18169
  }
17731
18170
  __name(WidgetControls, "WidgetControls");
17732
18171
  var BrowserRouter$1 = null;
17733
- var routerError = null;
17734
18172
  (async () => {
17735
18173
  try {
17736
- const routerModule = await __vitePreload(() => import("./index-RN6yjAFG.js"), true ? [] : void 0);
18174
+ const routerModule = await __vitePreload(() => import("./index-UvYe4W_n.js"), true ? [] : void 0);
17737
18175
  BrowserRouter$1 = routerModule.BrowserRouter;
17738
18176
  } catch (error) {
17739
- routerError = new Error(
17740
- "❌ react-router-dom not installed!\n\nTo use MCP widgets with McpUseProvider, you need to install:\n\n npm install react-router-dom\n # or\n pnpm add react-router-dom\n\nThis dependency is automatically included in projects created with 'create-mcp-use-app'."
17741
- );
17742
18177
  }
17743
18178
  })();
17744
18179
  function getBasename() {
@@ -17764,6 +18199,33 @@ function McpUseProvider({
17764
18199
  const lastHeightRef = reactExports.useRef(0);
17765
18200
  const debounceTimeoutRef = reactExports.useRef(null);
17766
18201
  const notificationInProgressRef = reactExports.useRef(false);
18202
+ const [BrowserRouter2, setBrowserRouter] = reactExports.useState(null);
18203
+ const [routerError2, setRouterError] = reactExports.useState(null);
18204
+ const [isRouterLoading, setIsRouterLoading] = reactExports.useState(true);
18205
+ reactExports.useEffect(() => {
18206
+ let mounted = true;
18207
+ (async () => {
18208
+ try {
18209
+ const routerModule = await __vitePreload(() => import("./index-UvYe4W_n.js"), true ? [] : void 0);
18210
+ if (mounted) {
18211
+ setBrowserRouter(() => routerModule.BrowserRouter);
18212
+ setIsRouterLoading(false);
18213
+ }
18214
+ } catch (error) {
18215
+ if (mounted) {
18216
+ setRouterError(
18217
+ new Error(
18218
+ "❌ react-router-dom not installed!\n\nTo use MCP widgets with McpUseProvider, you need to install:\n\n npm install react-router-dom\n # or\n pnpm add react-router-dom\n\nThis dependency is automatically included in projects created with 'create-mcp-use-app'."
18219
+ )
18220
+ );
18221
+ setIsRouterLoading(false);
18222
+ }
18223
+ }
18224
+ })();
18225
+ return () => {
18226
+ mounted = false;
18227
+ };
18228
+ }, []);
17767
18229
  const notifyHeight = reactExports.useCallback((height) => {
17768
18230
  if (typeof window !== "undefined" && window.openai?.notifyIntrinsicHeight) {
17769
18231
  notificationInProgressRef.current = true;
@@ -17829,18 +18291,20 @@ function McpUseProvider({
17829
18291
  notificationInProgressRef.current = false;
17830
18292
  };
17831
18293
  }, [autoSize, debouncedNotifyHeight]);
18294
+ if (isRouterLoading) {
18295
+ return /* @__PURE__ */ re$1.createElement(reactExports.StrictMode, null, /* @__PURE__ */ re$1.createElement(ThemeProvider$1, null, /* @__PURE__ */ re$1.createElement("div", { style: { padding: "20px", textAlign: "center" } }, "Loading...")));
18296
+ }
18297
+ if (routerError2) {
18298
+ throw routerError2;
18299
+ }
17832
18300
  let content = children;
17833
18301
  content = /* @__PURE__ */ re$1.createElement(ErrorBoundary, null, content);
17834
18302
  if (enableDebugger || viewControls) {
17835
18303
  content = /* @__PURE__ */ re$1.createElement(WidgetControls, { debugger: enableDebugger, viewControls }, content);
17836
18304
  }
17837
- if (routerError) {
17838
- throw routerError;
17839
- }
17840
- if (!BrowserRouter$1) {
17841
- throw new Error("react-router-dom is still loading, please try again.");
18305
+ if (BrowserRouter2) {
18306
+ content = /* @__PURE__ */ re$1.createElement(BrowserRouter2, { basename }, content);
17842
18307
  }
17843
- content = /* @__PURE__ */ re$1.createElement(BrowserRouter$1, { basename }, content);
17844
18308
  content = /* @__PURE__ */ re$1.createElement(ThemeProvider$1, null, content);
17845
18309
  if (autoSize) {
17846
18310
  const containerStyle = {
@@ -18128,13 +18592,13 @@ function requireReactDom_production() {
18128
18592
  hasRequiredReactDom_production = 1;
18129
18593
  var React2 = requireReact();
18130
18594
  function formatProdErrorMessage(code2) {
18131
- var url = "https://react.dev/errors/" + code2;
18595
+ var url2 = "https://react.dev/errors/" + code2;
18132
18596
  if (1 < arguments.length) {
18133
- url += "?args[]=" + encodeURIComponent(arguments[1]);
18597
+ url2 += "?args[]=" + encodeURIComponent(arguments[1]);
18134
18598
  for (var i2 = 2; i2 < arguments.length; i2++)
18135
- url += "&args[]=" + encodeURIComponent(arguments[i2]);
18599
+ url2 += "&args[]=" + encodeURIComponent(arguments[i2]);
18136
18600
  }
18137
- return "Minified React error #" + code2 + "; visit " + url + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
18601
+ return "Minified React error #" + code2 + "; visit " + url2 + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
18138
18602
  }
18139
18603
  function noop3() {
18140
18604
  }
@@ -18295,13 +18759,13 @@ function requireReactDomClient_production() {
18295
18759
  hasRequiredReactDomClient_production = 1;
18296
18760
  var Scheduler = requireScheduler(), React2 = requireReact(), ReactDOM2 = requireReactDom();
18297
18761
  function formatProdErrorMessage(code2) {
18298
- var url = "https://react.dev/errors/" + code2;
18762
+ var url2 = "https://react.dev/errors/" + code2;
18299
18763
  if (1 < arguments.length) {
18300
- url += "?args[]=" + encodeURIComponent(arguments[1]);
18764
+ url2 += "?args[]=" + encodeURIComponent(arguments[1]);
18301
18765
  for (var i2 = 2; i2 < arguments.length; i2++)
18302
- url += "&args[]=" + encodeURIComponent(arguments[i2]);
18766
+ url2 += "&args[]=" + encodeURIComponent(arguments[i2]);
18303
18767
  }
18304
- return "Minified React error #" + code2 + "; visit " + url + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
18768
+ return "Minified React error #" + code2 + "; visit " + url2 + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
18305
18769
  }
18306
18770
  function isValidContainer(node) {
18307
18771
  return !(!node || 1 !== node.nodeType && 9 !== node.nodeType && 11 !== node.nodeType);
@@ -19329,8 +19793,8 @@ function requireReactDomClient_production() {
19329
19793
  ["xmlnsXlink", "xmlns:xlink"],
19330
19794
  ["xHeight", "x-height"]
19331
19795
  ]), isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;
19332
- function sanitizeURL(url) {
19333
- return isJavaScriptProtocol.test("" + url) ? "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')" : url;
19796
+ function sanitizeURL(url2) {
19797
+ return isJavaScriptProtocol.test("" + url2) ? "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')" : url2;
19334
19798
  }
19335
19799
  function noop$12() {
19336
19800
  }
@@ -29980,9 +30444,9 @@ function createHashHistory(options = {}) {
29980
30444
  let base = window2.document.querySelector("base");
29981
30445
  let href = "";
29982
30446
  if (base && base.getAttribute("href")) {
29983
- let url = window2.location.href;
29984
- let hashIndex = url.indexOf("#");
29985
- href = hashIndex === -1 ? url : url.slice(0, hashIndex);
30447
+ let url2 = window2.location.href;
30448
+ let hashIndex = url2.indexOf("#");
30449
+ href = hashIndex === -1 ? url2 : url2.slice(0, hashIndex);
29986
30450
  }
29987
30451
  return href + "#" + (typeof to === "string" ? to : createPath(to));
29988
30452
  }
@@ -30099,14 +30563,14 @@ function getUrlBasedHistory(getLocation, createHref2, validateLocation, options
30099
30563
  if (validateLocation) validateLocation(location, to);
30100
30564
  index2 = getIndex() + 1;
30101
30565
  let historyState = getHistoryState(location, index2);
30102
- let url = history.createHref(location);
30566
+ let url2 = history.createHref(location);
30103
30567
  try {
30104
- globalHistory.pushState(historyState, "", url);
30568
+ globalHistory.pushState(historyState, "", url2);
30105
30569
  } catch (error) {
30106
30570
  if (error instanceof DOMException && error.name === "DataCloneError") {
30107
30571
  throw error;
30108
30572
  }
30109
- window2.location.assign(url);
30573
+ window2.location.assign(url2);
30110
30574
  }
30111
30575
  if (v5Compat && listener) {
30112
30576
  listener({ action, location: history.location, delta: 1 });
@@ -30118,8 +30582,8 @@ function getUrlBasedHistory(getLocation, createHref2, validateLocation, options
30118
30582
  if (validateLocation) validateLocation(location, to);
30119
30583
  index2 = getIndex();
30120
30584
  let historyState = getHistoryState(location, index2);
30121
- let url = history.createHref(location);
30122
- globalHistory.replaceState(historyState, "", url);
30585
+ let url2 = history.createHref(location);
30586
+ globalHistory.replaceState(historyState, "", url2);
30123
30587
  if (v5Compat && listener) {
30124
30588
  listener({ action, location: history.location, delta: 0 });
30125
30589
  }
@@ -30150,11 +30614,11 @@ function getUrlBasedHistory(getLocation, createHref2, validateLocation, options
30150
30614
  },
30151
30615
  createURL,
30152
30616
  encodeLocation(to) {
30153
- let url = createURL(to);
30617
+ let url2 = createURL(to);
30154
30618
  return {
30155
- pathname: url.pathname,
30156
- search: url.search,
30157
- hash: url.hash
30619
+ pathname: url2.pathname,
30620
+ search: url2.search,
30621
+ hash: url2.hash
30158
30622
  };
30159
30623
  },
30160
30624
  push,
@@ -30728,7 +31192,7 @@ function data(data2, init) {
30728
31192
  typeof init === "number" ? { status: init } : init
30729
31193
  );
30730
31194
  }
30731
- var redirect = (url, init = 302) => {
31195
+ var redirect = (url2, init = 302) => {
30732
31196
  let responseInit = init;
30733
31197
  if (typeof responseInit === "number") {
30734
31198
  responseInit = { status: responseInit };
@@ -30736,16 +31200,16 @@ var redirect = (url, init = 302) => {
30736
31200
  responseInit.status = 302;
30737
31201
  }
30738
31202
  let headers = new Headers(responseInit.headers);
30739
- headers.set("Location", url);
31203
+ headers.set("Location", url2);
30740
31204
  return new Response(null, { ...responseInit, headers });
30741
31205
  };
30742
- var redirectDocument = (url, init) => {
30743
- let response = redirect(url, init);
31206
+ var redirectDocument = (url2, init) => {
31207
+ let response = redirect(url2, init);
30744
31208
  response.headers.set("X-Remix-Reload-Document", "true");
30745
31209
  return response;
30746
31210
  };
30747
- var replace = (url, init) => {
30748
- let response = redirect(url, init);
31211
+ var replace = (url2, init) => {
31212
+ let response = redirect(url2, init);
30749
31213
  response.headers.set("X-Remix-Replace", "true");
30750
31214
  return response;
30751
31215
  };
@@ -31077,7 +31541,7 @@ var IDLE_BLOCKER = {
31077
31541
  location: void 0
31078
31542
  };
31079
31543
  var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
31080
- var isAbsoluteUrl = (url) => ABSOLUTE_URL_REGEX.test(url);
31544
+ var isAbsoluteUrl = (url2) => ABSOLUTE_URL_REGEX.test(url2);
31081
31545
  var defaultMapRouteProperties = (route) => ({
31082
31546
  hasErrorBoundary: Boolean(route.hasErrorBoundary)
31083
31547
  });
@@ -32384,10 +32848,10 @@ function createRouter(init) {
32384
32848
  if (redirect2.response.headers.has("X-Remix-Reload-Document")) {
32385
32849
  isDocumentReload = true;
32386
32850
  } else if (isAbsoluteUrl(location)) {
32387
- const url = createBrowserURLImpl(location, true);
32851
+ const url2 = createBrowserURLImpl(location, true);
32388
32852
  isDocumentReload = // Hard reload if it's an absolute URL to a new origin
32389
- url.origin !== routerWindow.location.origin || // Hard reload if it's an absolute URL that does not match our basename
32390
- stripBasename(url.pathname, basename) == null;
32853
+ url2.origin !== routerWindow.location.origin || // Hard reload if it's an absolute URL that does not match our basename
32854
+ stripBasename(url2.pathname, basename) == null;
32391
32855
  }
32392
32856
  if (isDocumentReload) {
32393
32857
  if (replace2) {
@@ -32899,9 +33363,9 @@ function createStaticHandler(routes, opts) {
32899
33363
  dataStrategy,
32900
33364
  generateMiddlewareResponse
32901
33365
  } = {}) {
32902
- let url = new URL(request.url);
33366
+ let url2 = new URL(request.url);
32903
33367
  let method = request.method;
32904
- let location = createLocation("", createPath(url), null, "default");
33368
+ let location = createLocation("", createPath(url2), null, "default");
32905
33369
  let matches = matchRoutes(dataRoutes, location, basename);
32906
33370
  requestContext = requestContext != null ? requestContext : new RouterContextProvider();
32907
33371
  if (!isValidMethod(method) && method !== "HEAD") {
@@ -33072,9 +33536,9 @@ function createStaticHandler(routes, opts) {
33072
33536
  dataStrategy,
33073
33537
  generateMiddlewareResponse
33074
33538
  } = {}) {
33075
- let url = new URL(request.url);
33539
+ let url2 = new URL(request.url);
33076
33540
  let method = request.method;
33077
- let location = createLocation("", createPath(url), null, "default");
33541
+ let location = createLocation("", createPath(url2), null, "default");
33078
33542
  let matches = matchRoutes(dataRoutes, location, basename);
33079
33543
  requestContext = requestContext != null ? requestContext : new RouterContextProvider();
33080
33544
  if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
@@ -34456,8 +34920,8 @@ async function callLoaderOrAction({
34456
34920
  if (handler2) {
34457
34921
  [result] = await Promise.all([runHandler(handler2), lazyRoutePromise]);
34458
34922
  } else if (type2 === "action") {
34459
- let url = new URL(request.url);
34460
- let pathname = url.pathname + url.search;
34923
+ let url2 = new URL(request.url);
34924
+ let pathname = url2.pathname + url2.search;
34461
34925
  throw getInternalRouterError(405, {
34462
34926
  method: request.method,
34463
34927
  pathname,
@@ -34468,8 +34932,8 @@ async function callLoaderOrAction({
34468
34932
  }
34469
34933
  }
34470
34934
  } else if (!handler) {
34471
- let url = new URL(request.url);
34472
- let pathname = url.pathname + url.search;
34935
+ let url2 = new URL(request.url);
34936
+ let pathname = url2.pathname + url2.search;
34473
34937
  throw getInternalRouterError(404, {
34474
34938
  pathname
34475
34939
  });
@@ -34577,16 +35041,16 @@ function normalizeRelativeRoutingRedirectResponse(response, request, routeId, ma
34577
35041
  function normalizeRedirectLocation(location, currentUrl, basename) {
34578
35042
  if (isAbsoluteUrl(location)) {
34579
35043
  let normalizedLocation = location;
34580
- let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);
34581
- let isSameBasename = stripBasename(url.pathname, basename) != null;
34582
- if (url.origin === currentUrl.origin && isSameBasename) {
34583
- return url.pathname + url.search + url.hash;
35044
+ let url2 = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);
35045
+ let isSameBasename = stripBasename(url2.pathname, basename) != null;
35046
+ if (url2.origin === currentUrl.origin && isSameBasename) {
35047
+ return url2.pathname + url2.search + url2.hash;
34584
35048
  }
34585
35049
  }
34586
35050
  return location;
34587
35051
  }
34588
35052
  function createClientSideRequest(history, location, signal, submission) {
34589
- let url = history.createURL(stripHashFromPath(location)).toString();
35053
+ let url2 = history.createURL(stripHashFromPath(location)).toString();
34590
35054
  let init = { signal };
34591
35055
  if (submission && isMutationMethod(submission.formMethod)) {
34592
35056
  let { formMethod, formEncType } = submission;
@@ -34602,7 +35066,7 @@ function createClientSideRequest(history, location, signal, submission) {
34602
35066
  init.body = submission.formData;
34603
35067
  }
34604
35068
  }
34605
- return new Request(url, init);
35069
+ return new Request(url2, init);
34606
35070
  }
34607
35071
  function convertFormDataToSearchParams(formData) {
34608
35072
  let searchParams = new URLSearchParams();
@@ -37496,9 +37960,9 @@ async function singleFetchLoaderFetcherStrategy(args, fetchAndDecode, basename)
37496
37960
  );
37497
37961
  return { [fetcherMatch.route.id]: result };
37498
37962
  }
37499
- function stripIndexParam(url) {
37500
- let indexValues = url.searchParams.getAll("index");
37501
- url.searchParams.delete("index");
37963
+ function stripIndexParam(url2) {
37964
+ let indexValues = url2.searchParams.getAll("index");
37965
+ url2.searchParams.delete("index");
37502
37966
  let indexValuesToKeep = [];
37503
37967
  for (let indexValue of indexValues) {
37504
37968
  if (indexValue) {
@@ -37506,36 +37970,36 @@ function stripIndexParam(url) {
37506
37970
  }
37507
37971
  }
37508
37972
  for (let toKeep of indexValuesToKeep) {
37509
- url.searchParams.append("index", toKeep);
37973
+ url2.searchParams.append("index", toKeep);
37510
37974
  }
37511
- return url;
37975
+ return url2;
37512
37976
  }
37513
37977
  function singleFetchUrl(reqUrl, basename, extension) {
37514
- let url = typeof reqUrl === "string" ? new URL(
37978
+ let url2 = typeof reqUrl === "string" ? new URL(
37515
37979
  reqUrl,
37516
37980
  // This can be called during the SSR flow via PrefetchPageLinksImpl so
37517
37981
  // don't assume window is available
37518
37982
  typeof window === "undefined" ? "server://singlefetch/" : window.location.origin
37519
37983
  ) : reqUrl;
37520
- if (url.pathname === "/") {
37521
- url.pathname = `_root.${extension}`;
37522
- } else if (basename && stripBasename(url.pathname, basename) === "/") {
37523
- url.pathname = `${basename.replace(/\/$/, "")}/_root.${extension}`;
37984
+ if (url2.pathname === "/") {
37985
+ url2.pathname = `_root.${extension}`;
37986
+ } else if (basename && stripBasename(url2.pathname, basename) === "/") {
37987
+ url2.pathname = `${basename.replace(/\/$/, "")}/_root.${extension}`;
37524
37988
  } else {
37525
- url.pathname = `${url.pathname.replace(/\/$/, "")}.${extension}`;
37989
+ url2.pathname = `${url2.pathname.replace(/\/$/, "")}.${extension}`;
37526
37990
  }
37527
- return url;
37991
+ return url2;
37528
37992
  }
37529
37993
  async function fetchAndDecodeViaTurboStream(args, basename, targetRoutes) {
37530
37994
  let { request } = args;
37531
- let url = singleFetchUrl(request.url, basename, "data");
37995
+ let url2 = singleFetchUrl(request.url, basename, "data");
37532
37996
  if (request.method === "GET") {
37533
- url = stripIndexParam(url);
37997
+ url2 = stripIndexParam(url2);
37534
37998
  if (targetRoutes) {
37535
- url.searchParams.set("_routes", targetRoutes.join(","));
37999
+ url2.searchParams.set("_routes", targetRoutes.join(","));
37536
38000
  }
37537
38001
  }
37538
- let res = await fetch(url, await createRequestInit(request));
38002
+ let res = await fetch(url2, await createRequestInit(request));
37539
38003
  if (res.status >= 400 && !res.headers.has("X-Remix-Response")) {
37540
38004
  throw new ErrorResponseImpl(res.status, res.statusText, await res.text());
37541
38005
  }
@@ -38449,18 +38913,18 @@ async function fetchAndApplyManifestPatches(paths, errorReloadPath, manifest, ro
38449
38913
  const searchParams = new URLSearchParams();
38450
38914
  searchParams.set("paths", paths.sort().join(","));
38451
38915
  searchParams.set("version", manifest.version);
38452
- let url = new URL(
38916
+ let url2 = new URL(
38453
38917
  getManifestPath(manifestPath, basename),
38454
38918
  window.location.origin
38455
38919
  );
38456
- url.search = searchParams.toString();
38457
- if (url.toString().length > URL_LIMIT) {
38920
+ url2.search = searchParams.toString();
38921
+ if (url2.toString().length > URL_LIMIT) {
38458
38922
  nextPaths.clear();
38459
38923
  return;
38460
38924
  }
38461
38925
  let serverPatches;
38462
38926
  try {
38463
- let res = await fetch(url, { signal });
38927
+ let res = await fetch(url2, { signal });
38464
38928
  if (!res.ok) {
38465
38929
  throw new Error(`${res.status} ${res.statusText}`);
38466
38930
  } else if (res.status === 204 && res.headers.has("X-Remix-Reload-Document")) {
@@ -38743,14 +39207,14 @@ function PrefetchPageLinksImpl({
38743
39207
  if (routesParams.size === 0) {
38744
39208
  return [];
38745
39209
  }
38746
- let url = singleFetchUrl(page, basename, "data");
39210
+ let url2 = singleFetchUrl(page, basename, "data");
38747
39211
  if (foundOptOutRoute && routesParams.size > 0) {
38748
- url.searchParams.set(
39212
+ url2.searchParams.set(
38749
39213
  "_routes",
38750
39214
  nextMatches.filter((m2) => routesParams.has(m2.route.id)).map((m2) => m2.route.id).join(",")
38751
39215
  );
38752
39216
  }
38753
- return [url.pathname + url.search];
39217
+ return [url2.pathname + url2.search];
38754
39218
  }, [
38755
39219
  basename,
38756
39220
  loaderData,
@@ -49745,7 +50209,7 @@ class MCPToolSavedEvent {
49745
50209
  function getPackageVersion() {
49746
50210
  try {
49747
50211
  if (true) {
49748
- return "0.9.0-canary.2";
50212
+ return "0.9.0-canary.3";
49749
50213
  }
49750
50214
  return "0.0.0";
49751
50215
  } catch {
@@ -49987,7 +50451,7 @@ function useMcpContext() {
49987
50451
  return context;
49988
50452
  }
49989
50453
  function McpConnectionWrapper({
49990
- url,
50454
+ url: url2,
49991
50455
  name,
49992
50456
  proxyConfig,
49993
50457
  transportType,
@@ -49996,13 +50460,13 @@ function McpConnectionWrapper({
49996
50460
  onRemove: _onRemove
49997
50461
  }) {
49998
50462
  const callbackUrl = typeof window !== "undefined" ? new URL("/inspector/oauth/callback", window.location.origin).toString() : "/inspector/oauth/callback";
49999
- let finalUrl = url;
50463
+ let finalUrl = url2;
50000
50464
  let customHeaders = {};
50001
50465
  if (proxyConfig?.proxyAddress) {
50002
50466
  const proxyUrl = new URL(proxyConfig.proxyAddress);
50003
- const originalUrl = new URL(url);
50467
+ const originalUrl = new URL(url2);
50004
50468
  finalUrl = `${proxyUrl.origin}${proxyUrl.pathname}${originalUrl.pathname}${originalUrl.search}`;
50005
- customHeaders["X-Target-URL"] = url;
50469
+ customHeaders["X-Target-URL"] = url2;
50006
50470
  }
50007
50471
  if (proxyConfig?.customHeaders) {
50008
50472
  customHeaders = { ...customHeaders, ...proxyConfig.customHeaders };
@@ -50126,7 +50590,7 @@ function McpConnectionWrapper({
50126
50590
  const unreadCount = notifications.filter((n2) => !n2.read).length;
50127
50591
  const connection = {
50128
50592
  id: connectionId,
50129
- url,
50593
+ url: url2,
50130
50594
  name: mcpHook.serverInfo?.name || name,
50131
50595
  // Use server-provided name if available
50132
50596
  state: mcpHook.state,
@@ -50165,7 +50629,7 @@ function McpConnectionWrapper({
50165
50629
  const unreadCount = notifications.filter((n2) => !n2.read).length;
50166
50630
  const connection = {
50167
50631
  id: connectionId,
50168
- url,
50632
+ url: url2,
50169
50633
  name: mcpHook.serverInfo?.name || name,
50170
50634
  // Use server-provided name if available
50171
50635
  state: mcpHook.state,
@@ -50201,7 +50665,7 @@ function McpConnectionWrapper({
50201
50665
  }
50202
50666
  }
50203
50667
  }, [
50204
- url,
50668
+ url2,
50205
50669
  name,
50206
50670
  transportType,
50207
50671
  proxyConfig,
@@ -50311,18 +50775,18 @@ function McpProvider({ children }) {
50311
50775
  localStorage.setItem("mcp-inspector-auto-connect", String(autoConnect));
50312
50776
  }, [autoConnect, configLoaded]);
50313
50777
  const addConnection = reactExports.useCallback(
50314
- (url, name, proxyConfig, transportType) => {
50315
- const existingConfig = connectionConfigs.find((c2) => c2.url === url);
50316
- const existingConnection = connections.find((c2) => c2.url === url);
50778
+ (url2, name, proxyConfig, transportType) => {
50779
+ const existingConfig = connectionConfigs.find((c2) => c2.url === url2);
50780
+ const existingConnection = connections.find((c2) => c2.url === url2);
50317
50781
  if (existingConfig && existingConnection) {
50318
50782
  const proxyConfigChanged = JSON.stringify(existingConfig.proxyConfig) !== JSON.stringify(proxyConfig);
50319
50783
  if (proxyConfigChanged && proxyConfig) {
50320
- setConnectionConfigs((prev) => prev.filter((c2) => c2.url !== url));
50321
- setConnections((prev) => prev.filter((c2) => c2.url !== url));
50784
+ setConnectionConfigs((prev) => prev.filter((c2) => c2.url !== url2));
50785
+ setConnections((prev) => prev.filter((c2) => c2.url !== url2));
50322
50786
  setTimeout(() => {
50323
50787
  const newConfig2 = {
50324
- id: url,
50325
- url,
50788
+ id: url2,
50789
+ url: url2,
50326
50790
  name: name || existingConfig.name || "MCP Server",
50327
50791
  proxyConfig,
50328
50792
  transportType: transportType || existingConfig.transportType
@@ -50331,8 +50795,8 @@ function McpProvider({ children }) {
50331
50795
  setConnections((prev) => [
50332
50796
  ...prev,
50333
50797
  {
50334
- id: url,
50335
- url,
50798
+ id: url2,
50799
+ url: url2,
50336
50800
  name: name || existingConfig.name || "MCP Server",
50337
50801
  state: "connecting",
50338
50802
  tools: [],
@@ -50379,7 +50843,7 @@ function McpProvider({ children }) {
50379
50843
  if (proxyConfig || transportType) {
50380
50844
  setConnectionConfigs(
50381
50845
  (prev) => prev.map(
50382
- (c2) => c2.url === url ? {
50846
+ (c2) => c2.url === url2 ? {
50383
50847
  ...c2,
50384
50848
  proxyConfig: proxyConfig || c2.proxyConfig,
50385
50849
  transportType: transportType || c2.transportType,
@@ -50391,8 +50855,8 @@ function McpProvider({ children }) {
50391
50855
  setConnections((prev) => [
50392
50856
  ...prev,
50393
50857
  {
50394
- id: existingConfig.id || url,
50395
- url,
50858
+ id: existingConfig.id || url2,
50859
+ url: url2,
50396
50860
  name: name || existingConfig.name || "MCP Server",
50397
50861
  state: "connecting",
50398
50862
  tools: [],
@@ -50433,8 +50897,8 @@ function McpProvider({ children }) {
50433
50897
  return;
50434
50898
  }
50435
50899
  const newConfig = {
50436
- id: url,
50437
- url,
50900
+ id: url2,
50901
+ url: url2,
50438
50902
  name: name || "MCP Server",
50439
50903
  proxyConfig,
50440
50904
  transportType
@@ -50443,8 +50907,8 @@ function McpProvider({ children }) {
50443
50907
  setConnections((prev) => [
50444
50908
  ...prev,
50445
50909
  {
50446
- id: url,
50447
- url,
50910
+ id: url2,
50911
+ url: url2,
50448
50912
  name: name || "MCP Server",
50449
50913
  state: "connecting",
50450
50914
  tools: [],
@@ -54063,7 +54527,7 @@ function CustomHeadersEditor({
54063
54527
  function ConnectionSettingsForm({
54064
54528
  transportType,
54065
54529
  setTransportType,
54066
- url,
54530
+ url: url2,
54067
54531
  setUrl,
54068
54532
  connectionType,
54069
54533
  setConnectionType,
@@ -54098,12 +54562,12 @@ function ConnectionSettingsForm({
54098
54562
  const [authDialogOpen, setAuthDialogOpen] = reactExports.useState(false);
54099
54563
  const [configDialogOpen, setConfigDialogOpen] = reactExports.useState(false);
54100
54564
  const handleCopyConfig = async () => {
54101
- if (!url.trim()) {
54565
+ if (!url2.trim()) {
54102
54566
  toast.error("Please enter a URL first");
54103
54567
  return;
54104
54568
  }
54105
54569
  const config2 = {
54106
- url,
54570
+ url: url2,
54107
54571
  transportType: transportType === "SSE" ? "http" : "sse",
54108
54572
  connectionType,
54109
54573
  proxyConfig: connectionType === "Via Proxy" && proxyAddress.trim() ? {
@@ -54202,7 +54666,7 @@ function ConnectionSettingsForm({
54202
54666
  const target = e.target;
54203
54667
  if (target.tagName !== "TEXTAREA") {
54204
54668
  e.preventDefault();
54205
- if (onConnect && url.trim()) {
54669
+ if (onConnect && url2.trim()) {
54206
54670
  onConnect();
54207
54671
  }
54208
54672
  }
@@ -54241,7 +54705,7 @@ function ConnectionSettingsForm({
54241
54705
  Input,
54242
54706
  {
54243
54707
  placeholder: "http://localhost:3001/sse",
54244
- value: url,
54708
+ value: url2,
54245
54709
  onChange: (e) => setUrl(e.target.value),
54246
54710
  onPaste: handlePaste,
54247
54711
  className: inputClassName
@@ -54471,7 +54935,7 @@ function ConnectionSettingsForm({
54471
54935
  Button,
54472
54936
  {
54473
54937
  onClick: onConnect,
54474
- disabled: !url.trim() || isConnecting,
54938
+ disabled: !url2.trim() || isConnecting,
54475
54939
  className: cn$1(
54476
54940
  "w-full font-semibold",
54477
54941
  isStyled ? "bg-white text-black hover:bg-white/90" : ""
@@ -54532,7 +54996,7 @@ function ServerConnectionModal({
54532
54996
  onConnect
54533
54997
  }) {
54534
54998
  const [transportType, setTransportType] = reactExports.useState("SSE");
54535
- const [url, setUrl] = reactExports.useState("");
54999
+ const [url2, setUrl] = reactExports.useState("");
54536
55000
  const [connectionType, setConnectionType] = reactExports.useState("Direct");
54537
55001
  const [customHeaders, setCustomHeaders] = reactExports.useState([]);
54538
55002
  const [requestTimeout, setRequestTimeout] = reactExports.useState("10000");
@@ -54573,7 +55037,7 @@ function ServerConnectionModal({
54573
55037
  }
54574
55038
  }, [connection, open]);
54575
55039
  const handleConnect = () => {
54576
- if (!url.trim()) return;
55040
+ if (!url2.trim()) return;
54577
55041
  const proxyConfig = connectionType === "Via Proxy" && proxyAddress.trim() ? {
54578
55042
  proxyAddress: proxyAddress.trim(),
54579
55043
  customHeaders: customHeaders.reduce(
@@ -54598,7 +55062,7 @@ function ServerConnectionModal({
54598
55062
  };
54599
55063
  const actualTransportType = transportType === "SSE" ? "http" : "sse";
54600
55064
  onConnect({
54601
- url,
55065
+ url: url2,
54602
55066
  name: connection?.name,
54603
55067
  transportType: actualTransportType,
54604
55068
  proxyConfig
@@ -54612,7 +55076,7 @@ function ServerConnectionModal({
54612
55076
  {
54613
55077
  transportType,
54614
55078
  setTransportType,
54615
- url,
55079
+ url: url2,
54616
55080
  setUrl,
54617
55081
  connectionType,
54618
55082
  setConnectionType,
@@ -62145,8 +62609,8 @@ function getCachedFavicon(domain) {
62145
62609
  }
62146
62610
  return null;
62147
62611
  }
62148
- async function fetchAndCacheImage(url, domain) {
62149
- const response = await fetch(url);
62612
+ async function fetchAndCacheImage(url2, domain) {
62613
+ const response = await fetch(url2);
62150
62614
  const blob = await response.blob();
62151
62615
  return new Promise((resolve2, reject) => {
62152
62616
  const reader = new FileReader();
@@ -62404,7 +62868,7 @@ function InspectorDashboard() {
62404
62868
  });
62405
62869
  }, []);
62406
62870
  const [transportType, setTransportType] = reactExports.useState("SSE");
62407
- const [url, setUrl] = reactExports.useState("");
62871
+ const [url2, setUrl] = reactExports.useState("");
62408
62872
  const [connectionType, setConnectionType] = reactExports.useState("Direct");
62409
62873
  const [customHeaders, setCustomHeaders] = reactExports.useState([]);
62410
62874
  const [requestTimeout, setRequestTimeout] = reactExports.useState("10000");
@@ -62431,7 +62895,7 @@ function InspectorDashboard() {
62431
62895
  }, []);
62432
62896
  const handleAddConnection = reactExports.useCallback(
62433
62897
  (isRetry = false, overrideConnectionType) => {
62434
- if (!url.trim()) return;
62898
+ if (!url2.trim()) return;
62435
62899
  setIsConnecting(true);
62436
62900
  hasShownToastRef.current = false;
62437
62901
  if (!isRetry) {
@@ -62462,13 +62926,13 @@ function InspectorDashboard() {
62462
62926
  };
62463
62927
  const actualTransportType = transportType === "SSE" ? "http" : "sse";
62464
62928
  setPendingConnectionConfig({
62465
- url,
62466
- name: url,
62929
+ url: url2,
62930
+ name: url2,
62467
62931
  proxyConfig,
62468
62932
  transportType: actualTransportType
62469
62933
  });
62470
62934
  },
62471
- [url, connectionType, proxyAddress, customHeaders, transportType]
62935
+ [url2, connectionType, proxyAddress, customHeaders, transportType]
62472
62936
  );
62473
62937
  const handleConnectionSuccess = reactExports.useCallback(() => {
62474
62938
  if (!pendingConnectionConfig) return;
@@ -62946,7 +63410,7 @@ function InspectorDashboard() {
62946
63410
  {
62947
63411
  transportType,
62948
63412
  setTransportType,
62949
- url,
63413
+ url: url2,
62950
63414
  setUrl,
62951
63415
  connectionType,
62952
63416
  setConnectionType,
@@ -63130,16 +63594,16 @@ function useAutoConnect({
63130
63594
  }, [autoConnectConfig]);
63131
63595
  const attemptConnection = reactExports.useCallback(
63132
63596
  (config2) => {
63133
- const { url, name, transportType, connectionType, customHeaders } = config2;
63597
+ const { url: url2, name, transportType, connectionType, customHeaders } = config2;
63134
63598
  const proxyConfig = connectionType === "Via Proxy" ? {
63135
63599
  proxyAddress: `${window.location.origin}/inspector/api/proxy/mcp`,
63136
63600
  customHeaders: customHeaders || {}
63137
63601
  } : customHeaders && Object.keys(customHeaders).length > 0 ? { proxyAddress: void 0, customHeaders } : void 0;
63138
63602
  console.warn(
63139
63603
  `[useAutoConnect] Attempting connection (${connectionType}):`,
63140
- { url, transportType, proxyConfig }
63604
+ { url: url2, transportType, proxyConfig }
63141
63605
  );
63142
- addConnection(url, name, proxyConfig, transportType);
63606
+ addConnection(url2, name, proxyConfig, transportType);
63143
63607
  },
63144
63608
  [addConnection]
63145
63609
  );
@@ -91038,14 +91502,14 @@ function downloadJSON(data2, filename) {
91038
91502
  const blob = new BlobConstructor([jsonString], {
91039
91503
  type: "application/json"
91040
91504
  });
91041
- const url = URL.createObjectURL(blob);
91505
+ const url2 = URL.createObjectURL(blob);
91042
91506
  const a2 = document.createElement("a");
91043
- a2.href = url;
91507
+ a2.href = url2;
91044
91508
  a2.download = filename || `data-${Date.now()}.json`;
91045
91509
  document.body.appendChild(a2);
91046
91510
  a2.click();
91047
91511
  document.body.removeChild(a2);
91048
- URL.revokeObjectURL(url);
91512
+ URL.revokeObjectURL(url2);
91049
91513
  } catch (error) {
91050
91514
  console.error("Failed to download JSON:", error);
91051
91515
  throw error;
@@ -96144,7 +96608,7 @@ function useChatMessagesClientSide({
96144
96608
  let llm;
96145
96609
  if (llmConfig.provider === "openai") {
96146
96610
  const { ChatOpenAI } = await __vitePreload(async () => {
96147
- const { ChatOpenAI: ChatOpenAI2 } = await import("./index-DoWSnGj3.js");
96611
+ const { ChatOpenAI: ChatOpenAI2 } = await import("./index-mu626HD_.js");
96148
96612
  return { ChatOpenAI: ChatOpenAI2 };
96149
96613
  }, true ? __vite__mapDeps([5,6,3,7,8]) : void 0);
96150
96614
  llm = new ChatOpenAI({
@@ -96153,7 +96617,7 @@ function useChatMessagesClientSide({
96153
96617
  });
96154
96618
  } else if (llmConfig.provider === "anthropic") {
96155
96619
  const { ChatAnthropic } = await __vitePreload(async () => {
96156
- const { ChatAnthropic: ChatAnthropic2 } = await import("./index-BCYl76Jb.js");
96620
+ const { ChatAnthropic: ChatAnthropic2 } = await import("./index-C9SmrfBE.js");
96157
96621
  return { ChatAnthropic: ChatAnthropic2 };
96158
96622
  }, true ? __vite__mapDeps([9,6,3]) : void 0);
96159
96623
  llm = new ChatAnthropic({
@@ -96162,7 +96626,7 @@ function useChatMessagesClientSide({
96162
96626
  });
96163
96627
  } else if (llmConfig.provider === "google") {
96164
96628
  const { ChatGoogleGenerativeAI } = await __vitePreload(async () => {
96165
- const { ChatGoogleGenerativeAI: ChatGoogleGenerativeAI2 } = await import("./index-CV9pPOH9.js");
96629
+ const { ChatGoogleGenerativeAI: ChatGoogleGenerativeAI2 } = await import("./index-CvbM0GyZ.js");
96166
96630
  return { ChatGoogleGenerativeAI: ChatGoogleGenerativeAI2 };
96167
96631
  }, true ? __vite__mapDeps([10,6,3,8]) : void 0);
96168
96632
  llm = new ChatGoogleGenerativeAI({
@@ -96181,7 +96645,7 @@ function useChatMessagesClientSide({
96181
96645
  }
96182
96646
  if (!agentRef.current || agentRef.current.llm !== llmRef.current.instance) {
96183
96647
  const { MCPAgent } = await __vitePreload(async () => {
96184
- const { MCPAgent: MCPAgent2 } = await import("./browser-B7TIAiNJ.js");
96648
+ const { MCPAgent: MCPAgent2 } = await import("./browser-BxSiNtQZ.js");
96185
96649
  return { MCPAgent: MCPAgent2 };
96186
96650
  }, true ? __vite__mapDeps([11,7,6,3,2,4,8]) : void 0);
96187
96651
  agentRef.current = new MCPAgent({
@@ -99281,14 +99745,14 @@ function NotificationsTab({
99281
99745
  type: "application/json"
99282
99746
  }
99283
99747
  );
99284
- const url = URL.createObjectURL(blob);
99748
+ const url2 = URL.createObjectURL(blob);
99285
99749
  const a2 = document.createElement("a");
99286
- a2.href = url;
99750
+ a2.href = url2;
99287
99751
  a2.download = `notification-${Date.now()}.json`;
99288
99752
  document.body.appendChild(a2);
99289
99753
  a2.click();
99290
99754
  document.body.removeChild(a2);
99291
- URL.revokeObjectURL(url);
99755
+ URL.revokeObjectURL(url2);
99292
99756
  } catch (error) {
99293
99757
  console.error(
99294
99758
  "[NotificationsTab] Failed to download notification:",
@@ -101107,14 +101571,14 @@ function ResourcesTab({
101107
101571
  type: "application/json"
101108
101572
  }
101109
101573
  );
101110
- const url = URL.createObjectURL(blob);
101574
+ const url2 = URL.createObjectURL(blob);
101111
101575
  const a2 = document.createElement("a");
101112
- a2.href = url;
101576
+ a2.href = url2;
101113
101577
  a2.download = `resource-${Date.now()}.json`;
101114
101578
  document.body.appendChild(a2);
101115
101579
  a2.click();
101116
101580
  document.body.removeChild(a2);
101117
- URL.revokeObjectURL(url);
101581
+ URL.revokeObjectURL(url2);
101118
101582
  } catch (error) {
101119
101583
  console.error("[ResourcesTab] Failed to download result:", error);
101120
101584
  }