mcp-remote 0.1.36 → 0.1.38

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.
@@ -6482,7 +6482,7 @@ var require_formats = __commonJS({
6482
6482
  }
6483
6483
  exports.fullFormats = {
6484
6484
  // date: http://tools.ietf.org/html/rfc3339#section-5.6
6485
- date: fmtDef(date3, compareDate),
6485
+ date: fmtDef(date4, compareDate),
6486
6486
  // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
6487
6487
  time: fmtDef(getTime(true), compareTime),
6488
6488
  "date-time": fmtDef(getDateTime(true), compareDateTime),
@@ -6548,7 +6548,7 @@ var require_formats = __commonJS({
6548
6548
  }
6549
6549
  var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
6550
6550
  var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
6551
- function date3(str) {
6551
+ function date4(str) {
6552
6552
  const matches = DATE.exec(str);
6553
6553
  if (!matches)
6554
6554
  return false;
@@ -6617,7 +6617,7 @@ var require_formats = __commonJS({
6617
6617
  const time3 = getTime(strictTimeZone);
6618
6618
  return function date_time(str) {
6619
6619
  const dateTime = str.split(DATE_TIME_SEPARATOR);
6620
- return dateTime.length === 2 && date3(dateTime[0]) && time3(dateTime[1]);
6620
+ return dateTime.length === 2 && date4(dateTime[0]) && time3(dateTime[1]);
6621
6621
  };
6622
6622
  }
6623
6623
  function compareDateTime(dt1, dt2) {
@@ -7697,9 +7697,11 @@ var string = (params) => {
7697
7697
  const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
7698
7698
  return new RegExp(`^${regex}$`);
7699
7699
  };
7700
+ var bigint = /^-?\d+n?$/;
7700
7701
  var integer = /^-?\d+$/;
7701
7702
  var number = /^-?\d+(?:\.\d+)?/;
7702
7703
  var boolean = /^(?:true|false)$/i;
7704
+ var _null = /^null$/i;
7703
7705
  var lowercase = /^[^A-Z]*$/;
7704
7706
  var uppercase = /^[^a-z]*$/;
7705
7707
 
@@ -8582,6 +8584,43 @@ var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
8582
8584
  return payload;
8583
8585
  };
8584
8586
  });
8587
+ var $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => {
8588
+ $ZodType.init(inst, def);
8589
+ inst._zod.pattern = bigint;
8590
+ inst._zod.parse = (payload, _ctx) => {
8591
+ if (def.coerce)
8592
+ try {
8593
+ payload.value = BigInt(payload.value);
8594
+ } catch (_) {
8595
+ }
8596
+ if (typeof payload.value === "bigint")
8597
+ return payload;
8598
+ payload.issues.push({
8599
+ expected: "bigint",
8600
+ code: "invalid_type",
8601
+ input: payload.value,
8602
+ inst
8603
+ });
8604
+ return payload;
8605
+ };
8606
+ });
8607
+ var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => {
8608
+ $ZodType.init(inst, def);
8609
+ inst._zod.pattern = _null;
8610
+ inst._zod.values = /* @__PURE__ */ new Set([null]);
8611
+ inst._zod.parse = (payload, _ctx) => {
8612
+ const input = payload.value;
8613
+ if (input === null)
8614
+ return payload;
8615
+ payload.issues.push({
8616
+ expected: "null",
8617
+ code: "invalid_type",
8618
+ input,
8619
+ inst
8620
+ });
8621
+ return payload;
8622
+ };
8623
+ });
8585
8624
  var $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => {
8586
8625
  $ZodType.init(inst, def);
8587
8626
  inst._zod.parse = (payload) => payload;
@@ -8602,6 +8641,30 @@ var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
8602
8641
  return payload;
8603
8642
  };
8604
8643
  });
8644
+ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
8645
+ $ZodType.init(inst, def);
8646
+ inst._zod.parse = (payload, _ctx) => {
8647
+ if (def.coerce) {
8648
+ try {
8649
+ payload.value = new Date(payload.value);
8650
+ } catch (_err) {
8651
+ }
8652
+ }
8653
+ const input = payload.value;
8654
+ const isDate = input instanceof Date;
8655
+ const isValidDate = isDate && !Number.isNaN(input.getTime());
8656
+ if (isValidDate)
8657
+ return payload;
8658
+ payload.issues.push({
8659
+ expected: "date",
8660
+ code: "invalid_type",
8661
+ input,
8662
+ ...isDate ? { received: "Invalid Date" } : {},
8663
+ inst
8664
+ });
8665
+ return payload;
8666
+ };
8667
+ });
8605
8668
  function handleArrayResult(result, final, index) {
8606
8669
  if (result.issues.length) {
8607
8670
  final.issues.push(...prefixIssues(index, result.issues));
@@ -9617,6 +9680,13 @@ function _string(Class2, params) {
9617
9680
  ...normalizeParams(params)
9618
9681
  });
9619
9682
  }
9683
+ function _coercedString(Class2, params) {
9684
+ return new Class2({
9685
+ type: "string",
9686
+ coerce: true,
9687
+ ...normalizeParams(params)
9688
+ });
9689
+ }
9620
9690
  function _email(Class2, params) {
9621
9691
  return new Class2({
9622
9692
  type: "string",
@@ -9861,6 +9931,14 @@ function _number(Class2, params) {
9861
9931
  ...normalizeParams(params)
9862
9932
  });
9863
9933
  }
9934
+ function _coercedNumber(Class2, params) {
9935
+ return new Class2({
9936
+ type: "number",
9937
+ coerce: true,
9938
+ checks: [],
9939
+ ...normalizeParams(params)
9940
+ });
9941
+ }
9864
9942
  function _int(Class2, params) {
9865
9943
  return new Class2({
9866
9944
  type: "number",
@@ -9876,6 +9954,26 @@ function _boolean(Class2, params) {
9876
9954
  ...normalizeParams(params)
9877
9955
  });
9878
9956
  }
9957
+ function _coercedBoolean(Class2, params) {
9958
+ return new Class2({
9959
+ type: "boolean",
9960
+ coerce: true,
9961
+ ...normalizeParams(params)
9962
+ });
9963
+ }
9964
+ function _coercedBigint(Class2, params) {
9965
+ return new Class2({
9966
+ type: "bigint",
9967
+ coerce: true,
9968
+ ...normalizeParams(params)
9969
+ });
9970
+ }
9971
+ function _null2(Class2, params) {
9972
+ return new Class2({
9973
+ type: "null",
9974
+ ...normalizeParams(params)
9975
+ });
9976
+ }
9879
9977
  function _any(Class2) {
9880
9978
  return new Class2({
9881
9979
  type: "any"
@@ -9892,6 +9990,13 @@ function _never(Class2, params) {
9892
9990
  ...normalizeParams(params)
9893
9991
  });
9894
9992
  }
9993
+ function _coercedDate(Class2, params) {
9994
+ return new Class2({
9995
+ type: "date",
9996
+ coerce: true,
9997
+ ...normalizeParams(params)
9998
+ });
9999
+ }
9895
10000
  function _lt(value, params) {
9896
10001
  return new $ZodCheckLessThan({
9897
10002
  check: "less_than",
@@ -10080,6 +10185,17 @@ function _check(fn, params) {
10080
10185
  }
10081
10186
 
10082
10187
  // node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/classic/iso.js
10188
+ var iso_exports = {};
10189
+ __export(iso_exports, {
10190
+ ZodISODate: () => ZodISODate,
10191
+ ZodISODateTime: () => ZodISODateTime,
10192
+ ZodISODuration: () => ZodISODuration,
10193
+ ZodISOTime: () => ZodISOTime,
10194
+ date: () => date2,
10195
+ datetime: () => datetime2,
10196
+ duration: () => duration2,
10197
+ time: () => time2
10198
+ });
10083
10199
  var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
10084
10200
  $ZodISODateTime.init(inst, def);
10085
10201
  ZodStringFormat.init(inst, def);
@@ -10417,6 +10533,34 @@ var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {
10417
10533
  function boolean2(params) {
10418
10534
  return _boolean(ZodBoolean, params);
10419
10535
  }
10536
+ var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => {
10537
+ $ZodBigInt.init(inst, def);
10538
+ ZodType.init(inst, def);
10539
+ inst.gte = (value, params) => inst.check(_gte(value, params));
10540
+ inst.min = (value, params) => inst.check(_gte(value, params));
10541
+ inst.gt = (value, params) => inst.check(_gt(value, params));
10542
+ inst.gte = (value, params) => inst.check(_gte(value, params));
10543
+ inst.min = (value, params) => inst.check(_gte(value, params));
10544
+ inst.lt = (value, params) => inst.check(_lt(value, params));
10545
+ inst.lte = (value, params) => inst.check(_lte(value, params));
10546
+ inst.max = (value, params) => inst.check(_lte(value, params));
10547
+ inst.positive = (params) => inst.check(_gt(BigInt(0), params));
10548
+ inst.negative = (params) => inst.check(_lt(BigInt(0), params));
10549
+ inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params));
10550
+ inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params));
10551
+ inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
10552
+ const bag = inst._zod.bag;
10553
+ inst.minValue = bag.minimum ?? null;
10554
+ inst.maxValue = bag.maximum ?? null;
10555
+ inst.format = bag.format ?? null;
10556
+ });
10557
+ var ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => {
10558
+ $ZodNull.init(inst, def);
10559
+ ZodType.init(inst, def);
10560
+ });
10561
+ function _null3(params) {
10562
+ return _null2(ZodNull, params);
10563
+ }
10420
10564
  var ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => {
10421
10565
  $ZodAny.init(inst, def);
10422
10566
  ZodType.init(inst, def);
@@ -10438,6 +10582,15 @@ var ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
10438
10582
  function never(params) {
10439
10583
  return _never(ZodNever, params);
10440
10584
  }
10585
+ var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => {
10586
+ $ZodDate.init(inst, def);
10587
+ ZodType.init(inst, def);
10588
+ inst.min = (value, params) => inst.check(_gte(value, params));
10589
+ inst.max = (value, params) => inst.check(_lte(value, params));
10590
+ const c = inst._zod.bag;
10591
+ inst.minDate = c.minimum ? new Date(c.minimum) : null;
10592
+ inst.maxDate = c.maximum ? new Date(c.maximum) : null;
10593
+ });
10441
10594
  var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
10442
10595
  $ZodArray.init(inst, def);
10443
10596
  ZodType.init(inst, def);
@@ -10778,49 +10931,108 @@ var ZodFirstPartyTypeKind;
10778
10931
  /* @__PURE__ */ (function(ZodFirstPartyTypeKind3) {
10779
10932
  })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
10780
10933
 
10934
+ // node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/classic/coerce.js
10935
+ var coerce_exports = {};
10936
+ __export(coerce_exports, {
10937
+ bigint: () => bigint2,
10938
+ boolean: () => boolean3,
10939
+ date: () => date3,
10940
+ number: () => number3,
10941
+ string: () => string3
10942
+ });
10943
+ function string3(params) {
10944
+ return _coercedString(ZodString, params);
10945
+ }
10946
+ function number3(params) {
10947
+ return _coercedNumber(ZodNumber, params);
10948
+ }
10949
+ function boolean3(params) {
10950
+ return _coercedBoolean(ZodBoolean, params);
10951
+ }
10952
+ function bigint2(params) {
10953
+ return _coercedBigint(ZodBigInt, params);
10954
+ }
10955
+ function date3(params) {
10956
+ return _coercedDate(ZodDate, params);
10957
+ }
10958
+
10781
10959
  // node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/classic/external.js
10782
10960
  config(en_default());
10783
10961
 
10784
- // node_modules/.pnpm/@modelcontextprotocol+sdk@1.23.0_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
10785
- var LATEST_PROTOCOL_VERSION = "2025-06-18";
10786
- var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-03-26", "2024-11-05", "2024-10-07"];
10962
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.3_hono@4.11.7_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
10963
+ var LATEST_PROTOCOL_VERSION = "2025-11-25";
10964
+ var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"];
10965
+ var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
10787
10966
  var JSONRPC_VERSION = "2.0";
10788
10967
  var AssertObjectSchema = custom((v) => v !== null && (typeof v === "object" || typeof v === "function"));
10789
10968
  var ProgressTokenSchema = union([string2(), number2().int()]);
10790
10969
  var CursorSchema = string2();
10970
+ var TaskCreationParamsSchema = looseObject({
10971
+ /**
10972
+ * Time in milliseconds to keep task results available after completion.
10973
+ * If null, the task has unlimited lifetime until manually cleaned up.
10974
+ */
10975
+ ttl: union([number2(), _null3()]).optional(),
10976
+ /**
10977
+ * Time in milliseconds to wait between task status requests.
10978
+ */
10979
+ pollInterval: number2().optional()
10980
+ });
10981
+ var TaskMetadataSchema = object({
10982
+ ttl: number2().optional()
10983
+ });
10984
+ var RelatedTaskMetadataSchema = object({
10985
+ taskId: string2()
10986
+ });
10791
10987
  var RequestMetaSchema = looseObject({
10792
10988
  /**
10793
10989
  * 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.
10794
10990
  */
10795
- progressToken: ProgressTokenSchema.optional()
10991
+ progressToken: ProgressTokenSchema.optional(),
10992
+ /**
10993
+ * If specified, this request is related to the provided task.
10994
+ */
10995
+ [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
10796
10996
  });
10797
- var BaseRequestParamsSchema = looseObject({
10997
+ var BaseRequestParamsSchema = object({
10798
10998
  /**
10799
10999
  * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.
10800
11000
  */
10801
11001
  _meta: RequestMetaSchema.optional()
10802
11002
  });
11003
+ var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({
11004
+ /**
11005
+ * If specified, the caller is requesting task-augmented execution for this request.
11006
+ * The request will return a CreateTaskResult immediately, and the actual result can be
11007
+ * retrieved later via tasks/result.
11008
+ *
11009
+ * Task augmentation is subject to capability negotiation - receivers MUST declare support
11010
+ * for task augmentation of specific request types in their capabilities.
11011
+ */
11012
+ task: TaskMetadataSchema.optional()
11013
+ });
11014
+ var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;
10803
11015
  var RequestSchema = object({
10804
11016
  method: string2(),
10805
- params: BaseRequestParamsSchema.optional()
11017
+ params: BaseRequestParamsSchema.loose().optional()
10806
11018
  });
10807
- var NotificationsParamsSchema = looseObject({
11019
+ var NotificationsParamsSchema = object({
10808
11020
  /**
10809
11021
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
10810
11022
  * for notes on _meta usage.
10811
11023
  */
10812
- _meta: record(string2(), unknown()).optional()
11024
+ _meta: RequestMetaSchema.optional()
10813
11025
  });
10814
11026
  var NotificationSchema = object({
10815
11027
  method: string2(),
10816
- params: NotificationsParamsSchema.optional()
11028
+ params: NotificationsParamsSchema.loose().optional()
10817
11029
  });
10818
11030
  var ResultSchema = looseObject({
10819
11031
  /**
10820
11032
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
10821
11033
  * for notes on _meta usage.
10822
11034
  */
10823
- _meta: record(string2(), unknown()).optional()
11035
+ _meta: RequestMetaSchema.optional()
10824
11036
  });
10825
11037
  var RequestIdSchema = union([string2(), number2().int()]);
10826
11038
  var JSONRPCRequestSchema = object({
@@ -10834,12 +11046,12 @@ var JSONRPCNotificationSchema = object({
10834
11046
  ...NotificationSchema.shape
10835
11047
  }).strict();
10836
11048
  var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;
10837
- var JSONRPCResponseSchema = object({
11049
+ var JSONRPCResultResponseSchema = object({
10838
11050
  jsonrpc: literal(JSONRPC_VERSION),
10839
11051
  id: RequestIdSchema,
10840
11052
  result: ResultSchema
10841
11053
  }).strict();
10842
- var isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success;
11054
+ var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;
10843
11055
  var ErrorCode;
10844
11056
  (function(ErrorCode2) {
10845
11057
  ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed";
@@ -10851,9 +11063,9 @@ var ErrorCode;
10851
11063
  ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError";
10852
11064
  ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
10853
11065
  })(ErrorCode || (ErrorCode = {}));
10854
- var JSONRPCErrorSchema = object({
11066
+ var JSONRPCErrorResponseSchema = object({
10855
11067
  jsonrpc: literal(JSONRPC_VERSION),
10856
- id: RequestIdSchema,
11068
+ id: RequestIdSchema.optional(),
10857
11069
  error: object({
10858
11070
  /**
10859
11071
  * The error type that occurred.
@@ -10866,11 +11078,17 @@ var JSONRPCErrorSchema = object({
10866
11078
  /**
10867
11079
  * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
10868
11080
  */
10869
- data: optional(unknown())
11081
+ data: unknown().optional()
10870
11082
  })
10871
11083
  }).strict();
10872
- var isJSONRPCError = (value) => JSONRPCErrorSchema.safeParse(value).success;
10873
- var JSONRPCMessageSchema = union([JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResponseSchema, JSONRPCErrorSchema]);
11084
+ var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;
11085
+ var JSONRPCMessageSchema = union([
11086
+ JSONRPCRequestSchema,
11087
+ JSONRPCNotificationSchema,
11088
+ JSONRPCResultResponseSchema,
11089
+ JSONRPCErrorResponseSchema
11090
+ ]);
11091
+ var JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
10874
11092
  var EmptyResultSchema = ResultSchema.strict();
10875
11093
  var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
10876
11094
  /**
@@ -10878,7 +11096,7 @@ var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
10878
11096
  *
10879
11097
  * This MUST correspond to the ID of a request previously issued in the same direction.
10880
11098
  */
10881
- requestId: RequestIdSchema,
11099
+ requestId: RequestIdSchema.optional(),
10882
11100
  /**
10883
11101
  * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
10884
11102
  */
@@ -10903,7 +11121,15 @@ var IconSchema = object({
10903
11121
  *
10904
11122
  * If not provided, the client should assume that the icon can be used at any size.
10905
11123
  */
10906
- sizes: array(string2()).optional()
11124
+ sizes: array(string2()).optional(),
11125
+ /**
11126
+ * Optional specifier for the theme this icon is designed for. `light` indicates
11127
+ * the icon is designed to be used with a light background, and `dark` indicates
11128
+ * the icon is designed to be used with a dark background.
11129
+ *
11130
+ * If not provided, the client should assume the icon can be used with any theme.
11131
+ */
11132
+ theme: _enum(["light", "dark"]).optional()
10907
11133
  });
10908
11134
  var IconsSchema = object({
10909
11135
  /**
@@ -10939,7 +11165,15 @@ var ImplementationSchema = BaseMetadataSchema.extend({
10939
11165
  /**
10940
11166
  * An optional URL of the website for this implementation.
10941
11167
  */
10942
- websiteUrl: string2().optional()
11168
+ websiteUrl: string2().optional(),
11169
+ /**
11170
+ * An optional human-readable description of what this implementation does.
11171
+ *
11172
+ * This can be used by clients or servers to provide context about their purpose
11173
+ * and capabilities. For example, a server might describe the types of resources
11174
+ * or tools it provides, while a client might describe its intended use case.
11175
+ */
11176
+ description: string2().optional()
10943
11177
  });
10944
11178
  var FormElicitationCapabilitySchema = intersection(object({
10945
11179
  applyDefaults: boolean2().optional()
@@ -10955,6 +11189,54 @@ var ElicitationCapabilitySchema = preprocess((value) => {
10955
11189
  form: FormElicitationCapabilitySchema.optional(),
10956
11190
  url: AssertObjectSchema.optional()
10957
11191
  }), record(string2(), unknown()).optional()));
11192
+ var ClientTasksCapabilitySchema = looseObject({
11193
+ /**
11194
+ * Present if the client supports listing tasks.
11195
+ */
11196
+ list: AssertObjectSchema.optional(),
11197
+ /**
11198
+ * Present if the client supports cancelling tasks.
11199
+ */
11200
+ cancel: AssertObjectSchema.optional(),
11201
+ /**
11202
+ * Capabilities for task creation on specific request types.
11203
+ */
11204
+ requests: looseObject({
11205
+ /**
11206
+ * Task support for sampling requests.
11207
+ */
11208
+ sampling: looseObject({
11209
+ createMessage: AssertObjectSchema.optional()
11210
+ }).optional(),
11211
+ /**
11212
+ * Task support for elicitation requests.
11213
+ */
11214
+ elicitation: looseObject({
11215
+ create: AssertObjectSchema.optional()
11216
+ }).optional()
11217
+ }).optional()
11218
+ });
11219
+ var ServerTasksCapabilitySchema = looseObject({
11220
+ /**
11221
+ * Present if the server supports listing tasks.
11222
+ */
11223
+ list: AssertObjectSchema.optional(),
11224
+ /**
11225
+ * Present if the server supports cancelling tasks.
11226
+ */
11227
+ cancel: AssertObjectSchema.optional(),
11228
+ /**
11229
+ * Capabilities for task creation on specific request types.
11230
+ */
11231
+ requests: looseObject({
11232
+ /**
11233
+ * Task support for tool requests.
11234
+ */
11235
+ tools: looseObject({
11236
+ call: AssertObjectSchema.optional()
11237
+ }).optional()
11238
+ }).optional()
11239
+ });
10958
11240
  var ClientCapabilitiesSchema = object({
10959
11241
  /**
10960
11242
  * Experimental, non-standard capabilities that the client supports.
@@ -10986,7 +11268,11 @@ var ClientCapabilitiesSchema = object({
10986
11268
  * Whether the client supports issuing notifications for changes to the roots list.
10987
11269
  */
10988
11270
  listChanged: boolean2().optional()
10989
- }).optional()
11271
+ }).optional(),
11272
+ /**
11273
+ * Present if the client supports task creation.
11274
+ */
11275
+ tasks: ClientTasksCapabilitySchema.optional()
10990
11276
  });
10991
11277
  var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
10992
11278
  /**
@@ -11016,12 +11302,12 @@ var ServerCapabilitiesSchema = object({
11016
11302
  /**
11017
11303
  * Present if the server offers any prompt templates.
11018
11304
  */
11019
- prompts: optional(object({
11305
+ prompts: object({
11020
11306
  /**
11021
11307
  * Whether this server supports issuing notifications for changes to the prompt list.
11022
11308
  */
11023
- listChanged: optional(boolean2())
11024
- })),
11309
+ listChanged: boolean2().optional()
11310
+ }).optional(),
11025
11311
  /**
11026
11312
  * Present if the server offers any resources to read.
11027
11313
  */
@@ -11043,7 +11329,11 @@ var ServerCapabilitiesSchema = object({
11043
11329
  * Whether this server supports issuing notifications for changes to the tool list.
11044
11330
  */
11045
11331
  listChanged: boolean2().optional()
11046
- }).optional()
11332
+ }).optional(),
11333
+ /**
11334
+ * Present if the server supports task creation.
11335
+ */
11336
+ tasks: ServerTasksCapabilitySchema.optional()
11047
11337
  });
11048
11338
  var InitializeResultSchema = ResultSchema.extend({
11049
11339
  /**
@@ -11060,11 +11350,13 @@ var InitializeResultSchema = ResultSchema.extend({
11060
11350
  instructions: string2().optional()
11061
11351
  });
11062
11352
  var InitializedNotificationSchema = NotificationSchema.extend({
11063
- method: literal("notifications/initialized")
11353
+ method: literal("notifications/initialized"),
11354
+ params: NotificationsParamsSchema.optional()
11064
11355
  });
11065
11356
  var isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success;
11066
11357
  var PingRequestSchema = RequestSchema.extend({
11067
- method: literal("ping")
11358
+ method: literal("ping"),
11359
+ params: BaseRequestParamsSchema.optional()
11068
11360
  });
11069
11361
  var ProgressSchema = object({
11070
11362
  /**
@@ -11107,8 +11399,66 @@ var PaginatedResultSchema = ResultSchema.extend({
11107
11399
  * An opaque token representing the pagination position after the last returned result.
11108
11400
  * If present, there may be more results available.
11109
11401
  */
11110
- nextCursor: optional(CursorSchema)
11402
+ nextCursor: CursorSchema.optional()
11111
11403
  });
11404
+ var TaskStatusSchema = _enum(["working", "input_required", "completed", "failed", "cancelled"]);
11405
+ var TaskSchema = object({
11406
+ taskId: string2(),
11407
+ status: TaskStatusSchema,
11408
+ /**
11409
+ * Time in milliseconds to keep task results available after completion.
11410
+ * If null, the task has unlimited lifetime until manually cleaned up.
11411
+ */
11412
+ ttl: union([number2(), _null3()]),
11413
+ /**
11414
+ * ISO 8601 timestamp when the task was created.
11415
+ */
11416
+ createdAt: string2(),
11417
+ /**
11418
+ * ISO 8601 timestamp when the task was last updated.
11419
+ */
11420
+ lastUpdatedAt: string2(),
11421
+ pollInterval: optional(number2()),
11422
+ /**
11423
+ * Optional diagnostic message for failed tasks or other status information.
11424
+ */
11425
+ statusMessage: optional(string2())
11426
+ });
11427
+ var CreateTaskResultSchema = ResultSchema.extend({
11428
+ task: TaskSchema
11429
+ });
11430
+ var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);
11431
+ var TaskStatusNotificationSchema = NotificationSchema.extend({
11432
+ method: literal("notifications/tasks/status"),
11433
+ params: TaskStatusNotificationParamsSchema
11434
+ });
11435
+ var GetTaskRequestSchema = RequestSchema.extend({
11436
+ method: literal("tasks/get"),
11437
+ params: BaseRequestParamsSchema.extend({
11438
+ taskId: string2()
11439
+ })
11440
+ });
11441
+ var GetTaskResultSchema = ResultSchema.merge(TaskSchema);
11442
+ var GetTaskPayloadRequestSchema = RequestSchema.extend({
11443
+ method: literal("tasks/result"),
11444
+ params: BaseRequestParamsSchema.extend({
11445
+ taskId: string2()
11446
+ })
11447
+ });
11448
+ var GetTaskPayloadResultSchema = ResultSchema.loose();
11449
+ var ListTasksRequestSchema = PaginatedRequestSchema.extend({
11450
+ method: literal("tasks/list")
11451
+ });
11452
+ var ListTasksResultSchema = PaginatedResultSchema.extend({
11453
+ tasks: array(TaskSchema)
11454
+ });
11455
+ var CancelTaskRequestSchema = RequestSchema.extend({
11456
+ method: literal("tasks/cancel"),
11457
+ params: BaseRequestParamsSchema.extend({
11458
+ taskId: string2()
11459
+ })
11460
+ });
11461
+ var CancelTaskResultSchema = ResultSchema.merge(TaskSchema);
11112
11462
  var ResourceContentsSchema = object({
11113
11463
  /**
11114
11464
  * The URI of this resource.
@@ -11134,7 +11484,7 @@ var Base64Schema = string2().refine((val) => {
11134
11484
  try {
11135
11485
  atob(val);
11136
11486
  return true;
11137
- } catch (_a2) {
11487
+ } catch {
11138
11488
  return false;
11139
11489
  }
11140
11490
  }, { message: "Invalid Base64 string" });
@@ -11144,6 +11494,21 @@ var BlobResourceContentsSchema = ResourceContentsSchema.extend({
11144
11494
  */
11145
11495
  blob: Base64Schema
11146
11496
  });
11497
+ var RoleSchema = _enum(["user", "assistant"]);
11498
+ var AnnotationsSchema = object({
11499
+ /**
11500
+ * Intended audience(s) for the resource.
11501
+ */
11502
+ audience: array(RoleSchema).optional(),
11503
+ /**
11504
+ * Importance hint for the resource, from 0 (least) to 1 (most).
11505
+ */
11506
+ priority: number2().min(0).max(1).optional(),
11507
+ /**
11508
+ * ISO 8601 timestamp for the most recent modification.
11509
+ */
11510
+ lastModified: iso_exports.datetime({ offset: true }).optional()
11511
+ });
11147
11512
  var ResourceSchema = object({
11148
11513
  ...BaseMetadataSchema.shape,
11149
11514
  ...IconsSchema.shape,
@@ -11161,6 +11526,10 @@ var ResourceSchema = object({
11161
11526
  * The MIME type of this resource, if known.
11162
11527
  */
11163
11528
  mimeType: optional(string2()),
11529
+ /**
11530
+ * Optional annotations for the client.
11531
+ */
11532
+ annotations: AnnotationsSchema.optional(),
11164
11533
  /**
11165
11534
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
11166
11535
  * for notes on _meta usage.
@@ -11184,6 +11553,10 @@ var ResourceTemplateSchema = object({
11184
11553
  * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.
11185
11554
  */
11186
11555
  mimeType: optional(string2()),
11556
+ /**
11557
+ * Optional annotations for the client.
11558
+ */
11559
+ annotations: AnnotationsSchema.optional(),
11187
11560
  /**
11188
11561
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
11189
11562
  * for notes on _meta usage.
@@ -11219,7 +11592,8 @@ var ReadResourceResultSchema = ResultSchema.extend({
11219
11592
  contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema]))
11220
11593
  });
11221
11594
  var ResourceListChangedNotificationSchema = NotificationSchema.extend({
11222
- method: literal("notifications/resources/list_changed")
11595
+ method: literal("notifications/resources/list_changed"),
11596
+ params: NotificationsParamsSchema.optional()
11223
11597
  });
11224
11598
  var SubscribeRequestParamsSchema = ResourceRequestParamsSchema;
11225
11599
  var SubscribeRequestSchema = RequestSchema.extend({
@@ -11298,6 +11672,10 @@ var TextContentSchema = object({
11298
11672
  * The text content of the message.
11299
11673
  */
11300
11674
  text: string2(),
11675
+ /**
11676
+ * Optional annotations for the client.
11677
+ */
11678
+ annotations: AnnotationsSchema.optional(),
11301
11679
  /**
11302
11680
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
11303
11681
  * for notes on _meta usage.
@@ -11314,6 +11692,10 @@ var ImageContentSchema = object({
11314
11692
  * The MIME type of the image. Different providers may support different image types.
11315
11693
  */
11316
11694
  mimeType: string2(),
11695
+ /**
11696
+ * Optional annotations for the client.
11697
+ */
11698
+ annotations: AnnotationsSchema.optional(),
11317
11699
  /**
11318
11700
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
11319
11701
  * for notes on _meta usage.
@@ -11330,6 +11712,10 @@ var AudioContentSchema = object({
11330
11712
  * The MIME type of the audio. Different providers may support different audio types.
11331
11713
  */
11332
11714
  mimeType: string2(),
11715
+ /**
11716
+ * Optional annotations for the client.
11717
+ */
11718
+ annotations: AnnotationsSchema.optional(),
11333
11719
  /**
11334
11720
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
11335
11721
  * for notes on _meta usage.
@@ -11352,16 +11738,20 @@ var ToolUseContentSchema = object({
11352
11738
  * Arguments to pass to the tool.
11353
11739
  * Must conform to the tool's inputSchema.
11354
11740
  */
11355
- input: object({}).passthrough(),
11741
+ input: record(string2(), unknown()),
11356
11742
  /**
11357
11743
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
11358
11744
  * for notes on _meta usage.
11359
11745
  */
11360
- _meta: optional(object({}).passthrough())
11361
- }).passthrough();
11746
+ _meta: record(string2(), unknown()).optional()
11747
+ });
11362
11748
  var EmbeddedResourceSchema = object({
11363
11749
  type: literal("resource"),
11364
11750
  resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
11751
+ /**
11752
+ * Optional annotations for the client.
11753
+ */
11754
+ annotations: AnnotationsSchema.optional(),
11365
11755
  /**
11366
11756
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
11367
11757
  * for notes on _meta usage.
@@ -11379,18 +11769,19 @@ var ContentBlockSchema = union([
11379
11769
  EmbeddedResourceSchema
11380
11770
  ]);
11381
11771
  var PromptMessageSchema = object({
11382
- role: _enum(["user", "assistant"]),
11772
+ role: RoleSchema,
11383
11773
  content: ContentBlockSchema
11384
11774
  });
11385
11775
  var GetPromptResultSchema = ResultSchema.extend({
11386
11776
  /**
11387
11777
  * An optional description for the prompt.
11388
11778
  */
11389
- description: optional(string2()),
11779
+ description: string2().optional(),
11390
11780
  messages: array(PromptMessageSchema)
11391
11781
  });
11392
11782
  var PromptListChangedNotificationSchema = NotificationSchema.extend({
11393
- method: literal("notifications/prompts/list_changed")
11783
+ method: literal("notifications/prompts/list_changed"),
11784
+ params: NotificationsParamsSchema.optional()
11394
11785
  });
11395
11786
  var ToolAnnotationsSchema = object({
11396
11787
  /**
@@ -11431,6 +11822,17 @@ var ToolAnnotationsSchema = object({
11431
11822
  */
11432
11823
  openWorldHint: boolean2().optional()
11433
11824
  });
11825
+ var ToolExecutionSchema = object({
11826
+ /**
11827
+ * Indicates the tool's preference for task-augmented execution.
11828
+ * - "required": Clients MUST invoke the tool as a task
11829
+ * - "optional": Clients MAY invoke the tool as a task or normal request
11830
+ * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task
11831
+ *
11832
+ * If not present, defaults to "forbidden".
11833
+ */
11834
+ taskSupport: _enum(["required", "optional", "forbidden"]).optional()
11835
+ });
11434
11836
  var ToolSchema = object({
11435
11837
  ...BaseMetadataSchema.shape,
11436
11838
  ...IconsSchema.shape,
@@ -11460,7 +11862,11 @@ var ToolSchema = object({
11460
11862
  /**
11461
11863
  * Optional additional tool information.
11462
11864
  */
11463
- annotations: optional(ToolAnnotationsSchema),
11865
+ annotations: ToolAnnotationsSchema.optional(),
11866
+ /**
11867
+ * Execution-related properties for this tool.
11868
+ */
11869
+ execution: ToolExecutionSchema.optional(),
11464
11870
  /**
11465
11871
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
11466
11872
  * for notes on _meta usage.
@@ -11501,12 +11907,12 @@ var CallToolResultSchema = ResultSchema.extend({
11501
11907
  * server does not support tool calls, or any other exceptional conditions,
11502
11908
  * should be reported as an MCP error response.
11503
11909
  */
11504
- isError: optional(boolean2())
11910
+ isError: boolean2().optional()
11505
11911
  });
11506
11912
  var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({
11507
11913
  toolResult: unknown()
11508
11914
  }));
11509
- var CallToolRequestParamsSchema = BaseRequestParamsSchema.extend({
11915
+ var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
11510
11916
  /**
11511
11917
  * The name of the tool to call.
11512
11918
  */
@@ -11514,14 +11920,35 @@ var CallToolRequestParamsSchema = BaseRequestParamsSchema.extend({
11514
11920
  /**
11515
11921
  * Arguments to pass to the tool.
11516
11922
  */
11517
- arguments: optional(record(string2(), unknown()))
11923
+ arguments: record(string2(), unknown()).optional()
11518
11924
  });
11519
11925
  var CallToolRequestSchema = RequestSchema.extend({
11520
11926
  method: literal("tools/call"),
11521
11927
  params: CallToolRequestParamsSchema
11522
11928
  });
11523
11929
  var ToolListChangedNotificationSchema = NotificationSchema.extend({
11524
- method: literal("notifications/tools/list_changed")
11930
+ method: literal("notifications/tools/list_changed"),
11931
+ params: NotificationsParamsSchema.optional()
11932
+ });
11933
+ var ListChangedOptionsBaseSchema = object({
11934
+ /**
11935
+ * If true, the list will be refreshed automatically when a list changed notification is received.
11936
+ * The callback will be called with the updated list.
11937
+ *
11938
+ * If false, the callback will be called with null items, allowing manual refresh.
11939
+ *
11940
+ * @default true
11941
+ */
11942
+ autoRefresh: boolean2().default(true),
11943
+ /**
11944
+ * Debounce time in milliseconds for list changed notification processing.
11945
+ *
11946
+ * Multiple notifications received within this timeframe will only trigger one refresh.
11947
+ * Set to 0 to disable debouncing.
11948
+ *
11949
+ * @default 300
11950
+ */
11951
+ debounceMs: number2().int().nonnegative().default(300)
11525
11952
  });
11526
11953
  var LoggingLevelSchema = _enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
11527
11954
  var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({
@@ -11562,19 +11989,19 @@ var ModelPreferencesSchema = object({
11562
11989
  /**
11563
11990
  * Optional hints to use for model selection.
11564
11991
  */
11565
- hints: optional(array(ModelHintSchema)),
11992
+ hints: array(ModelHintSchema).optional(),
11566
11993
  /**
11567
11994
  * How much to prioritize cost when selecting a model.
11568
11995
  */
11569
- costPriority: optional(number2().min(0).max(1)),
11996
+ costPriority: number2().min(0).max(1).optional(),
11570
11997
  /**
11571
11998
  * How much to prioritize sampling speed (latency) when selecting a model.
11572
11999
  */
11573
- speedPriority: optional(number2().min(0).max(1)),
12000
+ speedPriority: number2().min(0).max(1).optional(),
11574
12001
  /**
11575
12002
  * How much to prioritize intelligence and capabilities when selecting a model.
11576
12003
  */
11577
- intelligencePriority: optional(number2().min(0).max(1))
12004
+ intelligencePriority: number2().min(0).max(1).optional()
11578
12005
  });
11579
12006
  var ToolChoiceSchema = object({
11580
12007
  /**
@@ -11583,20 +12010,21 @@ var ToolChoiceSchema = object({
11583
12010
  * - "required": Model MUST use at least one tool before completing
11584
12011
  * - "none": Model MUST NOT use any tools
11585
12012
  */
11586
- mode: optional(_enum(["auto", "required", "none"]))
12013
+ mode: _enum(["auto", "required", "none"]).optional()
11587
12014
  });
11588
12015
  var ToolResultContentSchema = object({
11589
12016
  type: literal("tool_result"),
11590
12017
  toolUseId: string2().describe("The unique identifier for the corresponding tool call."),
11591
12018
  content: array(ContentBlockSchema).default([]),
11592
- structuredContent: object({}).passthrough().optional(),
11593
- isError: optional(boolean2()),
12019
+ structuredContent: object({}).loose().optional(),
12020
+ isError: boolean2().optional(),
11594
12021
  /**
11595
12022
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
11596
12023
  * for notes on _meta usage.
11597
12024
  */
11598
- _meta: optional(object({}).passthrough())
11599
- }).passthrough();
12025
+ _meta: record(string2(), unknown()).optional()
12026
+ });
12027
+ var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);
11600
12028
  var SamplingMessageContentBlockSchema = discriminatedUnion("type", [
11601
12029
  TextContentSchema,
11602
12030
  ImageContentSchema,
@@ -11605,15 +12033,15 @@ var SamplingMessageContentBlockSchema = discriminatedUnion("type", [
11605
12033
  ToolResultContentSchema
11606
12034
  ]);
11607
12035
  var SamplingMessageSchema = object({
11608
- role: _enum(["user", "assistant"]),
12036
+ role: RoleSchema,
11609
12037
  content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),
11610
12038
  /**
11611
12039
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
11612
12040
  * for notes on _meta usage.
11613
12041
  */
11614
- _meta: optional(object({}).passthrough())
11615
- }).passthrough();
11616
- var CreateMessageRequestParamsSchema = BaseRequestParamsSchema.extend({
12042
+ _meta: record(string2(), unknown()).optional()
12043
+ });
12044
+ var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
11617
12045
  messages: array(SamplingMessageSchema),
11618
12046
  /**
11619
12047
  * The server's preferences for which model to select. The client MAY modify or omit this request.
@@ -11647,19 +12075,41 @@ var CreateMessageRequestParamsSchema = BaseRequestParamsSchema.extend({
11647
12075
  * Tools that the model may use during generation.
11648
12076
  * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
11649
12077
  */
11650
- tools: optional(array(ToolSchema)),
12078
+ tools: array(ToolSchema).optional(),
11651
12079
  /**
11652
12080
  * Controls how the model uses tools.
11653
12081
  * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
11654
12082
  * Default is `{ mode: "auto" }`.
11655
12083
  */
11656
- toolChoice: optional(ToolChoiceSchema)
12084
+ toolChoice: ToolChoiceSchema.optional()
11657
12085
  });
11658
12086
  var CreateMessageRequestSchema = RequestSchema.extend({
11659
12087
  method: literal("sampling/createMessage"),
11660
12088
  params: CreateMessageRequestParamsSchema
11661
12089
  });
11662
12090
  var CreateMessageResultSchema = ResultSchema.extend({
12091
+ /**
12092
+ * The name of the model that generated the message.
12093
+ */
12094
+ model: string2(),
12095
+ /**
12096
+ * The reason why sampling stopped, if known.
12097
+ *
12098
+ * Standard values:
12099
+ * - "endTurn": Natural end of the assistant's turn
12100
+ * - "stopSequence": A stop sequence was encountered
12101
+ * - "maxTokens": Maximum token limit was reached
12102
+ *
12103
+ * This field is an open string to allow for provider-specific stop reasons.
12104
+ */
12105
+ stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens"]).or(string2())),
12106
+ role: RoleSchema,
12107
+ /**
12108
+ * Response content. Single content block (text, image, or audio).
12109
+ */
12110
+ content: SamplingContentSchema
12111
+ });
12112
+ var CreateMessageResultWithToolsSchema = ResultSchema.extend({
11663
12113
  /**
11664
12114
  * The name of the model that generated the message.
11665
12115
  */
@@ -11676,9 +12126,9 @@ var CreateMessageResultSchema = ResultSchema.extend({
11676
12126
  * This field is an open string to allow for provider-specific stop reasons.
11677
12127
  */
11678
12128
  stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())),
11679
- role: _enum(["user", "assistant"]),
12129
+ role: RoleSchema,
11680
12130
  /**
11681
- * Response content. May be ToolUseContent if stopReason is "toolUse".
12131
+ * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse".
11682
12132
  */
11683
12133
  content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])
11684
12134
  });
@@ -11760,7 +12210,7 @@ var TitledMultiSelectEnumSchemaSchema = object({
11760
12210
  var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
11761
12211
  var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
11762
12212
  var PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
11763
- var ElicitRequestFormParamsSchema = BaseRequestParamsSchema.extend({
12213
+ var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
11764
12214
  /**
11765
12215
  * The elicitation mode.
11766
12216
  *
@@ -11781,7 +12231,7 @@ var ElicitRequestFormParamsSchema = BaseRequestParamsSchema.extend({
11781
12231
  required: array(string2()).optional()
11782
12232
  })
11783
12233
  });
11784
- var ElicitRequestURLParamsSchema = BaseRequestParamsSchema.extend({
12234
+ var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({
11785
12235
  /**
11786
12236
  * The elicitation mode.
11787
12237
  */
@@ -11826,8 +12276,10 @@ var ElicitResultSchema = ResultSchema.extend({
11826
12276
  /**
11827
12277
  * The submitted form data, only present when action is "accept".
11828
12278
  * Contains values matching the requested schema.
12279
+ * Per MCP spec, content is "typically omitted" for decline/cancel actions.
12280
+ * We normalize null to undefined for leniency while maintaining type compatibility.
11829
12281
  */
11830
- content: record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional()
12282
+ content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional())
11831
12283
  });
11832
12284
  var ResourceTemplateReferenceSchema = object({
11833
12285
  type: literal("ref/resource"),
@@ -11901,13 +12353,15 @@ var RootSchema = object({
11901
12353
  _meta: record(string2(), unknown()).optional()
11902
12354
  });
11903
12355
  var ListRootsRequestSchema = RequestSchema.extend({
11904
- method: literal("roots/list")
12356
+ method: literal("roots/list"),
12357
+ params: BaseRequestParamsSchema.optional()
11905
12358
  });
11906
12359
  var ListRootsResultSchema = ResultSchema.extend({
11907
12360
  roots: array(RootSchema)
11908
12361
  });
11909
12362
  var RootsListChangedNotificationSchema = NotificationSchema.extend({
11910
- method: literal("notifications/roots/list_changed")
12363
+ method: literal("notifications/roots/list_changed"),
12364
+ params: NotificationsParamsSchema.optional()
11911
12365
  });
11912
12366
  var ClientRequestSchema = union([
11913
12367
  PingRequestSchema,
@@ -11922,16 +12376,39 @@ var ClientRequestSchema = union([
11922
12376
  SubscribeRequestSchema,
11923
12377
  UnsubscribeRequestSchema,
11924
12378
  CallToolRequestSchema,
11925
- ListToolsRequestSchema
12379
+ ListToolsRequestSchema,
12380
+ GetTaskRequestSchema,
12381
+ GetTaskPayloadRequestSchema,
12382
+ ListTasksRequestSchema,
12383
+ CancelTaskRequestSchema
11926
12384
  ]);
11927
12385
  var ClientNotificationSchema = union([
11928
12386
  CancelledNotificationSchema,
11929
12387
  ProgressNotificationSchema,
11930
12388
  InitializedNotificationSchema,
11931
- RootsListChangedNotificationSchema
12389
+ RootsListChangedNotificationSchema,
12390
+ TaskStatusNotificationSchema
12391
+ ]);
12392
+ var ClientResultSchema = union([
12393
+ EmptyResultSchema,
12394
+ CreateMessageResultSchema,
12395
+ CreateMessageResultWithToolsSchema,
12396
+ ElicitResultSchema,
12397
+ ListRootsResultSchema,
12398
+ GetTaskResultSchema,
12399
+ ListTasksResultSchema,
12400
+ CreateTaskResultSchema
12401
+ ]);
12402
+ var ServerRequestSchema = union([
12403
+ PingRequestSchema,
12404
+ CreateMessageRequestSchema,
12405
+ ElicitRequestSchema,
12406
+ ListRootsRequestSchema,
12407
+ GetTaskRequestSchema,
12408
+ GetTaskPayloadRequestSchema,
12409
+ ListTasksRequestSchema,
12410
+ CancelTaskRequestSchema
11932
12411
  ]);
11933
- var ClientResultSchema = union([EmptyResultSchema, CreateMessageResultSchema, ElicitResultSchema, ListRootsResultSchema]);
11934
- var ServerRequestSchema = union([PingRequestSchema, CreateMessageRequestSchema, ElicitRequestSchema, ListRootsRequestSchema]);
11935
12412
  var ServerNotificationSchema = union([
11936
12413
  CancelledNotificationSchema,
11937
12414
  ProgressNotificationSchema,
@@ -11940,6 +12417,7 @@ var ServerNotificationSchema = union([
11940
12417
  ResourceListChangedNotificationSchema,
11941
12418
  ToolListChangedNotificationSchema,
11942
12419
  PromptListChangedNotificationSchema,
12420
+ TaskStatusNotificationSchema,
11943
12421
  ElicitationCompleteNotificationSchema
11944
12422
  ]);
11945
12423
  var ServerResultSchema = union([
@@ -11952,7 +12430,10 @@ var ServerResultSchema = union([
11952
12430
  ListResourceTemplatesResultSchema,
11953
12431
  ReadResourceResultSchema,
11954
12432
  CallToolResultSchema,
11955
- ListToolsResultSchema
12433
+ ListToolsResultSchema,
12434
+ GetTaskResultSchema,
12435
+ ListTasksResultSchema,
12436
+ CreateTaskResultSchema
11956
12437
  ]);
11957
12438
  var McpError = class _McpError extends Error {
11958
12439
  constructor(code, message, data) {
@@ -11981,8 +12462,7 @@ var UrlElicitationRequiredError = class extends McpError {
11981
12462
  });
11982
12463
  }
11983
12464
  get elicitations() {
11984
- var _a2, _b;
11985
- return (_b = (_a2 = this.data) === null || _a2 === void 0 ? void 0 : _a2.elicitations) !== null && _b !== void 0 ? _b : [];
12465
+ return this.data?.elicitations ?? [];
11986
12466
  }
11987
12467
  };
11988
12468
 
@@ -14018,7 +14498,7 @@ ZodUndefined.create = (params) => {
14018
14498
  ...processCreateParams(params)
14019
14499
  });
14020
14500
  };
14021
- var ZodNull = class extends ZodType2 {
14501
+ var ZodNull2 = class extends ZodType2 {
14022
14502
  _parse(input) {
14023
14503
  const parsedType2 = this._getType(input);
14024
14504
  if (parsedType2 !== ZodParsedType.null) {
@@ -14033,8 +14513,8 @@ var ZodNull = class extends ZodType2 {
14033
14513
  return OK(input.data);
14034
14514
  }
14035
14515
  };
14036
- ZodNull.create = (params) => {
14037
- return new ZodNull({
14516
+ ZodNull2.create = (params) => {
14517
+ return new ZodNull2({
14038
14518
  typeName: ZodFirstPartyTypeKind2.ZodNull,
14039
14519
  ...processCreateParams(params)
14040
14520
  });
@@ -14678,7 +15158,7 @@ var getDiscriminator = (type) => {
14678
15158
  return getDiscriminator(type._def.innerType);
14679
15159
  } else if (type instanceof ZodUndefined) {
14680
15160
  return [void 0];
14681
- } else if (type instanceof ZodNull) {
15161
+ } else if (type instanceof ZodNull2) {
14682
15162
  return [null];
14683
15163
  } else if (type instanceof ZodOptional2) {
14684
15164
  return [void 0, ...getDiscriminator(type.unwrap())];
@@ -15836,7 +16316,7 @@ var booleanType = ZodBoolean2.create;
15836
16316
  var dateType = ZodDate2.create;
15837
16317
  var symbolType = ZodSymbol.create;
15838
16318
  var undefinedType = ZodUndefined.create;
15839
- var nullType = ZodNull.create;
16319
+ var nullType = ZodNull2.create;
15840
16320
  var anyType = ZodAny2.create;
15841
16321
  var unknownType = ZodUnknown2.create;
15842
16322
  var neverType = ZodNever2.create;
@@ -15863,7 +16343,7 @@ var nullableType = ZodNullable2.create;
15863
16343
  var preprocessType = ZodEffects.createWithPreprocess;
15864
16344
  var pipelineType = ZodPipeline.create;
15865
16345
 
15866
- // node_modules/.pnpm/@modelcontextprotocol+sdk@1.23.0_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
16346
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.3_hono@4.11.7_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
15867
16347
  function isZ4Schema(s) {
15868
16348
  const schema = s;
15869
16349
  return !!schema._zod;
@@ -15878,13 +16358,12 @@ function safeParse3(schema, data) {
15878
16358
  return result;
15879
16359
  }
15880
16360
  function getObjectShape(schema) {
15881
- var _a2, _b;
15882
16361
  if (!schema)
15883
16362
  return void 0;
15884
16363
  let rawShape;
15885
16364
  if (isZ4Schema(schema)) {
15886
16365
  const v4Schema = schema;
15887
- rawShape = (_b = (_a2 = v4Schema._zod) === null || _a2 === void 0 ? void 0 : _a2.def) === null || _b === void 0 ? void 0 : _b.shape;
16366
+ rawShape = v4Schema._zod?.def?.shape;
15888
16367
  } else {
15889
16368
  const v3Schema = schema;
15890
16369
  rawShape = v3Schema.shape;
@@ -15894,17 +16373,16 @@ function getObjectShape(schema) {
15894
16373
  if (typeof rawShape === "function") {
15895
16374
  try {
15896
16375
  return rawShape();
15897
- } catch (_c) {
16376
+ } catch {
15898
16377
  return void 0;
15899
16378
  }
15900
16379
  }
15901
16380
  return rawShape;
15902
16381
  }
15903
16382
  function getLiteralValue(schema) {
15904
- var _a2;
15905
16383
  if (isZ4Schema(schema)) {
15906
16384
  const v4Schema = schema;
15907
- const def2 = (_a2 = v4Schema._zod) === null || _a2 === void 0 ? void 0 : _a2.def;
16385
+ const def2 = v4Schema._zod?.def;
15908
16386
  if (def2) {
15909
16387
  if (def2.value !== void 0)
15910
16388
  return def2.value;
@@ -15928,16 +16406,21 @@ function getLiteralValue(schema) {
15928
16406
  return void 0;
15929
16407
  }
15930
16408
 
16409
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.3_hono@4.11.7_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js
16410
+ function isTerminal(status) {
16411
+ return status === "completed" || status === "failed" || status === "cancelled";
16412
+ }
16413
+
15931
16414
  // node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@4.1.13/node_modules/zod-to-json-schema/dist/esm/Options.js
15932
16415
  var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
15933
16416
 
15934
16417
  // node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@4.1.13/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
15935
16418
  var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
15936
16419
 
15937
- // node_modules/.pnpm/@modelcontextprotocol+sdk@1.23.0_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
16420
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.3_hono@4.11.7_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
15938
16421
  function getMethodLiteral(schema) {
15939
16422
  const shape = getObjectShape(schema);
15940
- const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method;
16423
+ const methodSchema = shape?.method;
15941
16424
  if (!methodSchema) {
15942
16425
  throw new Error("Schema is missing a method literal");
15943
16426
  }
@@ -15955,7 +16438,7 @@ function parseWithCompat(schema, data) {
15955
16438
  return result.data;
15956
16439
  }
15957
16440
 
15958
- // node_modules/.pnpm/@modelcontextprotocol+sdk@1.23.0_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
16441
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.3_hono@4.11.7_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
15959
16442
  var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4;
15960
16443
  var Protocol = class {
15961
16444
  constructor(_options) {
@@ -15968,9 +16451,10 @@ var Protocol = class {
15968
16451
  this._progressHandlers = /* @__PURE__ */ new Map();
15969
16452
  this._timeoutInfo = /* @__PURE__ */ new Map();
15970
16453
  this._pendingDebouncedNotifications = /* @__PURE__ */ new Set();
16454
+ this._taskProgressTokens = /* @__PURE__ */ new Map();
16455
+ this._requestResolvers = /* @__PURE__ */ new Map();
15971
16456
  this.setNotificationHandler(CancelledNotificationSchema, (notification) => {
15972
- const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
15973
- controller === null || controller === void 0 ? void 0 : controller.abort(notification.params.reason);
16457
+ this._oncancel(notification);
15974
16458
  });
15975
16459
  this.setNotificationHandler(ProgressNotificationSchema, (notification) => {
15976
16460
  this._onprogress(notification);
@@ -15980,7 +16464,118 @@ var Protocol = class {
15980
16464
  // Automatic pong by default.
15981
16465
  (_request) => ({})
15982
16466
  );
15983
- }
16467
+ this._taskStore = _options?.taskStore;
16468
+ this._taskMessageQueue = _options?.taskMessageQueue;
16469
+ if (this._taskStore) {
16470
+ this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {
16471
+ const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
16472
+ if (!task) {
16473
+ throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
16474
+ }
16475
+ return {
16476
+ ...task
16477
+ };
16478
+ });
16479
+ this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
16480
+ const handleTaskResult = async () => {
16481
+ const taskId = request.params.taskId;
16482
+ if (this._taskMessageQueue) {
16483
+ let queuedMessage;
16484
+ while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
16485
+ if (queuedMessage.type === "response" || queuedMessage.type === "error") {
16486
+ const message = queuedMessage.message;
16487
+ const requestId = message.id;
16488
+ const resolver = this._requestResolvers.get(requestId);
16489
+ if (resolver) {
16490
+ this._requestResolvers.delete(requestId);
16491
+ if (queuedMessage.type === "response") {
16492
+ resolver(message);
16493
+ } else {
16494
+ const errorMessage = message;
16495
+ const error2 = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
16496
+ resolver(error2);
16497
+ }
16498
+ } else {
16499
+ const messageType = queuedMessage.type === "response" ? "Response" : "Error";
16500
+ this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));
16501
+ }
16502
+ continue;
16503
+ }
16504
+ await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });
16505
+ }
16506
+ }
16507
+ const task = await this._taskStore.getTask(taskId, extra.sessionId);
16508
+ if (!task) {
16509
+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
16510
+ }
16511
+ if (!isTerminal(task.status)) {
16512
+ await this._waitForTaskUpdate(taskId, extra.signal);
16513
+ return await handleTaskResult();
16514
+ }
16515
+ if (isTerminal(task.status)) {
16516
+ const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
16517
+ this._clearTaskQueue(taskId);
16518
+ return {
16519
+ ...result,
16520
+ _meta: {
16521
+ ...result._meta,
16522
+ [RELATED_TASK_META_KEY]: {
16523
+ taskId
16524
+ }
16525
+ }
16526
+ };
16527
+ }
16528
+ return await handleTaskResult();
16529
+ };
16530
+ return await handleTaskResult();
16531
+ });
16532
+ this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {
16533
+ try {
16534
+ const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId);
16535
+ return {
16536
+ tasks,
16537
+ nextCursor,
16538
+ _meta: {}
16539
+ };
16540
+ } catch (error2) {
16541
+ throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error2 instanceof Error ? error2.message : String(error2)}`);
16542
+ }
16543
+ });
16544
+ this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {
16545
+ try {
16546
+ const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
16547
+ if (!task) {
16548
+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);
16549
+ }
16550
+ if (isTerminal(task.status)) {
16551
+ throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
16552
+ }
16553
+ await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
16554
+ this._clearTaskQueue(request.params.taskId);
16555
+ const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
16556
+ if (!cancelledTask) {
16557
+ throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
16558
+ }
16559
+ return {
16560
+ _meta: {},
16561
+ ...cancelledTask
16562
+ };
16563
+ } catch (error2) {
16564
+ if (error2 instanceof McpError) {
16565
+ throw error2;
16566
+ }
16567
+ throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error2 instanceof Error ? error2.message : String(error2)}`);
16568
+ }
16569
+ });
16570
+ }
16571
+ }
16572
+ async _oncancel(notification) {
16573
+ if (!notification.params.requestId) {
16574
+ return;
16575
+ }
16576
+ const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
16577
+ controller?.abort(notification.params.reason);
16578
+ }
15984
16579
  _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
15985
16580
  this._timeoutInfo.set(messageId, {
15986
16581
  timeoutId: setTimeout(onTimeout, timeout),
@@ -16020,22 +16615,21 @@ var Protocol = class {
16020
16615
  * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
16021
16616
  */
16022
16617
  async connect(transport) {
16023
- var _a2, _b, _c;
16024
16618
  this._transport = transport;
16025
- const _onclose = (_a2 = this.transport) === null || _a2 === void 0 ? void 0 : _a2.onclose;
16619
+ const _onclose = this.transport?.onclose;
16026
16620
  this._transport.onclose = () => {
16027
- _onclose === null || _onclose === void 0 ? void 0 : _onclose();
16621
+ _onclose?.();
16028
16622
  this._onclose();
16029
16623
  };
16030
- const _onerror = (_b = this.transport) === null || _b === void 0 ? void 0 : _b.onerror;
16624
+ const _onerror = this.transport?.onerror;
16031
16625
  this._transport.onerror = (error2) => {
16032
- _onerror === null || _onerror === void 0 ? void 0 : _onerror(error2);
16626
+ _onerror?.(error2);
16033
16627
  this._onerror(error2);
16034
16628
  };
16035
- const _onmessage = (_c = this._transport) === null || _c === void 0 ? void 0 : _c.onmessage;
16629
+ const _onmessage = this._transport?.onmessage;
16036
16630
  this._transport.onmessage = (message, extra) => {
16037
- _onmessage === null || _onmessage === void 0 ? void 0 : _onmessage(message, extra);
16038
- if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
16631
+ _onmessage?.(message, extra);
16632
+ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
16039
16633
  this._onresponse(message);
16040
16634
  } else if (isJSONRPCRequest(message)) {
16041
16635
  this._onrequest(message, extra);
@@ -16048,80 +16642,131 @@ var Protocol = class {
16048
16642
  await this._transport.start();
16049
16643
  }
16050
16644
  _onclose() {
16051
- var _a2;
16052
16645
  const responseHandlers = this._responseHandlers;
16053
16646
  this._responseHandlers = /* @__PURE__ */ new Map();
16054
16647
  this._progressHandlers.clear();
16648
+ this._taskProgressTokens.clear();
16055
16649
  this._pendingDebouncedNotifications.clear();
16056
- this._transport = void 0;
16057
- (_a2 = this.onclose) === null || _a2 === void 0 ? void 0 : _a2.call(this);
16058
16650
  const error2 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");
16651
+ this._transport = void 0;
16652
+ this.onclose?.();
16059
16653
  for (const handler of responseHandlers.values()) {
16060
16654
  handler(error2);
16061
16655
  }
16062
16656
  }
16063
16657
  _onerror(error2) {
16064
- var _a2;
16065
- (_a2 = this.onerror) === null || _a2 === void 0 ? void 0 : _a2.call(this, error2);
16658
+ this.onerror?.(error2);
16066
16659
  }
16067
16660
  _onnotification(notification) {
16068
- var _a2;
16069
- const handler = (_a2 = this._notificationHandlers.get(notification.method)) !== null && _a2 !== void 0 ? _a2 : this.fallbackNotificationHandler;
16661
+ const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;
16070
16662
  if (handler === void 0) {
16071
16663
  return;
16072
16664
  }
16073
16665
  Promise.resolve().then(() => handler(notification)).catch((error2) => this._onerror(new Error(`Uncaught error in notification handler: ${error2}`)));
16074
16666
  }
16075
16667
  _onrequest(request, extra) {
16076
- var _a2, _b;
16077
- const handler = (_a2 = this._requestHandlers.get(request.method)) !== null && _a2 !== void 0 ? _a2 : this.fallbackRequestHandler;
16668
+ const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
16078
16669
  const capturedTransport = this._transport;
16670
+ const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
16079
16671
  if (handler === void 0) {
16080
- capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({
16672
+ const errorResponse = {
16081
16673
  jsonrpc: "2.0",
16082
16674
  id: request.id,
16083
16675
  error: {
16084
16676
  code: ErrorCode.MethodNotFound,
16085
16677
  message: "Method not found"
16086
16678
  }
16087
- }).catch((error2) => this._onerror(new Error(`Failed to send an error response: ${error2}`)));
16679
+ };
16680
+ if (relatedTaskId && this._taskMessageQueue) {
16681
+ this._enqueueTaskMessage(relatedTaskId, {
16682
+ type: "error",
16683
+ message: errorResponse,
16684
+ timestamp: Date.now()
16685
+ }, capturedTransport?.sessionId).catch((error2) => this._onerror(new Error(`Failed to enqueue error response: ${error2}`)));
16686
+ } else {
16687
+ capturedTransport?.send(errorResponse).catch((error2) => this._onerror(new Error(`Failed to send an error response: ${error2}`)));
16688
+ }
16088
16689
  return;
16089
16690
  }
16090
16691
  const abortController = new AbortController();
16091
16692
  this._requestHandlerAbortControllers.set(request.id, abortController);
16693
+ const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0;
16694
+ const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : void 0;
16092
16695
  const fullExtra = {
16093
16696
  signal: abortController.signal,
16094
- sessionId: capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.sessionId,
16095
- _meta: (_b = request.params) === null || _b === void 0 ? void 0 : _b._meta,
16096
- sendNotification: (notification) => this.notification(notification, { relatedRequestId: request.id }),
16097
- sendRequest: (r, resultSchema, options) => this.request(r, resultSchema, { ...options, relatedRequestId: request.id }),
16098
- authInfo: extra === null || extra === void 0 ? void 0 : extra.authInfo,
16697
+ sessionId: capturedTransport?.sessionId,
16698
+ _meta: request.params?._meta,
16699
+ sendNotification: async (notification) => {
16700
+ const notificationOptions = { relatedRequestId: request.id };
16701
+ if (relatedTaskId) {
16702
+ notificationOptions.relatedTask = { taskId: relatedTaskId };
16703
+ }
16704
+ await this.notification(notification, notificationOptions);
16705
+ },
16706
+ sendRequest: async (r, resultSchema, options) => {
16707
+ const requestOptions = { ...options, relatedRequestId: request.id };
16708
+ if (relatedTaskId && !requestOptions.relatedTask) {
16709
+ requestOptions.relatedTask = { taskId: relatedTaskId };
16710
+ }
16711
+ const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;
16712
+ if (effectiveTaskId && taskStore) {
16713
+ await taskStore.updateTaskStatus(effectiveTaskId, "input_required");
16714
+ }
16715
+ return await this.request(r, resultSchema, requestOptions);
16716
+ },
16717
+ authInfo: extra?.authInfo,
16099
16718
  requestId: request.id,
16100
- requestInfo: extra === null || extra === void 0 ? void 0 : extra.requestInfo
16719
+ requestInfo: extra?.requestInfo,
16720
+ taskId: relatedTaskId,
16721
+ taskStore,
16722
+ taskRequestedTtl: taskCreationParams?.ttl,
16723
+ closeSSEStream: extra?.closeSSEStream,
16724
+ closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
16101
16725
  };
16102
- Promise.resolve().then(() => handler(request, fullExtra)).then((result) => {
16726
+ Promise.resolve().then(() => {
16727
+ if (taskCreationParams) {
16728
+ this.assertTaskHandlerCapability(request.method);
16729
+ }
16730
+ }).then(() => handler(request, fullExtra)).then(async (result) => {
16103
16731
  if (abortController.signal.aborted) {
16104
16732
  return;
16105
16733
  }
16106
- return capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({
16734
+ const response = {
16107
16735
  result,
16108
16736
  jsonrpc: "2.0",
16109
16737
  id: request.id
16110
- });
16111
- }, (error2) => {
16112
- var _a3;
16738
+ };
16739
+ if (relatedTaskId && this._taskMessageQueue) {
16740
+ await this._enqueueTaskMessage(relatedTaskId, {
16741
+ type: "response",
16742
+ message: response,
16743
+ timestamp: Date.now()
16744
+ }, capturedTransport?.sessionId);
16745
+ } else {
16746
+ await capturedTransport?.send(response);
16747
+ }
16748
+ }, async (error2) => {
16113
16749
  if (abortController.signal.aborted) {
16114
16750
  return;
16115
16751
  }
16116
- return capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({
16752
+ const errorResponse = {
16117
16753
  jsonrpc: "2.0",
16118
16754
  id: request.id,
16119
16755
  error: {
16120
16756
  code: Number.isSafeInteger(error2["code"]) ? error2["code"] : ErrorCode.InternalError,
16121
- message: (_a3 = error2.message) !== null && _a3 !== void 0 ? _a3 : "Internal error",
16757
+ message: error2.message ?? "Internal error",
16122
16758
  ...error2["data"] !== void 0 && { data: error2["data"] }
16123
16759
  }
16124
- });
16760
+ };
16761
+ if (relatedTaskId && this._taskMessageQueue) {
16762
+ await this._enqueueTaskMessage(relatedTaskId, {
16763
+ type: "error",
16764
+ message: errorResponse,
16765
+ timestamp: Date.now()
16766
+ }, capturedTransport?.sessionId);
16767
+ } else {
16768
+ await capturedTransport?.send(errorResponse);
16769
+ }
16125
16770
  }).catch((error2) => this._onerror(new Error(`Failed to send response: ${error2}`))).finally(() => {
16126
16771
  this._requestHandlerAbortControllers.delete(request.id);
16127
16772
  });
@@ -16140,6 +16785,9 @@ var Protocol = class {
16140
16785
  try {
16141
16786
  this._resetTimeout(messageId);
16142
16787
  } catch (error2) {
16788
+ this._responseHandlers.delete(messageId);
16789
+ this._progressHandlers.delete(messageId);
16790
+ this._cleanupTimeout(messageId);
16143
16791
  responseHandler(error2);
16144
16792
  return;
16145
16793
  }
@@ -16148,15 +16796,39 @@ var Protocol = class {
16148
16796
  }
16149
16797
  _onresponse(response) {
16150
16798
  const messageId = Number(response.id);
16799
+ const resolver = this._requestResolvers.get(messageId);
16800
+ if (resolver) {
16801
+ this._requestResolvers.delete(messageId);
16802
+ if (isJSONRPCResultResponse(response)) {
16803
+ resolver(response);
16804
+ } else {
16805
+ const error2 = new McpError(response.error.code, response.error.message, response.error.data);
16806
+ resolver(error2);
16807
+ }
16808
+ return;
16809
+ }
16151
16810
  const handler = this._responseHandlers.get(messageId);
16152
16811
  if (handler === void 0) {
16153
16812
  this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
16154
16813
  return;
16155
16814
  }
16156
16815
  this._responseHandlers.delete(messageId);
16157
- this._progressHandlers.delete(messageId);
16158
16816
  this._cleanupTimeout(messageId);
16159
- if (isJSONRPCResponse(response)) {
16817
+ let isTaskResponse = false;
16818
+ if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") {
16819
+ const result = response.result;
16820
+ if (result.task && typeof result.task === "object") {
16821
+ const task = result.task;
16822
+ if (typeof task.taskId === "string") {
16823
+ isTaskResponse = true;
16824
+ this._taskProgressTokens.set(task.taskId, messageId);
16825
+ }
16826
+ }
16827
+ }
16828
+ if (!isTaskResponse) {
16829
+ this._progressHandlers.delete(messageId);
16830
+ }
16831
+ if (isJSONRPCResultResponse(response)) {
16160
16832
  handler(response);
16161
16833
  } else {
16162
16834
  const error2 = McpError.fromError(response.error.code, response.error.message, response.error.data);
@@ -16170,60 +16842,169 @@ var Protocol = class {
16170
16842
  * Closes the connection.
16171
16843
  */
16172
16844
  async close() {
16173
- var _a2;
16174
- await ((_a2 = this._transport) === null || _a2 === void 0 ? void 0 : _a2.close());
16845
+ await this._transport?.close();
16846
+ }
16847
+ /**
16848
+ * Sends a request and returns an AsyncGenerator that yields response messages.
16849
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
16850
+ *
16851
+ * @example
16852
+ * ```typescript
16853
+ * const stream = protocol.requestStream(request, resultSchema, options);
16854
+ * for await (const message of stream) {
16855
+ * switch (message.type) {
16856
+ * case 'taskCreated':
16857
+ * console.log('Task created:', message.task.taskId);
16858
+ * break;
16859
+ * case 'taskStatus':
16860
+ * console.log('Task status:', message.task.status);
16861
+ * break;
16862
+ * case 'result':
16863
+ * console.log('Final result:', message.result);
16864
+ * break;
16865
+ * case 'error':
16866
+ * console.error('Error:', message.error);
16867
+ * break;
16868
+ * }
16869
+ * }
16870
+ * ```
16871
+ *
16872
+ * @experimental Use `client.experimental.tasks.requestStream()` to access this method.
16873
+ */
16874
+ async *requestStream(request, resultSchema, options) {
16875
+ const { task } = options ?? {};
16876
+ if (!task) {
16877
+ try {
16878
+ const result = await this.request(request, resultSchema, options);
16879
+ yield { type: "result", result };
16880
+ } catch (error2) {
16881
+ yield {
16882
+ type: "error",
16883
+ error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2))
16884
+ };
16885
+ }
16886
+ return;
16887
+ }
16888
+ let taskId;
16889
+ try {
16890
+ const createResult = await this.request(request, CreateTaskResultSchema, options);
16891
+ if (createResult.task) {
16892
+ taskId = createResult.task.taskId;
16893
+ yield { type: "taskCreated", task: createResult.task };
16894
+ } else {
16895
+ throw new McpError(ErrorCode.InternalError, "Task creation did not return a task");
16896
+ }
16897
+ while (true) {
16898
+ const task2 = await this.getTask({ taskId }, options);
16899
+ yield { type: "taskStatus", task: task2 };
16900
+ if (isTerminal(task2.status)) {
16901
+ if (task2.status === "completed") {
16902
+ const result = await this.getTaskResult({ taskId }, resultSchema, options);
16903
+ yield { type: "result", result };
16904
+ } else if (task2.status === "failed") {
16905
+ yield {
16906
+ type: "error",
16907
+ error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)
16908
+ };
16909
+ } else if (task2.status === "cancelled") {
16910
+ yield {
16911
+ type: "error",
16912
+ error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)
16913
+ };
16914
+ }
16915
+ return;
16916
+ }
16917
+ if (task2.status === "input_required") {
16918
+ const result = await this.getTaskResult({ taskId }, resultSchema, options);
16919
+ yield { type: "result", result };
16920
+ return;
16921
+ }
16922
+ const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
16923
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
16924
+ options?.signal?.throwIfAborted();
16925
+ }
16926
+ } catch (error2) {
16927
+ yield {
16928
+ type: "error",
16929
+ error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2))
16930
+ };
16931
+ }
16175
16932
  }
16176
16933
  /**
16177
- * Sends a request and wait for a response.
16934
+ * Sends a request and waits for a response.
16178
16935
  *
16179
16936
  * Do not use this method to emit notifications! Use notification() instead.
16180
16937
  */
16181
16938
  request(request, resultSchema, options) {
16182
- const { relatedRequestId, resumptionToken, onresumptiontoken } = options !== null && options !== void 0 ? options : {};
16939
+ const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
16183
16940
  return new Promise((resolve, reject) => {
16184
- var _a2, _b, _c, _d, _e, _f;
16941
+ const earlyReject = (error2) => {
16942
+ reject(error2);
16943
+ };
16185
16944
  if (!this._transport) {
16186
- reject(new Error("Not connected"));
16945
+ earlyReject(new Error("Not connected"));
16187
16946
  return;
16188
16947
  }
16189
- if (((_a2 = this._options) === null || _a2 === void 0 ? void 0 : _a2.enforceStrictCapabilities) === true) {
16190
- this.assertCapabilityForMethod(request.method);
16948
+ if (this._options?.enforceStrictCapabilities === true) {
16949
+ try {
16950
+ this.assertCapabilityForMethod(request.method);
16951
+ if (task) {
16952
+ this.assertTaskCapability(request.method);
16953
+ }
16954
+ } catch (e) {
16955
+ earlyReject(e);
16956
+ return;
16957
+ }
16191
16958
  }
16192
- (_b = options === null || options === void 0 ? void 0 : options.signal) === null || _b === void 0 ? void 0 : _b.throwIfAborted();
16959
+ options?.signal?.throwIfAborted();
16193
16960
  const messageId = this._requestMessageId++;
16194
16961
  const jsonrpcRequest = {
16195
16962
  ...request,
16196
16963
  jsonrpc: "2.0",
16197
16964
  id: messageId
16198
16965
  };
16199
- if (options === null || options === void 0 ? void 0 : options.onprogress) {
16966
+ if (options?.onprogress) {
16200
16967
  this._progressHandlers.set(messageId, options.onprogress);
16201
16968
  jsonrpcRequest.params = {
16202
16969
  ...request.params,
16203
16970
  _meta: {
16204
- ...((_c = request.params) === null || _c === void 0 ? void 0 : _c._meta) || {},
16971
+ ...request.params?._meta || {},
16205
16972
  progressToken: messageId
16206
16973
  }
16207
16974
  };
16208
16975
  }
16976
+ if (task) {
16977
+ jsonrpcRequest.params = {
16978
+ ...jsonrpcRequest.params,
16979
+ task
16980
+ };
16981
+ }
16982
+ if (relatedTask) {
16983
+ jsonrpcRequest.params = {
16984
+ ...jsonrpcRequest.params,
16985
+ _meta: {
16986
+ ...jsonrpcRequest.params?._meta || {},
16987
+ [RELATED_TASK_META_KEY]: relatedTask
16988
+ }
16989
+ };
16990
+ }
16209
16991
  const cancel = (reason) => {
16210
- var _a3;
16211
16992
  this._responseHandlers.delete(messageId);
16212
16993
  this._progressHandlers.delete(messageId);
16213
16994
  this._cleanupTimeout(messageId);
16214
- (_a3 = this._transport) === null || _a3 === void 0 ? void 0 : _a3.send({
16995
+ this._transport?.send({
16215
16996
  jsonrpc: "2.0",
16216
16997
  method: "notifications/cancelled",
16217
16998
  params: {
16218
16999
  requestId: messageId,
16219
17000
  reason: String(reason)
16220
17001
  }
16221
- }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => this._onerror(new Error(`Failed to send cancellation: ${error2}`)));
16222
- reject(reason);
17002
+ }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error3) => this._onerror(new Error(`Failed to send cancellation: ${error3}`)));
17003
+ const error2 = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));
17004
+ reject(error2);
16223
17005
  };
16224
17006
  this._responseHandlers.set(messageId, (response) => {
16225
- var _a3;
16226
- if ((_a3 = options === null || options === void 0 ? void 0 : options.signal) === null || _a3 === void 0 ? void 0 : _a3.aborted) {
17007
+ if (options?.signal?.aborted) {
16227
17008
  return;
16228
17009
  }
16229
17010
  if (response instanceof Error) {
@@ -16240,53 +17021,147 @@ var Protocol = class {
16240
17021
  reject(error2);
16241
17022
  }
16242
17023
  });
16243
- (_d = options === null || options === void 0 ? void 0 : options.signal) === null || _d === void 0 ? void 0 : _d.addEventListener("abort", () => {
16244
- var _a3;
16245
- cancel((_a3 = options === null || options === void 0 ? void 0 : options.signal) === null || _a3 === void 0 ? void 0 : _a3.reason);
17024
+ options?.signal?.addEventListener("abort", () => {
17025
+ cancel(options?.signal?.reason);
16246
17026
  });
16247
- const timeout = (_e = options === null || options === void 0 ? void 0 : options.timeout) !== null && _e !== void 0 ? _e : DEFAULT_REQUEST_TIMEOUT_MSEC;
17027
+ const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
16248
17028
  const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));
16249
- this._setupTimeout(messageId, timeout, options === null || options === void 0 ? void 0 : options.maxTotalTimeout, timeoutHandler, (_f = options === null || options === void 0 ? void 0 : options.resetTimeoutOnProgress) !== null && _f !== void 0 ? _f : false);
16250
- this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => {
16251
- this._cleanupTimeout(messageId);
16252
- reject(error2);
16253
- });
17029
+ this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);
17030
+ const relatedTaskId = relatedTask?.taskId;
17031
+ if (relatedTaskId) {
17032
+ const responseResolver = (response) => {
17033
+ const handler = this._responseHandlers.get(messageId);
17034
+ if (handler) {
17035
+ handler(response);
17036
+ } else {
17037
+ this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));
17038
+ }
17039
+ };
17040
+ this._requestResolvers.set(messageId, responseResolver);
17041
+ this._enqueueTaskMessage(relatedTaskId, {
17042
+ type: "request",
17043
+ message: jsonrpcRequest,
17044
+ timestamp: Date.now()
17045
+ }).catch((error2) => {
17046
+ this._cleanupTimeout(messageId);
17047
+ reject(error2);
17048
+ });
17049
+ } else {
17050
+ this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => {
17051
+ this._cleanupTimeout(messageId);
17052
+ reject(error2);
17053
+ });
17054
+ }
16254
17055
  });
16255
17056
  }
17057
+ /**
17058
+ * Gets the current status of a task.
17059
+ *
17060
+ * @experimental Use `client.experimental.tasks.getTask()` to access this method.
17061
+ */
17062
+ async getTask(params, options) {
17063
+ return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options);
17064
+ }
17065
+ /**
17066
+ * Retrieves the result of a completed task.
17067
+ *
17068
+ * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.
17069
+ */
17070
+ async getTaskResult(params, resultSchema, options) {
17071
+ return this.request({ method: "tasks/result", params }, resultSchema, options);
17072
+ }
17073
+ /**
17074
+ * Lists tasks, optionally starting from a pagination cursor.
17075
+ *
17076
+ * @experimental Use `client.experimental.tasks.listTasks()` to access this method.
17077
+ */
17078
+ async listTasks(params, options) {
17079
+ return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options);
17080
+ }
17081
+ /**
17082
+ * Cancels a specific task.
17083
+ *
17084
+ * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.
17085
+ */
17086
+ async cancelTask(params, options) {
17087
+ return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options);
17088
+ }
16256
17089
  /**
16257
17090
  * Emits a notification, which is a one-way message that does not expect a response.
16258
17091
  */
16259
17092
  async notification(notification, options) {
16260
- var _a2, _b;
16261
17093
  if (!this._transport) {
16262
17094
  throw new Error("Not connected");
16263
17095
  }
16264
17096
  this.assertNotificationCapability(notification.method);
16265
- const debouncedMethods = (_b = (_a2 = this._options) === null || _a2 === void 0 ? void 0 : _a2.debouncedNotificationMethods) !== null && _b !== void 0 ? _b : [];
16266
- const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !(options === null || options === void 0 ? void 0 : options.relatedRequestId);
17097
+ const relatedTaskId = options?.relatedTask?.taskId;
17098
+ if (relatedTaskId) {
17099
+ const jsonrpcNotification2 = {
17100
+ ...notification,
17101
+ jsonrpc: "2.0",
17102
+ params: {
17103
+ ...notification.params,
17104
+ _meta: {
17105
+ ...notification.params?._meta || {},
17106
+ [RELATED_TASK_META_KEY]: options.relatedTask
17107
+ }
17108
+ }
17109
+ };
17110
+ await this._enqueueTaskMessage(relatedTaskId, {
17111
+ type: "notification",
17112
+ message: jsonrpcNotification2,
17113
+ timestamp: Date.now()
17114
+ });
17115
+ return;
17116
+ }
17117
+ const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];
17118
+ const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask;
16267
17119
  if (canDebounce) {
16268
17120
  if (this._pendingDebouncedNotifications.has(notification.method)) {
16269
17121
  return;
16270
17122
  }
16271
17123
  this._pendingDebouncedNotifications.add(notification.method);
16272
17124
  Promise.resolve().then(() => {
16273
- var _a3;
16274
17125
  this._pendingDebouncedNotifications.delete(notification.method);
16275
17126
  if (!this._transport) {
16276
17127
  return;
16277
17128
  }
16278
- const jsonrpcNotification2 = {
17129
+ let jsonrpcNotification2 = {
16279
17130
  ...notification,
16280
17131
  jsonrpc: "2.0"
16281
17132
  };
16282
- (_a3 = this._transport) === null || _a3 === void 0 ? void 0 : _a3.send(jsonrpcNotification2, options).catch((error2) => this._onerror(error2));
17133
+ if (options?.relatedTask) {
17134
+ jsonrpcNotification2 = {
17135
+ ...jsonrpcNotification2,
17136
+ params: {
17137
+ ...jsonrpcNotification2.params,
17138
+ _meta: {
17139
+ ...jsonrpcNotification2.params?._meta || {},
17140
+ [RELATED_TASK_META_KEY]: options.relatedTask
17141
+ }
17142
+ }
17143
+ };
17144
+ }
17145
+ this._transport?.send(jsonrpcNotification2, options).catch((error2) => this._onerror(error2));
16283
17146
  });
16284
17147
  return;
16285
17148
  }
16286
- const jsonrpcNotification = {
17149
+ let jsonrpcNotification = {
16287
17150
  ...notification,
16288
17151
  jsonrpc: "2.0"
16289
17152
  };
17153
+ if (options?.relatedTask) {
17154
+ jsonrpcNotification = {
17155
+ ...jsonrpcNotification,
17156
+ params: {
17157
+ ...jsonrpcNotification.params,
17158
+ _meta: {
17159
+ ...jsonrpcNotification.params?._meta || {},
17160
+ [RELATED_TASK_META_KEY]: options.relatedTask
17161
+ }
17162
+ }
17163
+ };
17164
+ }
16290
17165
  await this._transport.send(jsonrpcNotification, options);
16291
17166
  }
16292
17167
  /**
@@ -16334,6 +17209,150 @@ var Protocol = class {
16334
17209
  removeNotificationHandler(method) {
16335
17210
  this._notificationHandlers.delete(method);
16336
17211
  }
17212
+ /**
17213
+ * Cleans up the progress handler associated with a task.
17214
+ * This should be called when a task reaches a terminal status.
17215
+ */
17216
+ _cleanupTaskProgressHandler(taskId) {
17217
+ const progressToken = this._taskProgressTokens.get(taskId);
17218
+ if (progressToken !== void 0) {
17219
+ this._progressHandlers.delete(progressToken);
17220
+ this._taskProgressTokens.delete(taskId);
17221
+ }
17222
+ }
17223
+ /**
17224
+ * Enqueues a task-related message for side-channel delivery via tasks/result.
17225
+ * @param taskId The task ID to associate the message with
17226
+ * @param message The message to enqueue
17227
+ * @param sessionId Optional session ID for binding the operation to a specific session
17228
+ * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)
17229
+ *
17230
+ * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle
17231
+ * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer
17232
+ * simply propagates the error.
17233
+ */
17234
+ async _enqueueTaskMessage(taskId, message, sessionId) {
17235
+ if (!this._taskStore || !this._taskMessageQueue) {
17236
+ throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
17237
+ }
17238
+ const maxQueueSize = this._options?.maxTaskQueueSize;
17239
+ await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
17240
+ }
17241
+ /**
17242
+ * Clears the message queue for a task and rejects any pending request resolvers.
17243
+ * @param taskId The task ID whose queue should be cleared
17244
+ * @param sessionId Optional session ID for binding the operation to a specific session
17245
+ */
17246
+ async _clearTaskQueue(taskId, sessionId) {
17247
+ if (this._taskMessageQueue) {
17248
+ const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);
17249
+ for (const message of messages) {
17250
+ if (message.type === "request" && isJSONRPCRequest(message.message)) {
17251
+ const requestId = message.message.id;
17252
+ const resolver = this._requestResolvers.get(requestId);
17253
+ if (resolver) {
17254
+ resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed"));
17255
+ this._requestResolvers.delete(requestId);
17256
+ } else {
17257
+ this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));
17258
+ }
17259
+ }
17260
+ }
17261
+ }
17262
+ }
17263
+ /**
17264
+ * Waits for a task update (new messages or status change) with abort signal support.
17265
+ * Uses polling to check for updates at the task's configured poll interval.
17266
+ * @param taskId The task ID to wait for
17267
+ * @param signal Abort signal to cancel the wait
17268
+ * @returns Promise that resolves when an update occurs or rejects if aborted
17269
+ */
17270
+ async _waitForTaskUpdate(taskId, signal) {
17271
+ let interval = this._options?.defaultTaskPollInterval ?? 1e3;
17272
+ try {
17273
+ const task = await this._taskStore?.getTask(taskId);
17274
+ if (task?.pollInterval) {
17275
+ interval = task.pollInterval;
17276
+ }
17277
+ } catch {
17278
+ }
17279
+ return new Promise((resolve, reject) => {
17280
+ if (signal.aborted) {
17281
+ reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
17282
+ return;
17283
+ }
17284
+ const timeoutId = setTimeout(resolve, interval);
17285
+ signal.addEventListener("abort", () => {
17286
+ clearTimeout(timeoutId);
17287
+ reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
17288
+ }, { once: true });
17289
+ });
17290
+ }
17291
+ requestTaskStore(request, sessionId) {
17292
+ const taskStore = this._taskStore;
17293
+ if (!taskStore) {
17294
+ throw new Error("No task store configured");
17295
+ }
17296
+ return {
17297
+ createTask: async (taskParams) => {
17298
+ if (!request) {
17299
+ throw new Error("No request provided");
17300
+ }
17301
+ return await taskStore.createTask(taskParams, request.id, {
17302
+ method: request.method,
17303
+ params: request.params
17304
+ }, sessionId);
17305
+ },
17306
+ getTask: async (taskId) => {
17307
+ const task = await taskStore.getTask(taskId, sessionId);
17308
+ if (!task) {
17309
+ throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
17310
+ }
17311
+ return task;
17312
+ },
17313
+ storeTaskResult: async (taskId, status, result) => {
17314
+ await taskStore.storeTaskResult(taskId, status, result, sessionId);
17315
+ const task = await taskStore.getTask(taskId, sessionId);
17316
+ if (task) {
17317
+ const notification = TaskStatusNotificationSchema.parse({
17318
+ method: "notifications/tasks/status",
17319
+ params: task
17320
+ });
17321
+ await this.notification(notification);
17322
+ if (isTerminal(task.status)) {
17323
+ this._cleanupTaskProgressHandler(taskId);
17324
+ }
17325
+ }
17326
+ },
17327
+ getTaskResult: (taskId) => {
17328
+ return taskStore.getTaskResult(taskId, sessionId);
17329
+ },
17330
+ updateTaskStatus: async (taskId, status, statusMessage) => {
17331
+ const task = await taskStore.getTask(taskId, sessionId);
17332
+ if (!task) {
17333
+ throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`);
17334
+ }
17335
+ if (isTerminal(task.status)) {
17336
+ throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);
17337
+ }
17338
+ await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);
17339
+ const updatedTask = await taskStore.getTask(taskId, sessionId);
17340
+ if (updatedTask) {
17341
+ const notification = TaskStatusNotificationSchema.parse({
17342
+ method: "notifications/tasks/status",
17343
+ params: updatedTask
17344
+ });
17345
+ await this.notification(notification);
17346
+ if (isTerminal(updatedTask.status)) {
17347
+ this._cleanupTaskProgressHandler(taskId);
17348
+ }
17349
+ }
17350
+ },
17351
+ listTasks: (cursor) => {
17352
+ return taskStore.listTasks(cursor, sessionId);
17353
+ }
17354
+ };
17355
+ }
16337
17356
  };
16338
17357
  function isPlainObject2(value) {
16339
17358
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -16355,11 +17374,11 @@ function mergeCapabilities(base, additional) {
16355
17374
  return result;
16356
17375
  }
16357
17376
 
16358
- // node_modules/.pnpm/@modelcontextprotocol+sdk@1.23.0_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js
17377
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.3_hono@4.11.7_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js
16359
17378
  var import_ajv = __toESM(require_ajv(), 1);
16360
17379
  var import_ajv_formats = __toESM(require_dist(), 1);
16361
17380
  function createDefaultAjvInstance() {
16362
- const ajv = new import_ajv.Ajv({
17381
+ const ajv = new import_ajv.default({
16363
17382
  strict: false,
16364
17383
  validateFormats: true,
16365
17384
  validateSchema: false,
@@ -16391,7 +17410,7 @@ var AjvJsonSchemaValidator = class {
16391
17410
  * ```
16392
17411
  */
16393
17412
  constructor(ajv) {
16394
- this._ajv = ajv !== null && ajv !== void 0 ? ajv : createDefaultAjvInstance();
17413
+ this._ajv = ajv ?? createDefaultAjvInstance();
16395
17414
  }
16396
17415
  /**
16397
17416
  * Create a validator for the given JSON Schema
@@ -16403,8 +17422,7 @@ var AjvJsonSchemaValidator = class {
16403
17422
  * @returns A validator function that validates input data
16404
17423
  */
16405
17424
  getValidator(schema) {
16406
- var _a2;
16407
- const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? (_a2 = this._ajv.getSchema(schema.$id)) !== null && _a2 !== void 0 ? _a2 : this._ajv.compile(schema) : this._ajv.compile(schema);
17425
+ const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema) : this._ajv.compile(schema);
16408
17426
  return (input) => {
16409
17427
  const valid = ajvValidator(input);
16410
17428
  if (valid) {
@@ -16424,7 +17442,196 @@ var AjvJsonSchemaValidator = class {
16424
17442
  }
16425
17443
  };
16426
17444
 
16427
- // node_modules/.pnpm/@modelcontextprotocol+sdk@1.23.0_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
17445
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.3_hono@4.11.7_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js
17446
+ var ExperimentalClientTasks = class {
17447
+ constructor(_client) {
17448
+ this._client = _client;
17449
+ }
17450
+ /**
17451
+ * Calls a tool and returns an AsyncGenerator that yields response messages.
17452
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
17453
+ *
17454
+ * This method provides streaming access to tool execution, allowing you to
17455
+ * observe intermediate task status updates for long-running tool calls.
17456
+ * Automatically validates structured output if the tool has an outputSchema.
17457
+ *
17458
+ * @example
17459
+ * ```typescript
17460
+ * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });
17461
+ * for await (const message of stream) {
17462
+ * switch (message.type) {
17463
+ * case 'taskCreated':
17464
+ * console.log('Tool execution started:', message.task.taskId);
17465
+ * break;
17466
+ * case 'taskStatus':
17467
+ * console.log('Tool status:', message.task.status);
17468
+ * break;
17469
+ * case 'result':
17470
+ * console.log('Tool result:', message.result);
17471
+ * break;
17472
+ * case 'error':
17473
+ * console.error('Tool error:', message.error);
17474
+ * break;
17475
+ * }
17476
+ * }
17477
+ * ```
17478
+ *
17479
+ * @param params - Tool call parameters (name and arguments)
17480
+ * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)
17481
+ * @param options - Optional request options (timeout, signal, task creation params, etc.)
17482
+ * @returns AsyncGenerator that yields ResponseMessage objects
17483
+ *
17484
+ * @experimental
17485
+ */
17486
+ async *callToolStream(params, resultSchema = CallToolResultSchema, options) {
17487
+ const clientInternal = this._client;
17488
+ const optionsWithTask = {
17489
+ ...options,
17490
+ // We check if the tool is known to be a task during auto-configuration, but assume
17491
+ // the caller knows what they're doing if they pass this explicitly
17492
+ task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : void 0)
17493
+ };
17494
+ const stream = clientInternal.requestStream({ method: "tools/call", params }, resultSchema, optionsWithTask);
17495
+ const validator = clientInternal.getToolOutputValidator(params.name);
17496
+ for await (const message of stream) {
17497
+ if (message.type === "result" && validator) {
17498
+ const result = message.result;
17499
+ if (!result.structuredContent && !result.isError) {
17500
+ yield {
17501
+ type: "error",
17502
+ error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)
17503
+ };
17504
+ return;
17505
+ }
17506
+ if (result.structuredContent) {
17507
+ try {
17508
+ const validationResult = validator(result.structuredContent);
17509
+ if (!validationResult.valid) {
17510
+ yield {
17511
+ type: "error",
17512
+ error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)
17513
+ };
17514
+ return;
17515
+ }
17516
+ } catch (error2) {
17517
+ if (error2 instanceof McpError) {
17518
+ yield { type: "error", error: error2 };
17519
+ return;
17520
+ }
17521
+ yield {
17522
+ type: "error",
17523
+ error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error2 instanceof Error ? error2.message : String(error2)}`)
17524
+ };
17525
+ return;
17526
+ }
17527
+ }
17528
+ }
17529
+ yield message;
17530
+ }
17531
+ }
17532
+ /**
17533
+ * Gets the current status of a task.
17534
+ *
17535
+ * @param taskId - The task identifier
17536
+ * @param options - Optional request options
17537
+ * @returns The task status
17538
+ *
17539
+ * @experimental
17540
+ */
17541
+ async getTask(taskId, options) {
17542
+ return this._client.getTask({ taskId }, options);
17543
+ }
17544
+ /**
17545
+ * Retrieves the result of a completed task.
17546
+ *
17547
+ * @param taskId - The task identifier
17548
+ * @param resultSchema - Zod schema for validating the result
17549
+ * @param options - Optional request options
17550
+ * @returns The task result
17551
+ *
17552
+ * @experimental
17553
+ */
17554
+ async getTaskResult(taskId, resultSchema, options) {
17555
+ return this._client.getTaskResult({ taskId }, resultSchema, options);
17556
+ }
17557
+ /**
17558
+ * Lists tasks with optional pagination.
17559
+ *
17560
+ * @param cursor - Optional pagination cursor
17561
+ * @param options - Optional request options
17562
+ * @returns List of tasks with optional next cursor
17563
+ *
17564
+ * @experimental
17565
+ */
17566
+ async listTasks(cursor, options) {
17567
+ return this._client.listTasks(cursor ? { cursor } : void 0, options);
17568
+ }
17569
+ /**
17570
+ * Cancels a running task.
17571
+ *
17572
+ * @param taskId - The task identifier
17573
+ * @param options - Optional request options
17574
+ *
17575
+ * @experimental
17576
+ */
17577
+ async cancelTask(taskId, options) {
17578
+ return this._client.cancelTask({ taskId }, options);
17579
+ }
17580
+ /**
17581
+ * Sends a request and returns an AsyncGenerator that yields response messages.
17582
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
17583
+ *
17584
+ * This method provides streaming access to request processing, allowing you to
17585
+ * observe intermediate task status updates for task-augmented requests.
17586
+ *
17587
+ * @param request - The request to send
17588
+ * @param resultSchema - Zod schema for validating the result
17589
+ * @param options - Optional request options (timeout, signal, task creation params, etc.)
17590
+ * @returns AsyncGenerator that yields ResponseMessage objects
17591
+ *
17592
+ * @experimental
17593
+ */
17594
+ requestStream(request, resultSchema, options) {
17595
+ return this._client.requestStream(request, resultSchema, options);
17596
+ }
17597
+ };
17598
+
17599
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.3_hono@4.11.7_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js
17600
+ function assertToolsCallTaskCapability(requests, method, entityName) {
17601
+ if (!requests) {
17602
+ throw new Error(`${entityName} does not support task creation (required for ${method})`);
17603
+ }
17604
+ switch (method) {
17605
+ case "tools/call":
17606
+ if (!requests.tools?.call) {
17607
+ throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);
17608
+ }
17609
+ break;
17610
+ default:
17611
+ break;
17612
+ }
17613
+ }
17614
+ function assertClientRequestTaskCapability(requests, method, entityName) {
17615
+ if (!requests) {
17616
+ throw new Error(`${entityName} does not support task creation (required for ${method})`);
17617
+ }
17618
+ switch (method) {
17619
+ case "sampling/createMessage":
17620
+ if (!requests.sampling?.createMessage) {
17621
+ throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);
17622
+ }
17623
+ break;
17624
+ case "elicitation/create":
17625
+ if (!requests.elicitation?.create) {
17626
+ throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);
17627
+ }
17628
+ break;
17629
+ default:
17630
+ break;
17631
+ }
17632
+ }
17633
+
17634
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.3_hono@4.11.7_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
16428
17635
  function applyElicitationDefaults(schema, data) {
16429
17636
  if (!schema || data === null || typeof data !== "object")
16430
17637
  return;
@@ -16443,12 +17650,16 @@ function applyElicitationDefaults(schema, data) {
16443
17650
  }
16444
17651
  if (Array.isArray(schema.anyOf)) {
16445
17652
  for (const sub of schema.anyOf) {
16446
- applyElicitationDefaults(sub, data);
17653
+ if (typeof sub !== "boolean") {
17654
+ applyElicitationDefaults(sub, data);
17655
+ }
16447
17656
  }
16448
17657
  }
16449
17658
  if (Array.isArray(schema.oneOf)) {
16450
17659
  for (const sub of schema.oneOf) {
16451
- applyElicitationDefaults(sub, data);
17660
+ if (typeof sub !== "boolean") {
17661
+ applyElicitationDefaults(sub, data);
17662
+ }
16452
17663
  }
16453
17664
  }
16454
17665
  }
@@ -16467,12 +17678,58 @@ var Client = class extends Protocol {
16467
17678
  * Initializes this client with the given name and version information.
16468
17679
  */
16469
17680
  constructor(_clientInfo, options) {
16470
- var _a2, _b;
16471
17681
  super(options);
16472
17682
  this._clientInfo = _clientInfo;
16473
17683
  this._cachedToolOutputValidators = /* @__PURE__ */ new Map();
16474
- this._capabilities = (_a2 = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a2 !== void 0 ? _a2 : {};
16475
- this._jsonSchemaValidator = (_b = options === null || options === void 0 ? void 0 : options.jsonSchemaValidator) !== null && _b !== void 0 ? _b : new AjvJsonSchemaValidator();
17684
+ this._cachedKnownTaskTools = /* @__PURE__ */ new Set();
17685
+ this._cachedRequiredTaskTools = /* @__PURE__ */ new Set();
17686
+ this._listChangedDebounceTimers = /* @__PURE__ */ new Map();
17687
+ this._capabilities = options?.capabilities ?? {};
17688
+ this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
17689
+ if (options?.listChanged) {
17690
+ this._pendingListChangedConfig = options.listChanged;
17691
+ }
17692
+ }
17693
+ /**
17694
+ * Set up handlers for list changed notifications based on config and server capabilities.
17695
+ * This should only be called after initialization when server capabilities are known.
17696
+ * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.
17697
+ * @internal
17698
+ */
17699
+ _setupListChangedHandlers(config2) {
17700
+ if (config2.tools && this._serverCapabilities?.tools?.listChanged) {
17701
+ this._setupListChangedHandler("tools", ToolListChangedNotificationSchema, config2.tools, async () => {
17702
+ const result = await this.listTools();
17703
+ return result.tools;
17704
+ });
17705
+ }
17706
+ if (config2.prompts && this._serverCapabilities?.prompts?.listChanged) {
17707
+ this._setupListChangedHandler("prompts", PromptListChangedNotificationSchema, config2.prompts, async () => {
17708
+ const result = await this.listPrompts();
17709
+ return result.prompts;
17710
+ });
17711
+ }
17712
+ if (config2.resources && this._serverCapabilities?.resources?.listChanged) {
17713
+ this._setupListChangedHandler("resources", ResourceListChangedNotificationSchema, config2.resources, async () => {
17714
+ const result = await this.listResources();
17715
+ return result.resources;
17716
+ });
17717
+ }
17718
+ }
17719
+ /**
17720
+ * Access experimental features.
17721
+ *
17722
+ * WARNING: These APIs are experimental and may change without notice.
17723
+ *
17724
+ * @experimental
17725
+ */
17726
+ get experimental() {
17727
+ if (!this._experimental) {
17728
+ this._experimental = {
17729
+ tasks: new ExperimentalClientTasks(this)
17730
+ };
17731
+ }
17732
+ return this._experimental;
16476
17733
  }
16477
17734
  /**
16478
17735
  * Registers new capabilities. This can only be called before connecting to a transport.
@@ -16489,21 +17746,20 @@ var Client = class extends Protocol {
16489
17746
  * Override request handler registration to enforce client-side validation for elicitation.
16490
17747
  */
16491
17748
  setRequestHandler(requestSchema, handler) {
16492
- var _a2, _b, _c;
16493
17749
  const shape = getObjectShape(requestSchema);
16494
- const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method;
17750
+ const methodSchema = shape?.method;
16495
17751
  if (!methodSchema) {
16496
17752
  throw new Error("Schema is missing a method literal");
16497
17753
  }
16498
17754
  let methodValue;
16499
17755
  if (isZ4Schema(methodSchema)) {
16500
17756
  const v4Schema = methodSchema;
16501
- const v4Def = (_a2 = v4Schema._zod) === null || _a2 === void 0 ? void 0 : _a2.def;
16502
- methodValue = (_b = v4Def === null || v4Def === void 0 ? void 0 : v4Def.value) !== null && _b !== void 0 ? _b : v4Schema.value;
17757
+ const v4Def = v4Schema._zod?.def;
17758
+ methodValue = v4Def?.value ?? v4Schema.value;
16503
17759
  } else {
16504
17760
  const v3Schema = methodSchema;
16505
17761
  const legacyDef = v3Schema._def;
16506
- methodValue = (_c = legacyDef === null || legacyDef === void 0 ? void 0 : legacyDef.value) !== null && _c !== void 0 ? _c : v3Schema.value;
17762
+ methodValue = legacyDef?.value ?? v3Schema.value;
16507
17763
  }
16508
17764
  if (typeof methodValue !== "string") {
16509
17765
  throw new Error("Schema method literal must be a string");
@@ -16511,34 +17767,41 @@ var Client = class extends Protocol {
16511
17767
  const method = methodValue;
16512
17768
  if (method === "elicitation/create") {
16513
17769
  const wrappedHandler = async (request, extra) => {
16514
- var _a3, _b2, _c2;
16515
17770
  const validatedRequest = safeParse3(ElicitRequestSchema, request);
16516
17771
  if (!validatedRequest.success) {
16517
17772
  const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
16518
17773
  throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);
16519
17774
  }
16520
17775
  const { params } = validatedRequest.data;
16521
- const mode = (_a3 = params.mode) !== null && _a3 !== void 0 ? _a3 : "form";
17776
+ params.mode = params.mode ?? "form";
16522
17777
  const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);
16523
- if (mode === "form" && !supportsFormMode) {
17778
+ if (params.mode === "form" && !supportsFormMode) {
16524
17779
  throw new McpError(ErrorCode.InvalidParams, "Client does not support form-mode elicitation requests");
16525
17780
  }
16526
- if (mode === "url" && !supportsUrlMode) {
17781
+ if (params.mode === "url" && !supportsUrlMode) {
16527
17782
  throw new McpError(ErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests");
16528
17783
  }
16529
17784
  const result = await Promise.resolve(handler(request, extra));
17785
+ if (params.task) {
17786
+ const taskValidationResult = safeParse3(CreateTaskResultSchema, result);
17787
+ if (!taskValidationResult.success) {
17788
+ const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
17789
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
17790
+ }
17791
+ return taskValidationResult.data;
17792
+ }
16530
17793
  const validationResult = safeParse3(ElicitResultSchema, result);
16531
17794
  if (!validationResult.success) {
16532
17795
  const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
16533
17796
  throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);
16534
17797
  }
16535
17798
  const validatedResult = validationResult.data;
16536
- const requestedSchema = mode === "form" ? params.requestedSchema : void 0;
16537
- if (mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) {
16538
- if ((_c2 = (_b2 = this._capabilities.elicitation) === null || _b2 === void 0 ? void 0 : _b2.form) === null || _c2 === void 0 ? void 0 : _c2.applyDefaults) {
17799
+ const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0;
17800
+ if (params.mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) {
17801
+ if (this._capabilities.elicitation?.form?.applyDefaults) {
16539
17802
  try {
16540
17803
  applyElicitationDefaults(requestedSchema, validatedResult.content);
16541
- } catch (_d) {
17804
+ } catch {
16542
17805
  }
16543
17806
  }
16544
17807
  }
@@ -16546,11 +17809,38 @@ var Client = class extends Protocol {
16546
17809
  };
16547
17810
  return super.setRequestHandler(requestSchema, wrappedHandler);
16548
17811
  }
17812
+ if (method === "sampling/createMessage") {
17813
+ const wrappedHandler = async (request, extra) => {
17814
+ const validatedRequest = safeParse3(CreateMessageRequestSchema, request);
17815
+ if (!validatedRequest.success) {
17816
+ const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
17817
+ throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);
17818
+ }
17819
+ const { params } = validatedRequest.data;
17820
+ const result = await Promise.resolve(handler(request, extra));
17821
+ if (params.task) {
17822
+ const taskValidationResult = safeParse3(CreateTaskResultSchema, result);
17823
+ if (!taskValidationResult.success) {
17824
+ const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
17825
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
17826
+ }
17827
+ return taskValidationResult.data;
17828
+ }
17829
+ const hasTools = params.tools || params.toolChoice;
17830
+ const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;
17831
+ const validationResult = safeParse3(resultSchema, result);
17832
+ if (!validationResult.success) {
17833
+ const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
17834
+ throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);
17835
+ }
17836
+ return validationResult.data;
17837
+ };
17838
+ return super.setRequestHandler(requestSchema, wrappedHandler);
17839
+ }
16549
17840
  return super.setRequestHandler(requestSchema, handler);
16550
17841
  }
16551
17842
  assertCapability(capability, method) {
16552
- var _a2;
16553
- if (!((_a2 = this._serverCapabilities) === null || _a2 === void 0 ? void 0 : _a2[capability])) {
17843
+ if (!this._serverCapabilities?.[capability]) {
16554
17844
  throw new Error(`Server does not support ${capability} (required for ${method})`);
16555
17845
  }
16556
17846
  }
@@ -16583,6 +17873,10 @@ var Client = class extends Protocol {
16583
17873
  await this.notification({
16584
17874
  method: "notifications/initialized"
16585
17875
  });
17876
+ if (this._pendingListChangedConfig) {
17877
+ this._setupListChangedHandlers(this._pendingListChangedConfig);
17878
+ this._pendingListChangedConfig = void 0;
17879
+ }
16586
17880
  } catch (error2) {
16587
17881
  void this.close();
16588
17882
  throw error2;
@@ -16607,16 +17901,15 @@ var Client = class extends Protocol {
16607
17901
  return this._instructions;
16608
17902
  }
16609
17903
  assertCapabilityForMethod(method) {
16610
- var _a2, _b, _c, _d, _e;
16611
17904
  switch (method) {
16612
17905
  case "logging/setLevel":
16613
- if (!((_a2 = this._serverCapabilities) === null || _a2 === void 0 ? void 0 : _a2.logging)) {
17906
+ if (!this._serverCapabilities?.logging) {
16614
17907
  throw new Error(`Server does not support logging (required for ${method})`);
16615
17908
  }
16616
17909
  break;
16617
17910
  case "prompts/get":
16618
17911
  case "prompts/list":
16619
- if (!((_b = this._serverCapabilities) === null || _b === void 0 ? void 0 : _b.prompts)) {
17912
+ if (!this._serverCapabilities?.prompts) {
16620
17913
  throw new Error(`Server does not support prompts (required for ${method})`);
16621
17914
  }
16622
17915
  break;
@@ -16625,7 +17918,7 @@ var Client = class extends Protocol {
16625
17918
  case "resources/read":
16626
17919
  case "resources/subscribe":
16627
17920
  case "resources/unsubscribe":
16628
- if (!((_c = this._serverCapabilities) === null || _c === void 0 ? void 0 : _c.resources)) {
17921
+ if (!this._serverCapabilities?.resources) {
16629
17922
  throw new Error(`Server does not support resources (required for ${method})`);
16630
17923
  }
16631
17924
  if (method === "resources/subscribe" && !this._serverCapabilities.resources.subscribe) {
@@ -16634,12 +17927,12 @@ var Client = class extends Protocol {
16634
17927
  break;
16635
17928
  case "tools/call":
16636
17929
  case "tools/list":
16637
- if (!((_d = this._serverCapabilities) === null || _d === void 0 ? void 0 : _d.tools)) {
17930
+ if (!this._serverCapabilities?.tools) {
16638
17931
  throw new Error(`Server does not support tools (required for ${method})`);
16639
17932
  }
16640
17933
  break;
16641
17934
  case "completion/complete":
16642
- if (!((_e = this._serverCapabilities) === null || _e === void 0 ? void 0 : _e.completions)) {
17935
+ if (!this._serverCapabilities?.completions) {
16643
17936
  throw new Error(`Server does not support completions (required for ${method})`);
16644
17937
  }
16645
17938
  break;
@@ -16650,10 +17943,9 @@ var Client = class extends Protocol {
16650
17943
  }
16651
17944
  }
16652
17945
  assertNotificationCapability(method) {
16653
- var _a2;
16654
17946
  switch (method) {
16655
17947
  case "notifications/roots/list_changed":
16656
- if (!((_a2 = this._capabilities.roots) === null || _a2 === void 0 ? void 0 : _a2.listChanged)) {
17948
+ if (!this._capabilities.roots?.listChanged) {
16657
17949
  throw new Error(`Client does not support roots list changed notifications (required for ${method})`);
16658
17950
  }
16659
17951
  break;
@@ -16666,6 +17958,9 @@ var Client = class extends Protocol {
16666
17958
  }
16667
17959
  }
16668
17960
  assertRequestHandlerCapability(method) {
17961
+ if (!this._capabilities) {
17962
+ return;
17963
+ }
16669
17964
  switch (method) {
16670
17965
  case "sampling/createMessage":
16671
17966
  if (!this._capabilities.sampling) {
@@ -16682,10 +17977,27 @@ var Client = class extends Protocol {
16682
17977
  throw new Error(`Client does not support roots capability (required for ${method})`);
16683
17978
  }
16684
17979
  break;
17980
+ case "tasks/get":
17981
+ case "tasks/list":
17982
+ case "tasks/result":
17983
+ case "tasks/cancel":
17984
+ if (!this._capabilities.tasks) {
17985
+ throw new Error(`Client does not support tasks capability (required for ${method})`);
17986
+ }
17987
+ break;
16685
17988
  case "ping":
16686
17989
  break;
16687
17990
  }
16688
17991
  }
17992
+ assertTaskCapability(method) {
17993
+ assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, "Server");
17994
+ }
17995
+ assertTaskHandlerCapability(method) {
17996
+ if (!this._capabilities) {
17997
+ return;
17998
+ }
17999
+ assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, "Client");
18000
+ }
16689
18001
  async ping(options) {
16690
18002
  return this.request({ method: "ping" }, EmptyResultSchema, options);
16691
18003
  }
@@ -16716,7 +18028,15 @@ var Client = class extends Protocol {
16716
18028
  async unsubscribeResource(params, options) {
16717
18029
  return this.request({ method: "resources/unsubscribe", params }, EmptyResultSchema, options);
16718
18030
  }
18031
+ /**
18032
+ * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.
18033
+ *
18034
+ * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
18035
+ */
16719
18036
  async callTool(params, resultSchema = CallToolResultSchema, options) {
18037
+ if (this.isToolTaskRequired(params.name)) {
18038
+ throw new McpError(ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);
18039
+ }
16720
18040
  const result = await this.request({ method: "tools/call", params }, resultSchema, options);
16721
18041
  const validator = this.getToolOutputValidator(params.name);
16722
18042
  if (validator) {
@@ -16739,17 +18059,39 @@ var Client = class extends Protocol {
16739
18059
  }
16740
18060
  return result;
16741
18061
  }
18062
+ isToolTask(toolName) {
18063
+ if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {
18064
+ return false;
18065
+ }
18066
+ return this._cachedKnownTaskTools.has(toolName);
18067
+ }
18068
+ /**
18069
+ * Check if a tool requires task-based execution.
18070
+ * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.
18071
+ */
18072
+ isToolTaskRequired(toolName) {
18073
+ return this._cachedRequiredTaskTools.has(toolName);
18074
+ }
16742
18075
  /**
16743
18076
  * Cache validators for tool output schemas.
16744
18077
  * Called after listTools() to pre-compile validators for better performance.
16745
18078
  */
16746
- cacheToolOutputSchemas(tools) {
18079
+ cacheToolMetadata(tools) {
16747
18080
  this._cachedToolOutputValidators.clear();
18081
+ this._cachedKnownTaskTools.clear();
18082
+ this._cachedRequiredTaskTools.clear();
16748
18083
  for (const tool of tools) {
16749
18084
  if (tool.outputSchema) {
16750
18085
  const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
16751
18086
  this._cachedToolOutputValidators.set(tool.name, toolValidator);
16752
18087
  }
18088
+ const taskSupport = tool.execution?.taskSupport;
18089
+ if (taskSupport === "required" || taskSupport === "optional") {
18090
+ this._cachedKnownTaskTools.add(tool.name);
18091
+ }
18092
+ if (taskSupport === "required") {
18093
+ this._cachedRequiredTaskTools.add(tool.name);
18094
+ }
16753
18095
  }
16754
18096
  }
16755
18097
  /**
@@ -16760,16 +18102,57 @@ var Client = class extends Protocol {
16760
18102
  }
16761
18103
  async listTools(params, options) {
16762
18104
  const result = await this.request({ method: "tools/list", params }, ListToolsResultSchema, options);
16763
- this.cacheToolOutputSchemas(result.tools);
18105
+ this.cacheToolMetadata(result.tools);
16764
18106
  return result;
16765
18107
  }
18108
+ /**
18109
+ * Set up a single list changed handler.
18110
+ * @internal
18111
+ */
18112
+ _setupListChangedHandler(listType, notificationSchema, options, fetcher) {
18113
+ const parseResult = ListChangedOptionsBaseSchema.safeParse(options);
18114
+ if (!parseResult.success) {
18115
+ throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);
18116
+ }
18117
+ if (typeof options.onChanged !== "function") {
18118
+ throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);
18119
+ }
18120
+ const { autoRefresh, debounceMs } = parseResult.data;
18121
+ const { onChanged } = options;
18122
+ const refresh = async () => {
18123
+ if (!autoRefresh) {
18124
+ onChanged(null, null);
18125
+ return;
18126
+ }
18127
+ try {
18128
+ const items = await fetcher();
18129
+ onChanged(null, items);
18130
+ } catch (e) {
18131
+ const error2 = e instanceof Error ? e : new Error(String(e));
18132
+ onChanged(error2, null);
18133
+ }
18134
+ };
18135
+ const handler = () => {
18136
+ if (debounceMs) {
18137
+ const existingTimer = this._listChangedDebounceTimers.get(listType);
18138
+ if (existingTimer) {
18139
+ clearTimeout(existingTimer);
18140
+ }
18141
+ const timer = setTimeout(refresh, debounceMs);
18142
+ this._listChangedDebounceTimers.set(listType, timer);
18143
+ } else {
18144
+ refresh();
18145
+ }
18146
+ };
18147
+ this.setNotificationHandler(notificationSchema, handler);
18148
+ }
16766
18149
  async sendRootsListChanged() {
16767
18150
  return this.notification({ method: "notifications/roots/list_changed" });
16768
18151
  }
16769
18152
  };
16770
18153
 
16771
18154
  // package.json
16772
- var version2 = "0.1.35";
18155
+ var version2 = "0.1.37";
16773
18156
 
16774
18157
  // node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js
16775
18158
  var crypto;
@@ -16814,7 +18197,7 @@ async function pkceChallenge(length) {
16814
18197
  };
16815
18198
  }
16816
18199
 
16817
- // node_modules/.pnpm/@modelcontextprotocol+sdk@1.23.0_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
18200
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.3_hono@4.11.7_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
16818
18201
  var SafeUrlSchema = url().superRefine((val, ctx) => {
16819
18202
  if (!URL.canParse(val)) {
16820
18203
  ctx.addIssue({
@@ -16914,7 +18297,7 @@ var OAuthTokensSchema = object({
16914
18297
  id_token: string2().optional(),
16915
18298
  // Optional for OAuth 2.1, but necessary in OpenID Connect
16916
18299
  token_type: string2(),
16917
- expires_in: number2().optional(),
18300
+ expires_in: coerce_exports.number().optional(),
16918
18301
  scope: string2().optional(),
16919
18302
  refresh_token: string2().optional()
16920
18303
  }).strip();
@@ -16958,7 +18341,7 @@ var OAuthTokenRevocationRequestSchema = object({
16958
18341
  token_type_hint: string2().optional()
16959
18342
  }).strip();
16960
18343
 
16961
- // node_modules/.pnpm/@modelcontextprotocol+sdk@1.23.0_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js
18344
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.3_hono@4.11.7_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js
16962
18345
  function resourceUrlFromServerUrl(url2) {
16963
18346
  const resourceURL = typeof url2 === "string" ? new URL(url2) : new URL(url2.href);
16964
18347
  resourceURL.hash = "";
@@ -16978,7 +18361,7 @@ function checkResourceAllowed({ requestedResource, configuredResource }) {
16978
18361
  return requestedPath.startsWith(configuredPath);
16979
18362
  }
16980
18363
 
16981
- // node_modules/.pnpm/@modelcontextprotocol+sdk@1.23.0_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js
18364
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.3_hono@4.11.7_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js
16982
18365
  var OAuthError = class extends Error {
16983
18366
  constructor(message, errorUri) {
16984
18367
  super(message);
@@ -17050,6 +18433,9 @@ InvalidClientMetadataError.errorCode = "invalid_client_metadata";
17050
18433
  var InsufficientScopeError = class extends OAuthError {
17051
18434
  };
17052
18435
  InsufficientScopeError.errorCode = "insufficient_scope";
18436
+ var InvalidTargetError = class extends OAuthError {
18437
+ };
18438
+ InvalidTargetError.errorCode = "invalid_target";
17053
18439
  var OAUTH_ERRORS = {
17054
18440
  [InvalidRequestError.errorCode]: InvalidRequestError,
17055
18441
  [InvalidClientError.errorCode]: InvalidClientError,
@@ -17066,13 +18452,14 @@ var OAUTH_ERRORS = {
17066
18452
  [MethodNotAllowedError.errorCode]: MethodNotAllowedError,
17067
18453
  [TooManyRequestsError.errorCode]: TooManyRequestsError,
17068
18454
  [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,
17069
- [InsufficientScopeError.errorCode]: InsufficientScopeError
18455
+ [InsufficientScopeError.errorCode]: InsufficientScopeError,
18456
+ [InvalidTargetError.errorCode]: InvalidTargetError
17070
18457
  };
17071
18458
 
17072
- // node_modules/.pnpm/@modelcontextprotocol+sdk@1.23.0_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
18459
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.3_hono@4.11.7_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
17073
18460
  var UnauthorizedError = class extends Error {
17074
18461
  constructor(message) {
17075
- super(message !== null && message !== void 0 ? message : "Unauthorized");
18462
+ super(message ?? "Unauthorized");
17076
18463
  }
17077
18464
  };
17078
18465
  function isClientAuthMethod(method) {
@@ -17145,22 +18532,20 @@ async function parseErrorResponse(input) {
17145
18532
  }
17146
18533
  }
17147
18534
  async function auth(provider, options) {
17148
- var _a2, _b;
17149
18535
  try {
17150
18536
  return await authInternal(provider, options);
17151
18537
  } catch (error2) {
17152
18538
  if (error2 instanceof InvalidClientError || error2 instanceof UnauthorizedClientError) {
17153
- await ((_a2 = provider.invalidateCredentials) === null || _a2 === void 0 ? void 0 : _a2.call(provider, "all"));
18539
+ await provider.invalidateCredentials?.("all");
17154
18540
  return await authInternal(provider, options);
17155
18541
  } else if (error2 instanceof InvalidGrantError) {
17156
- await ((_b = provider.invalidateCredentials) === null || _b === void 0 ? void 0 : _b.call(provider, "tokens"));
18542
+ await provider.invalidateCredentials?.("tokens");
17157
18543
  return await authInternal(provider, options);
17158
18544
  }
17159
18545
  throw error2;
17160
18546
  }
17161
18547
  }
17162
18548
  async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {
17163
- var _a2, _b;
17164
18549
  let resourceMetadata;
17165
18550
  let authorizationServerUrl;
17166
18551
  try {
@@ -17168,7 +18553,7 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
17168
18553
  if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {
17169
18554
  authorizationServerUrl = resourceMetadata.authorization_servers[0];
17170
18555
  }
17171
- } catch (_c) {
18556
+ } catch {
17172
18557
  }
17173
18558
  if (!authorizationServerUrl) {
17174
18559
  authorizationServerUrl = new URL("/", serverUrl);
@@ -17182,7 +18567,7 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
17182
18567
  if (authorizationCode !== void 0) {
17183
18568
  throw new Error("Existing OAuth client information is required when exchanging an authorization code");
17184
18569
  }
17185
- const supportsUrlBasedClientId = (metadata === null || metadata === void 0 ? void 0 : metadata.client_id_metadata_document_supported) === true;
18570
+ const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true;
17186
18571
  const clientMetadataUrl = provider.clientMetadataUrl;
17187
18572
  if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) {
17188
18573
  throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);
@@ -17192,7 +18577,7 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
17192
18577
  clientInformation = {
17193
18578
  client_id: clientMetadataUrl
17194
18579
  };
17195
- await ((_a2 = provider.saveClientInformation) === null || _a2 === void 0 ? void 0 : _a2.call(provider, clientInformation));
18580
+ await provider.saveClientInformation?.(clientInformation);
17196
18581
  } else {
17197
18582
  if (!provider.saveClientInformation) {
17198
18583
  throw new Error("OAuth client information must be saveable for dynamic registration");
@@ -17206,23 +18591,19 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
17206
18591
  clientInformation = fullInformation;
17207
18592
  }
17208
18593
  }
17209
- if (authorizationCode !== void 0) {
17210
- const codeVerifier2 = await provider.codeVerifier();
17211
- const tokens2 = await exchangeAuthorization(authorizationServerUrl, {
18594
+ const nonInteractiveFlow = !provider.redirectUrl;
18595
+ if (authorizationCode !== void 0 || nonInteractiveFlow) {
18596
+ const tokens2 = await fetchToken(provider, authorizationServerUrl, {
17212
18597
  metadata,
17213
- clientInformation,
17214
- authorizationCode,
17215
- codeVerifier: codeVerifier2,
17216
- redirectUri: provider.redirectUrl,
17217
18598
  resource,
17218
- addClientAuthentication: provider.addClientAuthentication,
18599
+ authorizationCode,
17219
18600
  fetchFn
17220
18601
  });
17221
18602
  await provider.saveTokens(tokens2);
17222
18603
  return "AUTHORIZED";
17223
18604
  }
17224
18605
  const tokens = await provider.tokens();
17225
- if (tokens === null || tokens === void 0 ? void 0 : tokens.refresh_token) {
18606
+ if (tokens?.refresh_token) {
17226
18607
  try {
17227
18608
  const newTokens = await refreshAuthorization(authorizationServerUrl, {
17228
18609
  metadata,
@@ -17247,7 +18628,7 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
17247
18628
  clientInformation,
17248
18629
  state,
17249
18630
  redirectUrl: provider.redirectUrl,
17250
- scope: scope || ((_b = resourceMetadata === null || resourceMetadata === void 0 ? void 0 : resourceMetadata.scopes_supported) === null || _b === void 0 ? void 0 : _b.join(" ")) || provider.clientMetadata.scope,
18631
+ scope: scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope,
17251
18632
  resource
17252
18633
  });
17253
18634
  await provider.saveCodeVerifier(codeVerifier);
@@ -17260,14 +18641,14 @@ function isHttpsUrl(value) {
17260
18641
  try {
17261
18642
  const url2 = new URL(value);
17262
18643
  return url2.protocol === "https:" && url2.pathname !== "/";
17263
- } catch (_a2) {
18644
+ } catch {
17264
18645
  return false;
17265
18646
  }
17266
18647
  }
17267
18648
  async function selectResourceURL(serverUrl, provider, resourceMetadata) {
17268
18649
  const defaultResource = resourceUrlFromServerUrl(serverUrl);
17269
18650
  if (provider.validateResourceURL) {
17270
- return await provider.validateResourceURL(defaultResource, resourceMetadata === null || resourceMetadata === void 0 ? void 0 : resourceMetadata.resource);
18651
+ return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource);
17271
18652
  }
17272
18653
  if (!resourceMetadata) {
17273
18654
  return void 0;
@@ -17291,7 +18672,7 @@ function extractWWWAuthenticateParams(res) {
17291
18672
  if (resourceMetadataMatch) {
17292
18673
  try {
17293
18674
  resourceMetadataUrl = new URL(resourceMetadataMatch);
17294
- } catch (_a2) {
18675
+ } catch {
17295
18676
  }
17296
18677
  }
17297
18678
  const scope = extractFieldFromWwwAuth(res, "scope") || void 0;
@@ -17316,13 +18697,15 @@ function extractFieldFromWwwAuth(response, fieldName) {
17316
18697
  }
17317
18698
  async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
17318
18699
  const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, {
17319
- protocolVersion: opts === null || opts === void 0 ? void 0 : opts.protocolVersion,
17320
- metadataUrl: opts === null || opts === void 0 ? void 0 : opts.resourceMetadataUrl
18700
+ protocolVersion: opts?.protocolVersion,
18701
+ metadataUrl: opts?.resourceMetadataUrl
17321
18702
  });
17322
18703
  if (!response || response.status === 404) {
18704
+ await response?.body?.cancel();
17323
18705
  throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);
17324
18706
  }
17325
18707
  if (!response.ok) {
18708
+ await response.body?.cancel();
17326
18709
  throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);
17327
18710
  }
17328
18711
  return OAuthProtectedResourceMetadataSchema.parse(await response.json());
@@ -17357,19 +18740,18 @@ function shouldAttemptFallback(response, pathname) {
17357
18740
  return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
17358
18741
  }
17359
18742
  async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
17360
- var _a2, _b;
17361
18743
  const issuer = new URL(serverUrl);
17362
- const protocolVersion = (_a2 = opts === null || opts === void 0 ? void 0 : opts.protocolVersion) !== null && _a2 !== void 0 ? _a2 : LATEST_PROTOCOL_VERSION;
18744
+ const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION;
17363
18745
  let url2;
17364
- if (opts === null || opts === void 0 ? void 0 : opts.metadataUrl) {
18746
+ if (opts?.metadataUrl) {
17365
18747
  url2 = new URL(opts.metadataUrl);
17366
18748
  } else {
17367
18749
  const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
17368
- url2 = new URL(wellKnownPath, (_b = opts === null || opts === void 0 ? void 0 : opts.metadataServerUrl) !== null && _b !== void 0 ? _b : issuer);
18750
+ url2 = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer);
17369
18751
  url2.search = issuer.search;
17370
18752
  }
17371
18753
  let response = await tryMetadataDiscovery(url2, protocolVersion, fetchFn);
17372
- if (!(opts === null || opts === void 0 ? void 0 : opts.metadataUrl) && shouldAttemptFallback(response, issuer.pathname)) {
18754
+ if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) {
17373
18755
  const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);
17374
18756
  response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);
17375
18757
  }
@@ -17420,6 +18802,7 @@ async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fet
17420
18802
  continue;
17421
18803
  }
17422
18804
  if (!response.ok) {
18805
+ await response.body?.cancel();
17423
18806
  if (response.status >= 400 && response.status < 500) {
17424
18807
  continue;
17425
18808
  }
@@ -17460,7 +18843,7 @@ async function startAuthorization(authorizationServerUrl, { metadata, clientInfo
17460
18843
  if (scope) {
17461
18844
  authorizationUrl.searchParams.set("scope", scope);
17462
18845
  }
17463
- if (scope === null || scope === void 0 ? void 0 : scope.includes("offline_access")) {
18846
+ if (scope?.includes("offline_access")) {
17464
18847
  authorizationUrl.searchParams.append("prompt", "consent");
17465
18848
  }
17466
18849
  if (resource) {
@@ -17468,37 +18851,34 @@ async function startAuthorization(authorizationServerUrl, { metadata, clientInfo
17468
18851
  }
17469
18852
  return { authorizationUrl, codeVerifier };
17470
18853
  }
17471
- async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) {
17472
- var _a2;
17473
- const grantType = "authorization_code";
17474
- const tokenUrl = (metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint) ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl);
17475
- if ((metadata === null || metadata === void 0 ? void 0 : metadata.grant_types_supported) && !metadata.grant_types_supported.includes(grantType)) {
17476
- throw new Error(`Incompatible auth server: does not support grant type ${grantType}`);
17477
- }
17478
- const headers = new Headers({
17479
- "Content-Type": "application/x-www-form-urlencoded",
17480
- Accept: "application/json"
17481
- });
17482
- const params = new URLSearchParams({
17483
- grant_type: grantType,
18854
+ function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {
18855
+ return new URLSearchParams({
18856
+ grant_type: "authorization_code",
17484
18857
  code: authorizationCode,
17485
18858
  code_verifier: codeVerifier,
17486
18859
  redirect_uri: String(redirectUri)
17487
18860
  });
18861
+ }
18862
+ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {
18863
+ const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl);
18864
+ const headers = new Headers({
18865
+ "Content-Type": "application/x-www-form-urlencoded",
18866
+ Accept: "application/json"
18867
+ });
18868
+ if (resource) {
18869
+ tokenRequestParams.set("resource", resource.href);
18870
+ }
17488
18871
  if (addClientAuthentication) {
17489
- addClientAuthentication(headers, params, authorizationServerUrl, metadata);
17490
- } else {
17491
- const supportedMethods = (_a2 = metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint_auth_methods_supported) !== null && _a2 !== void 0 ? _a2 : [];
18872
+ await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
18873
+ } else if (clientInformation) {
18874
+ const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? [];
17492
18875
  const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
17493
- applyClientAuthentication(authMethod, clientInformation, headers, params);
17494
- }
17495
- if (resource) {
17496
- params.set("resource", resource.href);
18876
+ applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);
17497
18877
  }
17498
- const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, {
18878
+ const response = await (fetchFn ?? fetch)(tokenUrl, {
17499
18879
  method: "POST",
17500
18880
  headers,
17501
- body: params
18881
+ body: tokenRequestParams
17502
18882
  });
17503
18883
  if (!response.ok) {
17504
18884
  throw await parseErrorResponse(response);
@@ -17506,43 +18886,45 @@ async function exchangeAuthorization(authorizationServerUrl, { metadata, clientI
17506
18886
  return OAuthTokensSchema.parse(await response.json());
17507
18887
  }
17508
18888
  async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
17509
- var _a2;
17510
- const grantType = "refresh_token";
17511
- let tokenUrl;
17512
- if (metadata) {
17513
- tokenUrl = new URL(metadata.token_endpoint);
17514
- if (metadata.grant_types_supported && !metadata.grant_types_supported.includes(grantType)) {
17515
- throw new Error(`Incompatible auth server: does not support grant type ${grantType}`);
17516
- }
17517
- } else {
17518
- tokenUrl = new URL("/token", authorizationServerUrl);
17519
- }
17520
- const headers = new Headers({
17521
- "Content-Type": "application/x-www-form-urlencoded"
17522
- });
17523
- const params = new URLSearchParams({
17524
- grant_type: grantType,
18889
+ const tokenRequestParams = new URLSearchParams({
18890
+ grant_type: "refresh_token",
17525
18891
  refresh_token: refreshToken
17526
18892
  });
17527
- if (addClientAuthentication) {
17528
- addClientAuthentication(headers, params, authorizationServerUrl, metadata);
17529
- } else {
17530
- const supportedMethods = (_a2 = metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint_auth_methods_supported) !== null && _a2 !== void 0 ? _a2 : [];
17531
- const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
17532
- applyClientAuthentication(authMethod, clientInformation, headers, params);
18893
+ const tokens = await executeTokenRequest(authorizationServerUrl, {
18894
+ metadata,
18895
+ tokenRequestParams,
18896
+ clientInformation,
18897
+ addClientAuthentication,
18898
+ resource,
18899
+ fetchFn
18900
+ });
18901
+ return { refresh_token: refreshToken, ...tokens };
18902
+ }
18903
+ async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
18904
+ const scope = provider.clientMetadata.scope;
18905
+ let tokenRequestParams;
18906
+ if (provider.prepareTokenRequest) {
18907
+ tokenRequestParams = await provider.prepareTokenRequest(scope);
17533
18908
  }
17534
- if (resource) {
17535
- params.set("resource", resource.href);
18909
+ if (!tokenRequestParams) {
18910
+ if (!authorizationCode) {
18911
+ throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");
18912
+ }
18913
+ if (!provider.redirectUrl) {
18914
+ throw new Error("redirectUrl is required for authorization_code flow");
18915
+ }
18916
+ const codeVerifier = await provider.codeVerifier();
18917
+ tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);
17536
18918
  }
17537
- const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, {
17538
- method: "POST",
17539
- headers,
17540
- body: params
18919
+ const clientInformation = await provider.clientInformation();
18920
+ return executeTokenRequest(authorizationServerUrl, {
18921
+ metadata,
18922
+ tokenRequestParams,
18923
+ clientInformation: clientInformation ?? void 0,
18924
+ addClientAuthentication: provider.addClientAuthentication,
18925
+ resource,
18926
+ fetchFn
17541
18927
  });
17542
- if (!response.ok) {
17543
- throw await parseErrorResponse(response);
17544
- }
17545
- return OAuthTokensSchema.parse({ refresh_token: refreshToken, ...await response.json() });
17546
18928
  }
17547
18929
  async function registerClient(authorizationServerUrl, { metadata, clientMetadata, fetchFn }) {
17548
18930
  let registrationUrl;
@@ -17554,7 +18936,7 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
17554
18936
  } else {
17555
18937
  registrationUrl = new URL("/register", authorizationServerUrl);
17556
18938
  }
17557
- const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(registrationUrl, {
18939
+ const response = await (fetchFn ?? fetch)(registrationUrl, {
17558
18940
  method: "POST",
17559
18941
  headers: {
17560
18942
  "Content-Type": "application/json"
@@ -17967,7 +19349,7 @@ function getBaseURL() {
17967
19349
  return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0;
17968
19350
  }
17969
19351
 
17970
- // node_modules/.pnpm/@modelcontextprotocol+sdk@1.23.0_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js
19352
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.3_hono@4.11.7_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js
17971
19353
  function normalizeHeaders(headers) {
17972
19354
  if (!headers)
17973
19355
  return {};
@@ -17988,13 +19370,13 @@ function createFetchWithInit(baseFetch = fetch, baseInit) {
17988
19370
  ...baseInit,
17989
19371
  ...init,
17990
19372
  // Headers need special handling - merge instead of replace
17991
- headers: (init === null || init === void 0 ? void 0 : init.headers) ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers
19373
+ headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers
17992
19374
  };
17993
19375
  return baseFetch(url2, mergedInit);
17994
19376
  };
17995
19377
  }
17996
19378
 
17997
- // node_modules/.pnpm/@modelcontextprotocol+sdk@1.23.0_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
19379
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.3_hono@4.11.7_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
17998
19380
  var SseError = class extends Error {
17999
19381
  constructor(code, message, event) {
18000
19382
  super(`SSE error: ${message}`);
@@ -18007,14 +19389,13 @@ var SSEClientTransport = class {
18007
19389
  this._url = url2;
18008
19390
  this._resourceMetadataUrl = void 0;
18009
19391
  this._scope = void 0;
18010
- this._eventSourceInit = opts === null || opts === void 0 ? void 0 : opts.eventSourceInit;
18011
- this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit;
18012
- this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider;
18013
- this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch;
18014
- this._fetchWithInit = createFetchWithInit(opts === null || opts === void 0 ? void 0 : opts.fetch, opts === null || opts === void 0 ? void 0 : opts.requestInit);
19392
+ this._eventSourceInit = opts?.eventSourceInit;
19393
+ this._requestInit = opts?.requestInit;
19394
+ this._authProvider = opts?.authProvider;
19395
+ this._fetch = opts?.fetch;
19396
+ this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
18015
19397
  }
18016
19398
  async _authThenStart() {
18017
- var _a2;
18018
19399
  if (!this._authProvider) {
18019
19400
  throw new UnauthorizedError("No auth provider");
18020
19401
  }
@@ -18027,7 +19408,7 @@ var SSEClientTransport = class {
18027
19408
  fetchFn: this._fetchWithInit
18028
19409
  });
18029
19410
  } catch (error2) {
18030
- (_a2 = this.onerror) === null || _a2 === void 0 ? void 0 : _a2.call(this, error2);
19411
+ this.onerror?.(error2);
18031
19412
  throw error2;
18032
19413
  }
18033
19414
  if (result !== "AUTHORIZED") {
@@ -18036,7 +19417,6 @@ var SSEClientTransport = class {
18036
19417
  return await this._startOrAuth();
18037
19418
  }
18038
19419
  async _commonHeaders() {
18039
- var _a2;
18040
19420
  const headers = {};
18041
19421
  if (this._authProvider) {
18042
19422
  const tokens = await this._authProvider.tokens();
@@ -18047,11 +19427,14 @@ var SSEClientTransport = class {
18047
19427
  if (this._protocolVersion) {
18048
19428
  headers["mcp-protocol-version"] = this._protocolVersion;
18049
19429
  }
18050
- return new Headers({ ...headers, ...(_a2 = this._requestInit) === null || _a2 === void 0 ? void 0 : _a2.headers });
19430
+ const extraHeaders = normalizeHeaders(this._requestInit?.headers);
19431
+ return new Headers({
19432
+ ...headers,
19433
+ ...extraHeaders
19434
+ });
18051
19435
  }
18052
19436
  _startOrAuth() {
18053
- var _a2, _b, _c;
18054
- const fetchImpl = (_c = (_b = (_a2 = this === null || this === void 0 ? void 0 : this._eventSourceInit) === null || _a2 === void 0 ? void 0 : _a2.fetch) !== null && _b !== void 0 ? _b : this._fetch) !== null && _c !== void 0 ? _c : fetch;
19437
+ const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
18055
19438
  return new Promise((resolve, reject) => {
18056
19439
  this._eventSource = new EventSource(this._url.href, {
18057
19440
  ...this._eventSourceInit,
@@ -18072,19 +19455,17 @@ var SSEClientTransport = class {
18072
19455
  });
18073
19456
  this._abortController = new AbortController();
18074
19457
  this._eventSource.onerror = (event) => {
18075
- var _a3;
18076
19458
  if (event.code === 401 && this._authProvider) {
18077
19459
  this._authThenStart().then(resolve, reject);
18078
19460
  return;
18079
19461
  }
18080
19462
  const error2 = new SseError(event.code, event.message, event);
18081
19463
  reject(error2);
18082
- (_a3 = this.onerror) === null || _a3 === void 0 ? void 0 : _a3.call(this, error2);
19464
+ this.onerror?.(error2);
18083
19465
  };
18084
19466
  this._eventSource.onopen = () => {
18085
19467
  };
18086
19468
  this._eventSource.addEventListener("endpoint", (event) => {
18087
- var _a3;
18088
19469
  const messageEvent = event;
18089
19470
  try {
18090
19471
  this._endpoint = new URL(messageEvent.data, this._url);
@@ -18093,23 +19474,22 @@ var SSEClientTransport = class {
18093
19474
  }
18094
19475
  } catch (error2) {
18095
19476
  reject(error2);
18096
- (_a3 = this.onerror) === null || _a3 === void 0 ? void 0 : _a3.call(this, error2);
19477
+ this.onerror?.(error2);
18097
19478
  void this.close();
18098
19479
  return;
18099
19480
  }
18100
19481
  resolve();
18101
19482
  });
18102
19483
  this._eventSource.onmessage = (event) => {
18103
- var _a3, _b2;
18104
19484
  const messageEvent = event;
18105
19485
  let message;
18106
19486
  try {
18107
19487
  message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
18108
19488
  } catch (error2) {
18109
- (_a3 = this.onerror) === null || _a3 === void 0 ? void 0 : _a3.call(this, error2);
19489
+ this.onerror?.(error2);
18110
19490
  return;
18111
19491
  }
18112
- (_b2 = this.onmessage) === null || _b2 === void 0 ? void 0 : _b2.call(this, message);
19492
+ this.onmessage?.(message);
18113
19493
  };
18114
19494
  });
18115
19495
  }
@@ -18138,13 +19518,11 @@ var SSEClientTransport = class {
18138
19518
  }
18139
19519
  }
18140
19520
  async close() {
18141
- var _a2, _b, _c;
18142
- (_a2 = this._abortController) === null || _a2 === void 0 ? void 0 : _a2.abort();
18143
- (_b = this._eventSource) === null || _b === void 0 ? void 0 : _b.close();
18144
- (_c = this.onclose) === null || _c === void 0 ? void 0 : _c.call(this);
19521
+ this._abortController?.abort();
19522
+ this._eventSource?.close();
19523
+ this.onclose?.();
18145
19524
  }
18146
19525
  async send(message) {
18147
- var _a2, _b, _c;
18148
19526
  if (!this._endpoint) {
18149
19527
  throw new Error("Not connected");
18150
19528
  }
@@ -18156,10 +19534,11 @@ var SSEClientTransport = class {
18156
19534
  method: "POST",
18157
19535
  headers,
18158
19536
  body: JSON.stringify(message),
18159
- signal: (_a2 = this._abortController) === null || _a2 === void 0 ? void 0 : _a2.signal
19537
+ signal: this._abortController?.signal
18160
19538
  };
18161
- const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._endpoint, init);
19539
+ const response = await (this._fetch ?? fetch)(this._endpoint, init);
18162
19540
  if (!response.ok) {
19541
+ const text = await response.text().catch(() => null);
18163
19542
  if (response.status === 401 && this._authProvider) {
18164
19543
  const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
18165
19544
  this._resourceMetadataUrl = resourceMetadataUrl;
@@ -18175,11 +19554,11 @@ var SSEClientTransport = class {
18175
19554
  }
18176
19555
  return this.send(message);
18177
19556
  }
18178
- const text = await response.text().catch(() => null);
18179
19557
  throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
18180
19558
  }
19559
+ await response.body?.cancel();
18181
19560
  } catch (error2) {
18182
- (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error2);
19561
+ this.onerror?.(error2);
18183
19562
  throw error2;
18184
19563
  }
18185
19564
  }
@@ -18212,7 +19591,7 @@ var EventSourceParserStream = class extends TransformStream {
18212
19591
  }
18213
19592
  };
18214
19593
 
18215
- // node_modules/.pnpm/@modelcontextprotocol+sdk@1.23.0_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
19594
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.3_hono@4.11.7_zod@4.1.13/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
18216
19595
  var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
18217
19596
  initialReconnectionDelay: 1e3,
18218
19597
  maxReconnectionDelay: 3e4,
@@ -18227,20 +19606,18 @@ var StreamableHTTPError = class extends Error {
18227
19606
  };
18228
19607
  var StreamableHTTPClientTransport = class {
18229
19608
  constructor(url2, opts) {
18230
- var _a2;
18231
19609
  this._hasCompletedAuthFlow = false;
18232
19610
  this._url = url2;
18233
19611
  this._resourceMetadataUrl = void 0;
18234
19612
  this._scope = void 0;
18235
- this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit;
18236
- this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider;
18237
- this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch;
18238
- this._fetchWithInit = createFetchWithInit(opts === null || opts === void 0 ? void 0 : opts.fetch, opts === null || opts === void 0 ? void 0 : opts.requestInit);
18239
- this._sessionId = opts === null || opts === void 0 ? void 0 : opts.sessionId;
18240
- this._reconnectionOptions = (_a2 = opts === null || opts === void 0 ? void 0 : opts.reconnectionOptions) !== null && _a2 !== void 0 ? _a2 : DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
19613
+ this._requestInit = opts?.requestInit;
19614
+ this._authProvider = opts?.authProvider;
19615
+ this._fetch = opts?.fetch;
19616
+ this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
19617
+ this._sessionId = opts?.sessionId;
19618
+ this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
18241
19619
  }
18242
19620
  async _authThenStart() {
18243
- var _a2;
18244
19621
  if (!this._authProvider) {
18245
19622
  throw new UnauthorizedError("No auth provider");
18246
19623
  }
@@ -18253,7 +19630,7 @@ var StreamableHTTPClientTransport = class {
18253
19630
  fetchFn: this._fetchWithInit
18254
19631
  });
18255
19632
  } catch (error2) {
18256
- (_a2 = this.onerror) === null || _a2 === void 0 ? void 0 : _a2.call(this, error2);
19633
+ this.onerror?.(error2);
18257
19634
  throw error2;
18258
19635
  }
18259
19636
  if (result !== "AUTHORIZED") {
@@ -18262,7 +19639,6 @@ var StreamableHTTPClientTransport = class {
18262
19639
  return await this._startOrAuthSse({ resumptionToken: void 0 });
18263
19640
  }
18264
19641
  async _commonHeaders() {
18265
- var _a2;
18266
19642
  const headers = {};
18267
19643
  if (this._authProvider) {
18268
19644
  const tokens = await this._authProvider.tokens();
@@ -18276,14 +19652,13 @@ var StreamableHTTPClientTransport = class {
18276
19652
  if (this._protocolVersion) {
18277
19653
  headers["mcp-protocol-version"] = this._protocolVersion;
18278
19654
  }
18279
- const extraHeaders = normalizeHeaders((_a2 = this._requestInit) === null || _a2 === void 0 ? void 0 : _a2.headers);
19655
+ const extraHeaders = normalizeHeaders(this._requestInit?.headers);
18280
19656
  return new Headers({
18281
19657
  ...headers,
18282
19658
  ...extraHeaders
18283
19659
  });
18284
19660
  }
18285
19661
  async _startOrAuthSse(options) {
18286
- var _a2, _b, _c;
18287
19662
  const { resumptionToken } = options;
18288
19663
  try {
18289
19664
  const headers = await this._commonHeaders();
@@ -18291,12 +19666,13 @@ var StreamableHTTPClientTransport = class {
18291
19666
  if (resumptionToken) {
18292
19667
  headers.set("last-event-id", resumptionToken);
18293
19668
  }
18294
- const response = await ((_a2 = this._fetch) !== null && _a2 !== void 0 ? _a2 : fetch)(this._url, {
19669
+ const response = await (this._fetch ?? fetch)(this._url, {
18295
19670
  method: "GET",
18296
19671
  headers,
18297
- signal: (_b = this._abortController) === null || _b === void 0 ? void 0 : _b.signal
19672
+ signal: this._abortController?.signal
18298
19673
  });
18299
19674
  if (!response.ok) {
19675
+ await response.body?.cancel();
18300
19676
  if (response.status === 401 && this._authProvider) {
18301
19677
  return await this._authThenStart();
18302
19678
  }
@@ -18307,7 +19683,7 @@ var StreamableHTTPClientTransport = class {
18307
19683
  }
18308
19684
  this._handleSseStream(response.body, options, true);
18309
19685
  } catch (error2) {
18310
- (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error2);
19686
+ this.onerror?.(error2);
18311
19687
  throw error2;
18312
19688
  }
18313
19689
  }
@@ -18333,17 +19709,15 @@ var StreamableHTTPClientTransport = class {
18333
19709
  * @param attemptCount Current reconnection attempt count for this specific stream
18334
19710
  */
18335
19711
  _scheduleReconnection(options, attemptCount = 0) {
18336
- var _a2;
18337
19712
  const maxRetries = this._reconnectionOptions.maxRetries;
18338
- if (maxRetries > 0 && attemptCount >= maxRetries) {
18339
- (_a2 = this.onerror) === null || _a2 === void 0 ? void 0 : _a2.call(this, new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
19713
+ if (attemptCount >= maxRetries) {
19714
+ this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
18340
19715
  return;
18341
19716
  }
18342
19717
  const delay = this._getNextReconnectionDelay(attemptCount);
18343
- setTimeout(() => {
19718
+ this._reconnectionTimeout = setTimeout(() => {
18344
19719
  this._startOrAuthSse(options).catch((error2) => {
18345
- var _a3;
18346
- (_a3 = this.onerror) === null || _a3 === void 0 ? void 0 : _a3.call(this, new Error(`Failed to reconnect SSE stream: ${error2 instanceof Error ? error2.message : String(error2)}`));
19720
+ this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error2 instanceof Error ? error2.message : String(error2)}`));
18347
19721
  this._scheduleReconnection(options, attemptCount + 1);
18348
19722
  });
18349
19723
  }, delay);
@@ -18355,8 +19729,8 @@ var StreamableHTTPClientTransport = class {
18355
19729
  const { onresumptiontoken, replayMessageId } = options;
18356
19730
  let lastEventId;
18357
19731
  let hasPrimingEvent = false;
19732
+ let receivedResponse = false;
18358
19733
  const processStream = async () => {
18359
- var _a2, _b, _c, _d;
18360
19734
  try {
18361
19735
  const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({
18362
19736
  onRetry: (retryMs) => {
@@ -18371,22 +19745,29 @@ var StreamableHTTPClientTransport = class {
18371
19745
  if (event.id) {
18372
19746
  lastEventId = event.id;
18373
19747
  hasPrimingEvent = true;
18374
- onresumptiontoken === null || onresumptiontoken === void 0 ? void 0 : onresumptiontoken(event.id);
19748
+ onresumptiontoken?.(event.id);
19749
+ }
19750
+ if (!event.data) {
19751
+ continue;
18375
19752
  }
18376
19753
  if (!event.event || event.event === "message") {
18377
19754
  try {
18378
19755
  const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
18379
- if (replayMessageId !== void 0 && isJSONRPCResponse(message)) {
18380
- message.id = replayMessageId;
19756
+ if (isJSONRPCResultResponse(message)) {
19757
+ receivedResponse = true;
19758
+ if (replayMessageId !== void 0) {
19759
+ message.id = replayMessageId;
19760
+ }
18381
19761
  }
18382
- (_a2 = this.onmessage) === null || _a2 === void 0 ? void 0 : _a2.call(this, message);
19762
+ this.onmessage?.(message);
18383
19763
  } catch (error2) {
18384
- (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error2);
19764
+ this.onerror?.(error2);
18385
19765
  }
18386
19766
  }
18387
19767
  }
18388
19768
  const canResume = isReconnectable || hasPrimingEvent;
18389
- if (canResume && this._abortController && !this._abortController.signal.aborted) {
19769
+ const needsReconnect = canResume && !receivedResponse;
19770
+ if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
18390
19771
  this._scheduleReconnection({
18391
19772
  resumptionToken: lastEventId,
18392
19773
  onresumptiontoken,
@@ -18394,9 +19775,10 @@ var StreamableHTTPClientTransport = class {
18394
19775
  }, 0);
18395
19776
  }
18396
19777
  } catch (error2) {
18397
- (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, new Error(`SSE stream disconnected: ${error2}`));
19778
+ this.onerror?.(new Error(`SSE stream disconnected: ${error2}`));
18398
19779
  const canResume = isReconnectable || hasPrimingEvent;
18399
- if (canResume && this._abortController && !this._abortController.signal.aborted) {
19780
+ const needsReconnect = canResume && !receivedResponse;
19781
+ if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
18400
19782
  try {
18401
19783
  this._scheduleReconnection({
18402
19784
  resumptionToken: lastEventId,
@@ -18404,7 +19786,7 @@ var StreamableHTTPClientTransport = class {
18404
19786
  replayMessageId
18405
19787
  }, 0);
18406
19788
  } catch (error3) {
18407
- (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, new Error(`Failed to reconnect: ${error3 instanceof Error ? error3.message : String(error3)}`));
19789
+ this.onerror?.(new Error(`Failed to reconnect: ${error3 instanceof Error ? error3.message : String(error3)}`));
18408
19790
  }
18409
19791
  }
18410
19792
  }
@@ -18436,19 +19818,18 @@ var StreamableHTTPClientTransport = class {
18436
19818
  }
18437
19819
  }
18438
19820
  async close() {
18439
- var _a2, _b;
18440
- (_a2 = this._abortController) === null || _a2 === void 0 ? void 0 : _a2.abort();
18441
- (_b = this.onclose) === null || _b === void 0 ? void 0 : _b.call(this);
19821
+ if (this._reconnectionTimeout) {
19822
+ clearTimeout(this._reconnectionTimeout);
19823
+ this._reconnectionTimeout = void 0;
19824
+ }
19825
+ this._abortController?.abort();
19826
+ this.onclose?.();
18442
19827
  }
18443
19828
  async send(message, options) {
18444
- var _a2, _b, _c, _d;
18445
19829
  try {
18446
19830
  const { resumptionToken, onresumptiontoken } = options || {};
18447
19831
  if (resumptionToken) {
18448
- this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : void 0 }).catch((err) => {
18449
- var _a3;
18450
- return (_a3 = this.onerror) === null || _a3 === void 0 ? void 0 : _a3.call(this, err);
18451
- });
19832
+ this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : void 0 }).catch((err) => this.onerror?.(err));
18452
19833
  return;
18453
19834
  }
18454
19835
  const headers = await this._commonHeaders();
@@ -18459,14 +19840,15 @@ var StreamableHTTPClientTransport = class {
18459
19840
  method: "POST",
18460
19841
  headers,
18461
19842
  body: JSON.stringify(message),
18462
- signal: (_a2 = this._abortController) === null || _a2 === void 0 ? void 0 : _a2.signal
19843
+ signal: this._abortController?.signal
18463
19844
  };
18464
- const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._url, init);
19845
+ const response = await (this._fetch ?? fetch)(this._url, init);
18465
19846
  const sessionId = response.headers.get("mcp-session-id");
18466
19847
  if (sessionId) {
18467
19848
  this._sessionId = sessionId;
18468
19849
  }
18469
19850
  if (!response.ok) {
19851
+ const text = await response.text().catch(() => null);
18470
19852
  if (response.status === 401 && this._authProvider) {
18471
19853
  if (this._hasCompletedAuthFlow) {
18472
19854
  throw new StreamableHTTPError(401, "Server returned 401 after successful authentication");
@@ -18499,7 +19881,7 @@ var StreamableHTTPClientTransport = class {
18499
19881
  if (resourceMetadataUrl) {
18500
19882
  this._resourceMetadataUrl = resourceMetadataUrl;
18501
19883
  }
18502
- this._lastUpscopingHeader = wwwAuthHeader !== null && wwwAuthHeader !== void 0 ? wwwAuthHeader : void 0;
19884
+ this._lastUpscopingHeader = wwwAuthHeader ?? void 0;
18503
19885
  const result = await auth(this._authProvider, {
18504
19886
  serverUrl: this._url,
18505
19887
  resourceMetadataUrl: this._resourceMetadataUrl,
@@ -18512,17 +19894,14 @@ var StreamableHTTPClientTransport = class {
18512
19894
  return this.send(message);
18513
19895
  }
18514
19896
  }
18515
- const text = await response.text().catch(() => null);
18516
- throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
19897
+ throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);
18517
19898
  }
18518
19899
  this._hasCompletedAuthFlow = false;
18519
19900
  this._lastUpscopingHeader = void 0;
18520
19901
  if (response.status === 202) {
19902
+ await response.body?.cancel();
18521
19903
  if (isInitializedNotification(message)) {
18522
- this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => {
18523
- var _a3;
18524
- return (_a3 = this.onerror) === null || _a3 === void 0 ? void 0 : _a3.call(this, err);
18525
- });
19904
+ this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => this.onerror?.(err));
18526
19905
  }
18527
19906
  return;
18528
19907
  }
@@ -18530,20 +19909,23 @@ var StreamableHTTPClientTransport = class {
18530
19909
  const hasRequests = messages.filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0;
18531
19910
  const contentType = response.headers.get("content-type");
18532
19911
  if (hasRequests) {
18533
- if (contentType === null || contentType === void 0 ? void 0 : contentType.includes("text/event-stream")) {
19912
+ if (contentType?.includes("text/event-stream")) {
18534
19913
  this._handleSseStream(response.body, { onresumptiontoken }, false);
18535
- } else if (contentType === null || contentType === void 0 ? void 0 : contentType.includes("application/json")) {
19914
+ } else if (contentType?.includes("application/json")) {
18536
19915
  const data = await response.json();
18537
19916
  const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)];
18538
19917
  for (const msg of responseMessages) {
18539
- (_c = this.onmessage) === null || _c === void 0 ? void 0 : _c.call(this, msg);
19918
+ this.onmessage?.(msg);
18540
19919
  }
18541
19920
  } else {
19921
+ await response.body?.cancel();
18542
19922
  throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);
18543
19923
  }
19924
+ } else {
19925
+ await response.body?.cancel();
18544
19926
  }
18545
19927
  } catch (error2) {
18546
- (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, error2);
19928
+ this.onerror?.(error2);
18547
19929
  throw error2;
18548
19930
  }
18549
19931
  }
@@ -18562,7 +19944,6 @@ var StreamableHTTPClientTransport = class {
18562
19944
  * the server does not allow clients to terminate sessions.
18563
19945
  */
18564
19946
  async terminateSession() {
18565
- var _a2, _b, _c;
18566
19947
  if (!this._sessionId) {
18567
19948
  return;
18568
19949
  }
@@ -18572,15 +19953,16 @@ var StreamableHTTPClientTransport = class {
18572
19953
  ...this._requestInit,
18573
19954
  method: "DELETE",
18574
19955
  headers,
18575
- signal: (_a2 = this._abortController) === null || _a2 === void 0 ? void 0 : _a2.signal
19956
+ signal: this._abortController?.signal
18576
19957
  };
18577
- const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._url, init);
19958
+ const response = await (this._fetch ?? fetch)(this._url, init);
19959
+ await response.body?.cancel();
18578
19960
  if (!response.ok && response.status !== 405) {
18579
19961
  throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);
18580
19962
  }
18581
19963
  this._sessionId = void 0;
18582
19964
  } catch (error2) {
18583
- (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error2);
19965
+ this.onerror?.(error2);
18584
19966
  throw error2;
18585
19967
  }
18586
19968
  }
@@ -18600,7 +19982,7 @@ var StreamableHTTPClientTransport = class {
18600
19982
  async resumeStream(lastEventId, options) {
18601
19983
  await this._startOrAuthSse({
18602
19984
  resumptionToken: lastEventId,
18603
- onresumptiontoken: options === null || options === void 0 ? void 0 : options.onresumptiontoken
19985
+ onresumptiontoken: options?.onresumptiontoken
18604
19986
  });
18605
19987
  }
18606
19988
  };
@@ -18682,7 +20064,7 @@ async function writeJsonFile(serverUrlHash, filename, data) {
18682
20064
  try {
18683
20065
  await ensureConfigDir();
18684
20066
  const filePath = getConfigFilePath(serverUrlHash, filename);
18685
- await fs.writeFile(filePath, JSON.stringify(data, null, 2), "utf-8");
20067
+ await fs.writeFile(filePath, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: 384 });
18686
20068
  } catch (error2) {
18687
20069
  log(`Error writing ${filename}:`, error2);
18688
20070
  throw error2;
@@ -18701,7 +20083,7 @@ async function writeTextFile(serverUrlHash, filename, text) {
18701
20083
  try {
18702
20084
  await ensureConfigDir();
18703
20085
  const filePath = getConfigFilePath(serverUrlHash, filename);
18704
- await fs.writeFile(filePath, text, "utf-8");
20086
+ await fs.writeFile(filePath, text, { encoding: "utf-8", mode: 384 });
18705
20087
  } catch (error2) {
18706
20088
  log(`Error writing ${filename}:`, error2);
18707
20089
  throw error2;