@opentiny/next-sdk 0.1.15-beta.3 → 0.1.15-beta.5

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.
@@ -6851,9 +6851,8 @@
6851
6851
  return new RegExp(`^${regex}$`);
6852
6852
  };
6853
6853
  const integer = /^\d+$/;
6854
- const number$2 = /^-?\d+(?:\.\d+)?/i;
6854
+ const number$1 = /^-?\d+(?:\.\d+)?/i;
6855
6855
  const boolean$1 = /true|false/i;
6856
- const _null$2 = /null/i;
6857
6856
  const lowercase = /^[^A-Z]*$/;
6858
6857
  const uppercase = /^[^a-z]*$/;
6859
6858
  const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
@@ -7663,7 +7662,7 @@
7663
7662
  });
7664
7663
  const $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
7665
7664
  $ZodType.init(inst, def);
7666
- inst._zod.pattern = inst._zod.bag.pattern ?? number$2;
7665
+ inst._zod.pattern = inst._zod.bag.pattern ?? number$1;
7667
7666
  inst._zod.parse = (payload, _ctx) => {
7668
7667
  if (def.coerce)
7669
7668
  try {
@@ -7710,23 +7709,6 @@
7710
7709
  return payload;
7711
7710
  };
7712
7711
  });
7713
- const $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => {
7714
- $ZodType.init(inst, def);
7715
- inst._zod.pattern = _null$2;
7716
- inst._zod.values = /* @__PURE__ */ new Set([null]);
7717
- inst._zod.parse = (payload, _ctx) => {
7718
- const input = payload.value;
7719
- if (input === null)
7720
- return payload;
7721
- payload.issues.push({
7722
- expected: "null",
7723
- code: "invalid_type",
7724
- input,
7725
- inst
7726
- });
7727
- return payload;
7728
- };
7729
- });
7730
7712
  const $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => {
7731
7713
  $ZodType.init(inst, def);
7732
7714
  inst._zod.parse = (payload) => payload;
@@ -8814,14 +8796,6 @@
8814
8796
  ...normalizeParams(params)
8815
8797
  });
8816
8798
  }
8817
- function _coercedNumber(Class, params) {
8818
- return new Class({
8819
- type: "number",
8820
- coerce: true,
8821
- checks: [],
8822
- ...normalizeParams(params)
8823
- });
8824
- }
8825
8799
  function _int(Class, params) {
8826
8800
  return new Class({
8827
8801
  type: "number",
@@ -8837,12 +8811,6 @@
8837
8811
  ...normalizeParams(params)
8838
8812
  });
8839
8813
  }
8840
- function _null$1(Class, params) {
8841
- return new Class({
8842
- type: "null",
8843
- ...normalizeParams(params)
8844
- });
8845
- }
8846
8814
  function _any(Class) {
8847
8815
  return new Class({
8848
8816
  type: "any"
@@ -10066,7 +10034,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
10066
10034
  inst.isFinite = true;
10067
10035
  inst.format = bag.format ?? null;
10068
10036
  });
10069
- function number$1(params) {
10037
+ function number(params) {
10070
10038
  return _number(ZodNumber$1, params);
10071
10039
  }
10072
10040
  const ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
@@ -10083,13 +10051,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
10083
10051
  function boolean(params) {
10084
10052
  return _boolean(ZodBoolean$1, params);
10085
10053
  }
10086
- const ZodNull$1 = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => {
10087
- $ZodNull.init(inst, def);
10088
- ZodType$1.init(inst, def);
10089
- });
10090
- function _null(params) {
10091
- return _null$1(ZodNull$1, params);
10092
- }
10093
10054
  const ZodAny$1 = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => {
10094
10055
  $ZodAny.init(inst, def);
10095
10056
  ZodType$1.init(inst, def);
@@ -10458,47 +10419,20 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
10458
10419
  const ZodIssueCode$1 = {
10459
10420
  custom: "custom"
10460
10421
  };
10461
- function number(params) {
10462
- return _coercedNumber(ZodNumber$1, params);
10463
- }
10464
- const LATEST_PROTOCOL_VERSION = "2025-11-25";
10422
+ const LATEST_PROTOCOL_VERSION = "2025-06-18";
10465
10423
  const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26";
10466
- const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"];
10467
- const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
10424
+ const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-03-26", "2024-11-05", "2024-10-07"];
10468
10425
  const JSONRPC_VERSION = "2.0";
10469
10426
  const AssertObjectSchema = custom((v) => v !== null && (typeof v === "object" || typeof v === "function"));
10470
- const ProgressTokenSchema = union([string(), number$1().int()]);
10427
+ const ProgressTokenSchema = union([string(), number().int()]);
10471
10428
  const CursorSchema = string();
10472
- const TaskCreationParamsSchema = looseObject({
10473
- /**
10474
- * Time in milliseconds to keep task results available after completion.
10475
- * If null, the task has unlimited lifetime until manually cleaned up.
10476
- */
10477
- ttl: union([number$1(), _null()]).optional(),
10478
- /**
10479
- * Time in milliseconds to wait between task status requests.
10480
- */
10481
- pollInterval: number$1().optional()
10482
- });
10483
- const RelatedTaskMetadataSchema = looseObject({
10484
- taskId: string()
10485
- });
10486
10429
  const RequestMetaSchema = looseObject({
10487
10430
  /**
10488
10431
  * 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.
10489
10432
  */
10490
- progressToken: ProgressTokenSchema.optional(),
10491
- /**
10492
- * If specified, this request is related to the provided task.
10493
- */
10494
- [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
10433
+ progressToken: ProgressTokenSchema.optional()
10495
10434
  });
10496
10435
  const BaseRequestParamsSchema = looseObject({
10497
- /**
10498
- * If specified, the caller is requesting that the receiver create a task to represent the request.
10499
- * Task creation parameters are now at the top level instead of in _meta.
10500
- */
10501
- task: TaskCreationParamsSchema.optional(),
10502
10436
  /**
10503
10437
  * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.
10504
10438
  */
@@ -10513,12 +10447,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
10513
10447
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
10514
10448
  * for notes on _meta usage.
10515
10449
  */
10516
- _meta: object$1({
10517
- /**
10518
- * If specified, this notification is related to the provided task.
10519
- */
10520
- [RELATED_TASK_META_KEY]: optional(RelatedTaskMetadataSchema)
10521
- }).passthrough().optional()
10450
+ _meta: record(string(), unknown()).optional()
10522
10451
  });
10523
10452
  const NotificationSchema = object$1({
10524
10453
  method: string(),
@@ -10529,14 +10458,9 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
10529
10458
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
10530
10459
  * for notes on _meta usage.
10531
10460
  */
10532
- _meta: looseObject({
10533
- /**
10534
- * If specified, this result is related to the provided task.
10535
- */
10536
- [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
10537
- }).optional()
10461
+ _meta: record(string(), unknown()).optional()
10538
10462
  });
10539
- const RequestIdSchema = union([string(), number$1().int()]);
10463
+ const RequestIdSchema = union([string(), number().int()]);
10540
10464
  const JSONRPCRequestSchema = object$1({
10541
10465
  jsonrpc: literal(JSONRPC_VERSION),
10542
10466
  id: RequestIdSchema,
@@ -10572,7 +10496,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
10572
10496
  /**
10573
10497
  * The error type that occurred.
10574
10498
  */
10575
- code: number$1().int(),
10499
+ code: number().int(),
10576
10500
  /**
10577
10501
  * A short description of the error. The message SHOULD be limited to a concise single sentence.
10578
10502
  */
@@ -10669,54 +10593,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
10669
10593
  form: FormElicitationCapabilitySchema.optional(),
10670
10594
  url: AssertObjectSchema.optional()
10671
10595
  }), record(string(), unknown()).optional()));
10672
- const ClientTasksCapabilitySchema = object$1({
10673
- /**
10674
- * Present if the client supports listing tasks.
10675
- */
10676
- list: optional(object$1({}).passthrough()),
10677
- /**
10678
- * Present if the client supports cancelling tasks.
10679
- */
10680
- cancel: optional(object$1({}).passthrough()),
10681
- /**
10682
- * Capabilities for task creation on specific request types.
10683
- */
10684
- requests: optional(object$1({
10685
- /**
10686
- * Task support for sampling requests.
10687
- */
10688
- sampling: optional(object$1({
10689
- createMessage: optional(object$1({}).passthrough())
10690
- }).passthrough()),
10691
- /**
10692
- * Task support for elicitation requests.
10693
- */
10694
- elicitation: optional(object$1({
10695
- create: optional(object$1({}).passthrough())
10696
- }).passthrough())
10697
- }).passthrough())
10698
- }).passthrough();
10699
- const ServerTasksCapabilitySchema = object$1({
10700
- /**
10701
- * Present if the server supports listing tasks.
10702
- */
10703
- list: optional(object$1({}).passthrough()),
10704
- /**
10705
- * Present if the server supports cancelling tasks.
10706
- */
10707
- cancel: optional(object$1({}).passthrough()),
10708
- /**
10709
- * Capabilities for task creation on specific request types.
10710
- */
10711
- requests: optional(object$1({
10712
- /**
10713
- * Task support for tool requests.
10714
- */
10715
- tools: optional(object$1({
10716
- call: optional(object$1({}).passthrough())
10717
- }).passthrough())
10718
- }).passthrough())
10719
- }).passthrough();
10720
10596
  const ClientCapabilitiesSchema = object$1({
10721
10597
  /**
10722
10598
  * Experimental, non-standard capabilities that the client supports.
@@ -10748,11 +10624,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
10748
10624
  * Whether the client supports issuing notifications for changes to the roots list.
10749
10625
  */
10750
10626
  listChanged: boolean().optional()
10751
- }).optional(),
10752
- /**
10753
- * Present if the client supports task creation.
10754
- */
10755
- tasks: optional(ClientTasksCapabilitySchema)
10627
+ }).optional()
10756
10628
  });
10757
10629
  const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
10758
10630
  /**
@@ -10810,12 +10682,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
10810
10682
  * Whether this server supports issuing notifications for changes to the tool list.
10811
10683
  */
10812
10684
  listChanged: boolean().optional()
10813
- }).optional(),
10814
- /**
10815
- * Present if the server supports task creation.
10816
- */
10817
- tasks: optional(ServerTasksCapabilitySchema)
10818
- }).passthrough();
10685
+ }).optional()
10686
+ });
10819
10687
  const InitializeResultSchema = ResultSchema.extend({
10820
10688
  /**
10821
10689
  * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.
@@ -10841,11 +10709,11 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
10841
10709
  /**
10842
10710
  * The progress thus far. This should increase every time progress is made, even if the total is unknown.
10843
10711
  */
10844
- progress: number$1(),
10712
+ progress: number(),
10845
10713
  /**
10846
10714
  * Total number of items to process (or total progress required), if known.
10847
10715
  */
10848
- total: optional(number$1()),
10716
+ total: optional(number()),
10849
10717
  /**
10850
10718
  * An optional message describing the current progress.
10851
10719
  */
@@ -10880,62 +10748,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
10880
10748
  */
10881
10749
  nextCursor: optional(CursorSchema)
10882
10750
  });
10883
- const TaskSchema = object$1({
10884
- taskId: string(),
10885
- status: _enum(["working", "input_required", "completed", "failed", "cancelled"]),
10886
- /**
10887
- * Time in milliseconds to keep task results available after completion.
10888
- * If null, the task has unlimited lifetime until manually cleaned up.
10889
- */
10890
- ttl: union([number$1(), _null()]),
10891
- /**
10892
- * ISO 8601 timestamp when the task was created.
10893
- */
10894
- createdAt: string(),
10895
- /**
10896
- * ISO 8601 timestamp when the task was last updated.
10897
- */
10898
- lastUpdatedAt: string(),
10899
- pollInterval: optional(number$1()),
10900
- /**
10901
- * Optional diagnostic message for failed tasks or other status information.
10902
- */
10903
- statusMessage: optional(string())
10904
- });
10905
- const CreateTaskResultSchema = ResultSchema.extend({
10906
- task: TaskSchema
10907
- });
10908
- const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);
10909
- const TaskStatusNotificationSchema = NotificationSchema.extend({
10910
- method: literal("notifications/tasks/status"),
10911
- params: TaskStatusNotificationParamsSchema
10912
- });
10913
- const GetTaskRequestSchema = RequestSchema.extend({
10914
- method: literal("tasks/get"),
10915
- params: BaseRequestParamsSchema.extend({
10916
- taskId: string()
10917
- })
10918
- });
10919
- const GetTaskResultSchema = ResultSchema.merge(TaskSchema);
10920
- const GetTaskPayloadRequestSchema = RequestSchema.extend({
10921
- method: literal("tasks/result"),
10922
- params: BaseRequestParamsSchema.extend({
10923
- taskId: string()
10924
- })
10925
- });
10926
- const ListTasksRequestSchema = PaginatedRequestSchema.extend({
10927
- method: literal("tasks/list")
10928
- });
10929
- const ListTasksResultSchema = PaginatedResultSchema.extend({
10930
- tasks: array(TaskSchema)
10931
- });
10932
- const CancelTaskRequestSchema = RequestSchema.extend({
10933
- method: literal("tasks/cancel"),
10934
- params: BaseRequestParamsSchema.extend({
10935
- taskId: string()
10936
- })
10937
- });
10938
- const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);
10939
10751
  const ResourceContentsSchema = object$1({
10940
10752
  /**
10941
10753
  * The URI of this resource.
@@ -10971,20 +10783,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
10971
10783
  */
10972
10784
  blob: Base64Schema
10973
10785
  });
10974
- const AnnotationsSchema = object$1({
10975
- /**
10976
- * Intended audience(s) for the resource.
10977
- */
10978
- audience: array(_enum(["user", "assistant"])).optional(),
10979
- /**
10980
- * Importance hint for the resource, from 0 (least) to 1 (most).
10981
- */
10982
- priority: number$1().min(0).max(1).optional(),
10983
- /**
10984
- * ISO 8601 timestamp for the most recent modification.
10985
- */
10986
- lastModified: datetime({ offset: true }).optional()
10987
- });
10988
10786
  const ResourceSchema = object$1({
10989
10787
  ...BaseMetadataSchema.shape,
10990
10788
  ...IconsSchema.shape,
@@ -11002,10 +10800,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11002
10800
  * The MIME type of this resource, if known.
11003
10801
  */
11004
10802
  mimeType: optional(string()),
11005
- /**
11006
- * Optional annotations for the client.
11007
- */
11008
- annotations: AnnotationsSchema.optional(),
11009
10803
  /**
11010
10804
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
11011
10805
  * for notes on _meta usage.
@@ -11029,10 +10823,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11029
10823
  * 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.
11030
10824
  */
11031
10825
  mimeType: optional(string()),
11032
- /**
11033
- * Optional annotations for the client.
11034
- */
11035
- annotations: AnnotationsSchema.optional(),
11036
10826
  /**
11037
10827
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
11038
10828
  * for notes on _meta usage.
@@ -11147,10 +10937,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11147
10937
  * The text content of the message.
11148
10938
  */
11149
10939
  text: string(),
11150
- /**
11151
- * Optional annotations for the client.
11152
- */
11153
- annotations: AnnotationsSchema.optional(),
11154
10940
  /**
11155
10941
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
11156
10942
  * for notes on _meta usage.
@@ -11167,10 +10953,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11167
10953
  * The MIME type of the image. Different providers may support different image types.
11168
10954
  */
11169
10955
  mimeType: string(),
11170
- /**
11171
- * Optional annotations for the client.
11172
- */
11173
- annotations: AnnotationsSchema.optional(),
11174
10956
  /**
11175
10957
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
11176
10958
  * for notes on _meta usage.
@@ -11187,10 +10969,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11187
10969
  * The MIME type of the audio. Different providers may support different audio types.
11188
10970
  */
11189
10971
  mimeType: string(),
11190
- /**
11191
- * Optional annotations for the client.
11192
- */
11193
- annotations: AnnotationsSchema.optional(),
11194
10972
  /**
11195
10973
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
11196
10974
  * for notes on _meta usage.
@@ -11223,10 +11001,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11223
11001
  const EmbeddedResourceSchema = object$1({
11224
11002
  type: literal("resource"),
11225
11003
  resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
11226
- /**
11227
- * Optional annotations for the client.
11228
- */
11229
- annotations: AnnotationsSchema.optional(),
11230
11004
  /**
11231
11005
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
11232
11006
  * for notes on _meta usage.
@@ -11296,17 +11070,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11296
11070
  */
11297
11071
  openWorldHint: boolean().optional()
11298
11072
  });
11299
- const ToolExecutionSchema = object$1({
11300
- /**
11301
- * Indicates the tool's preference for task-augmented execution.
11302
- * - "required": Clients MUST invoke the tool as a task
11303
- * - "optional": Clients MAY invoke the tool as a task or normal request
11304
- * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task
11305
- *
11306
- * If not present, defaults to "forbidden".
11307
- */
11308
- taskSupport: _enum(["required", "optional", "forbidden"]).optional()
11309
- });
11310
11073
  const ToolSchema = object$1({
11311
11074
  ...BaseMetadataSchema.shape,
11312
11075
  ...IconsSchema.shape,
@@ -11337,10 +11100,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11337
11100
  * Optional additional tool information.
11338
11101
  */
11339
11102
  annotations: optional(ToolAnnotationsSchema),
11340
- /**
11341
- * Execution-related properties for this tool.
11342
- */
11343
- execution: optional(ToolExecutionSchema),
11344
11103
  /**
11345
11104
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
11346
11105
  * for notes on _meta usage.
@@ -11446,15 +11205,15 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11446
11205
  /**
11447
11206
  * How much to prioritize cost when selecting a model.
11448
11207
  */
11449
- costPriority: optional(number$1().min(0).max(1)),
11208
+ costPriority: optional(number().min(0).max(1)),
11450
11209
  /**
11451
11210
  * How much to prioritize sampling speed (latency) when selecting a model.
11452
11211
  */
11453
- speedPriority: optional(number$1().min(0).max(1)),
11212
+ speedPriority: optional(number().min(0).max(1)),
11454
11213
  /**
11455
11214
  * How much to prioritize intelligence and capabilities when selecting a model.
11456
11215
  */
11457
- intelligencePriority: optional(number$1().min(0).max(1))
11216
+ intelligencePriority: optional(number().min(0).max(1))
11458
11217
  });
11459
11218
  const ToolChoiceSchema = object$1({
11460
11219
  /**
@@ -11477,7 +11236,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11477
11236
  */
11478
11237
  _meta: optional(object$1({}).passthrough())
11479
11238
  }).passthrough();
11480
- const SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);
11481
11239
  const SamplingMessageContentBlockSchema = discriminatedUnion("type", [
11482
11240
  TextContentSchema,
11483
11241
  ImageContentSchema,
@@ -11512,13 +11270,13 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11512
11270
  * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.
11513
11271
  */
11514
11272
  includeContext: _enum(["none", "thisServer", "allServers"]).optional(),
11515
- temperature: number$1().optional(),
11273
+ temperature: number().optional(),
11516
11274
  /**
11517
11275
  * The requested maximum number of tokens to sample (to prevent runaway completions).
11518
11276
  *
11519
11277
  * The client MAY choose to sample fewer tokens than the requested maximum.
11520
11278
  */
11521
- maxTokens: number$1().int(),
11279
+ maxTokens: number().int(),
11522
11280
  stopSequences: array(string()).optional(),
11523
11281
  /**
11524
11282
  * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
@@ -11541,28 +11299,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11541
11299
  params: CreateMessageRequestParamsSchema
11542
11300
  });
11543
11301
  const CreateMessageResultSchema = ResultSchema.extend({
11544
- /**
11545
- * The name of the model that generated the message.
11546
- */
11547
- model: string(),
11548
- /**
11549
- * The reason why sampling stopped, if known.
11550
- *
11551
- * Standard values:
11552
- * - "endTurn": Natural end of the assistant's turn
11553
- * - "stopSequence": A stop sequence was encountered
11554
- * - "maxTokens": Maximum token limit was reached
11555
- *
11556
- * This field is an open string to allow for provider-specific stop reasons.
11557
- */
11558
- stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens"]).or(string())),
11559
- role: _enum(["user", "assistant"]),
11560
- /**
11561
- * Response content. Single content block (text, image, or audio).
11562
- */
11563
- content: SamplingContentSchema
11564
- });
11565
- const CreateMessageResultWithToolsSchema = ResultSchema.extend({
11566
11302
  /**
11567
11303
  * The name of the model that generated the message.
11568
11304
  */
@@ -11581,7 +11317,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11581
11317
  stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string())),
11582
11318
  role: _enum(["user", "assistant"]),
11583
11319
  /**
11584
- * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse".
11320
+ * Response content. May be ToolUseContent if stopReason is "toolUse".
11585
11321
  */
11586
11322
  content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])
11587
11323
  });
@@ -11595,8 +11331,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11595
11331
  type: literal("string"),
11596
11332
  title: string().optional(),
11597
11333
  description: string().optional(),
11598
- minLength: number$1().optional(),
11599
- maxLength: number$1().optional(),
11334
+ minLength: number().optional(),
11335
+ maxLength: number().optional(),
11600
11336
  format: _enum(["email", "uri", "date", "date-time"]).optional(),
11601
11337
  default: string().optional()
11602
11338
  });
@@ -11604,9 +11340,9 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11604
11340
  type: _enum(["number", "integer"]),
11605
11341
  title: string().optional(),
11606
11342
  description: string().optional(),
11607
- minimum: number$1().optional(),
11608
- maximum: number$1().optional(),
11609
- default: number$1().optional()
11343
+ minimum: number().optional(),
11344
+ maximum: number().optional(),
11345
+ default: number().optional()
11610
11346
  });
11611
11347
  const UntitledSingleSelectEnumSchemaSchema = object$1({
11612
11348
  type: literal("string"),
@@ -11638,8 +11374,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11638
11374
  type: literal("array"),
11639
11375
  title: string().optional(),
11640
11376
  description: string().optional(),
11641
- minItems: number$1().optional(),
11642
- maxItems: number$1().optional(),
11377
+ minItems: number().optional(),
11378
+ maxItems: number().optional(),
11643
11379
  items: object$1({
11644
11380
  type: literal("string"),
11645
11381
  enum: array(string())
@@ -11650,8 +11386,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11650
11386
  type: literal("array"),
11651
11387
  title: string().optional(),
11652
11388
  description: string().optional(),
11653
- minItems: number$1().optional(),
11654
- maxItems: number$1().optional(),
11389
+ minItems: number().optional(),
11390
+ maxItems: number().optional(),
11655
11391
  items: object$1({
11656
11392
  anyOf: array(object$1({
11657
11393
  const: string(),
@@ -11729,10 +11465,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11729
11465
  /**
11730
11466
  * The submitted form data, only present when action is "accept".
11731
11467
  * Contains values matching the requested schema.
11732
- * Per MCP spec, content is "typically omitted" for decline/cancel actions.
11733
- * We normalize null to undefined for leniency while maintaining type compatibility.
11734
11468
  */
11735
- content: preprocess((val) => val === null ? void 0 : val, record(string(), union([string(), number$1(), boolean(), array(string())])).optional())
11469
+ content: record(string(), union([string(), number(), boolean(), array(string())])).optional()
11736
11470
  });
11737
11471
  const ResourceTemplateReferenceSchema = object$1({
11738
11472
  type: literal("ref/resource"),
@@ -11794,7 +11528,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11794
11528
  /**
11795
11529
  * The total number of completion options available. This can exceed the number of values actually sent in the response.
11796
11530
  */
11797
- total: optional(number$1().int()),
11531
+ total: optional(number().int()),
11798
11532
  /**
11799
11533
  * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
11800
11534
  */
@@ -11838,37 +11572,16 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11838
11572
  SubscribeRequestSchema,
11839
11573
  UnsubscribeRequestSchema,
11840
11574
  CallToolRequestSchema,
11841
- ListToolsRequestSchema,
11842
- GetTaskRequestSchema,
11843
- GetTaskPayloadRequestSchema,
11844
- ListTasksRequestSchema
11575
+ ListToolsRequestSchema
11845
11576
  ]);
11846
11577
  const ClientNotificationSchema = union([
11847
11578
  CancelledNotificationSchema,
11848
11579
  ProgressNotificationSchema,
11849
11580
  InitializedNotificationSchema,
11850
- RootsListChangedNotificationSchema,
11851
- TaskStatusNotificationSchema
11852
- ]);
11853
- const ClientResultSchema = union([
11854
- EmptyResultSchema,
11855
- CreateMessageResultSchema,
11856
- CreateMessageResultWithToolsSchema,
11857
- ElicitResultSchema,
11858
- ListRootsResultSchema,
11859
- GetTaskResultSchema,
11860
- ListTasksResultSchema,
11861
- CreateTaskResultSchema
11862
- ]);
11863
- const ServerRequestSchema = union([
11864
- PingRequestSchema,
11865
- CreateMessageRequestSchema,
11866
- ElicitRequestSchema,
11867
- ListRootsRequestSchema,
11868
- GetTaskRequestSchema,
11869
- GetTaskPayloadRequestSchema,
11870
- ListTasksRequestSchema
11581
+ RootsListChangedNotificationSchema
11871
11582
  ]);
11583
+ const ClientResultSchema = union([EmptyResultSchema, CreateMessageResultSchema, ElicitResultSchema, ListRootsResultSchema]);
11584
+ const ServerRequestSchema = union([PingRequestSchema, CreateMessageRequestSchema, ElicitRequestSchema, ListRootsRequestSchema]);
11872
11585
  const ServerNotificationSchema = union([
11873
11586
  CancelledNotificationSchema,
11874
11587
  ProgressNotificationSchema,
@@ -11877,7 +11590,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11877
11590
  ResourceListChangedNotificationSchema,
11878
11591
  ToolListChangedNotificationSchema,
11879
11592
  PromptListChangedNotificationSchema,
11880
- TaskStatusNotificationSchema,
11881
11593
  ElicitationCompleteNotificationSchema
11882
11594
  ]);
11883
11595
  const ServerResultSchema = union([
@@ -11890,10 +11602,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11890
11602
  ListResourceTemplatesResultSchema,
11891
11603
  ReadResourceResultSchema,
11892
11604
  CallToolResultSchema,
11893
- ListToolsResultSchema,
11894
- GetTaskResultSchema,
11895
- ListTasksResultSchema,
11896
- CreateTaskResultSchema
11605
+ ListToolsResultSchema
11897
11606
  ]);
11898
11607
  class McpError extends Error {
11899
11608
  constructor(code2, message, data) {
@@ -12175,7 +11884,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
12175
11884
  if (metadata2.title !== void 0 && metadata2.title !== "") {
12176
11885
  return metadata2.title;
12177
11886
  }
12178
- if ("annotations" in metadata2 && ((_a = metadata2.annotations) === null || _a === void 0 ? void 0 : _a.title)) {
11887
+ if ((_a = metadata2.annotations) === null || _a === void 0 ? void 0 : _a.title) {
12179
11888
  return metadata2.annotations.title;
12180
11889
  }
12181
11890
  return metadata2.name;
@@ -15867,7 +15576,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
15867
15576
  if (isZ4Schema(schema)) {
15868
15577
  const v4Schema = schema;
15869
15578
  const def = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def;
15870
- if (def && (def.type === "object" || def.shape !== void 0)) {
15579
+ if (def && (def.typeName === "object" || def.shape !== void 0)) {
15871
15580
  return schema;
15872
15581
  }
15873
15582
  } else {
@@ -15910,7 +15619,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
15910
15619
  var _a, _b, _c;
15911
15620
  if (isZ4Schema(schema)) {
15912
15621
  const v4Schema = schema;
15913
- return ((_b = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def) === null || _b === void 0 ? void 0 : _b.type) === "optional";
15622
+ return ((_b = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def) === null || _b === void 0 ? void 0 : _b.typeName) === "ZodOptional";
15914
15623
  }
15915
15624
  const v3Schema = schema;
15916
15625
  if (typeof schema.isOptional === "function") {
@@ -15945,9 +15654,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
15945
15654
  return directValue;
15946
15655
  return void 0;
15947
15656
  }
15948
- function isTerminal(status) {
15949
- return status === "completed" || status === "failed" || status === "cancelled";
15950
- }
15951
15657
  const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
15952
15658
  const defaultOptions = {
15953
15659
  name: void 0,
@@ -17204,10 +16910,9 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
17204
16910
  this._progressHandlers = /* @__PURE__ */ new Map();
17205
16911
  this._timeoutInfo = /* @__PURE__ */ new Map();
17206
16912
  this._pendingDebouncedNotifications = /* @__PURE__ */ new Set();
17207
- this._taskProgressTokens = /* @__PURE__ */ new Map();
17208
- this._requestResolvers = /* @__PURE__ */ new Map();
17209
16913
  this.setNotificationHandler(CancelledNotificationSchema, (notification) => {
17210
- this._oncancel(notification);
16914
+ const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
16915
+ controller === null || controller === void 0 ? void 0 : controller.abort(notification.params.reason);
17211
16916
  });
17212
16917
  this.setNotificationHandler(ProgressNotificationSchema, (notification) => {
17213
16918
  this._onprogress(notification);
@@ -17217,116 +16922,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
17217
16922
  // Automatic pong by default.
17218
16923
  (_request) => ({})
17219
16924
  );
17220
- this._taskStore = _options === null || _options === void 0 ? void 0 : _options.taskStore;
17221
- this._taskMessageQueue = _options === null || _options === void 0 ? void 0 : _options.taskMessageQueue;
17222
- if (this._taskStore) {
17223
- this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {
17224
- const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
17225
- if (!task) {
17226
- throw new McpError(exports2.ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
17227
- }
17228
- return {
17229
- ...task
17230
- };
17231
- });
17232
- this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
17233
- const handleTaskResult = async () => {
17234
- var _a;
17235
- const taskId = request.params.taskId;
17236
- if (this._taskMessageQueue) {
17237
- let queuedMessage;
17238
- while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
17239
- if (queuedMessage.type === "response" || queuedMessage.type === "error") {
17240
- const message = queuedMessage.message;
17241
- const requestId = message.id;
17242
- const resolver = this._requestResolvers.get(requestId);
17243
- if (resolver) {
17244
- this._requestResolvers.delete(requestId);
17245
- if (queuedMessage.type === "response") {
17246
- resolver(message);
17247
- } else {
17248
- const errorMessage = message;
17249
- const error = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
17250
- resolver(error);
17251
- }
17252
- } else {
17253
- const messageType = queuedMessage.type === "response" ? "Response" : "Error";
17254
- this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));
17255
- }
17256
- continue;
17257
- }
17258
- await ((_a = this._transport) === null || _a === void 0 ? void 0 : _a.send(queuedMessage.message, { relatedRequestId: extra.requestId }));
17259
- }
17260
- }
17261
- const task = await this._taskStore.getTask(taskId, extra.sessionId);
17262
- if (!task) {
17263
- throw new McpError(exports2.ErrorCode.InvalidParams, `Task not found: ${taskId}`);
17264
- }
17265
- if (!isTerminal(task.status)) {
17266
- await this._waitForTaskUpdate(taskId, extra.signal);
17267
- return await handleTaskResult();
17268
- }
17269
- if (isTerminal(task.status)) {
17270
- const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
17271
- this._clearTaskQueue(taskId);
17272
- return {
17273
- ...result,
17274
- _meta: {
17275
- ...result._meta,
17276
- [RELATED_TASK_META_KEY]: {
17277
- taskId
17278
- }
17279
- }
17280
- };
17281
- }
17282
- return await handleTaskResult();
17283
- };
17284
- return await handleTaskResult();
17285
- });
17286
- this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {
17287
- var _a;
17288
- try {
17289
- const { tasks, nextCursor } = await this._taskStore.listTasks((_a = request.params) === null || _a === void 0 ? void 0 : _a.cursor, extra.sessionId);
17290
- return {
17291
- tasks,
17292
- nextCursor,
17293
- _meta: {}
17294
- };
17295
- } catch (error) {
17296
- throw new McpError(exports2.ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`);
17297
- }
17298
- });
17299
- this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {
17300
- try {
17301
- const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
17302
- if (!task) {
17303
- throw new McpError(exports2.ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);
17304
- }
17305
- if (isTerminal(task.status)) {
17306
- throw new McpError(exports2.ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
17307
- }
17308
- await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
17309
- this._clearTaskQueue(request.params.taskId);
17310
- const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
17311
- if (!cancelledTask) {
17312
- throw new McpError(exports2.ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
17313
- }
17314
- return {
17315
- _meta: {},
17316
- ...cancelledTask
17317
- };
17318
- } catch (error) {
17319
- if (error instanceof McpError) {
17320
- throw error;
17321
- }
17322
- throw new McpError(exports2.ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`);
17323
- }
17324
- });
17325
- }
17326
- }
17327
- async _oncancel(notification) {
17328
- const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
17329
- controller === null || controller === void 0 ? void 0 : controller.abort(notification.params.reason);
17330
16925
  }
17331
16926
  _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
17332
16927
  this._timeoutInfo.set(messageId, {
@@ -17399,11 +16994,10 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
17399
16994
  const responseHandlers = this._responseHandlers;
17400
16995
  this._responseHandlers = /* @__PURE__ */ new Map();
17401
16996
  this._progressHandlers.clear();
17402
- this._taskProgressTokens.clear();
17403
16997
  this._pendingDebouncedNotifications.clear();
17404
- const error = McpError.fromError(exports2.ErrorCode.ConnectionClosed, "Connection closed");
17405
16998
  this._transport = void 0;
17406
16999
  (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this);
17000
+ const error = McpError.fromError(exports2.ErrorCode.ConnectionClosed, "Connection closed");
17407
17001
  for (const handler of responseHandlers.values()) {
17408
17002
  handler(error);
17409
17003
  }
@@ -17421,94 +17015,47 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
17421
17015
  Promise.resolve().then(() => handler(notification)).catch((error) => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));
17422
17016
  }
17423
17017
  _onrequest(request, extra) {
17424
- var _a, _b, _c, _d, _e, _f;
17018
+ var _a, _b;
17425
17019
  const handler = (_a = this._requestHandlers.get(request.method)) !== null && _a !== void 0 ? _a : this.fallbackRequestHandler;
17426
17020
  const capturedTransport = this._transport;
17427
- const relatedTaskId = (_d = (_c = (_b = request.params) === null || _b === void 0 ? void 0 : _b._meta) === null || _c === void 0 ? void 0 : _c[RELATED_TASK_META_KEY]) === null || _d === void 0 ? void 0 : _d.taskId;
17428
17021
  if (handler === void 0) {
17429
- const errorResponse = {
17022
+ capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({
17430
17023
  jsonrpc: "2.0",
17431
17024
  id: request.id,
17432
17025
  error: {
17433
17026
  code: exports2.ErrorCode.MethodNotFound,
17434
17027
  message: "Method not found"
17435
17028
  }
17436
- };
17437
- if (relatedTaskId && this._taskMessageQueue) {
17438
- this._enqueueTaskMessage(relatedTaskId, {
17439
- type: "error",
17440
- message: errorResponse,
17441
- timestamp: Date.now()
17442
- }, capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.sessionId).catch((error) => this._onerror(new Error(`Failed to enqueue error response: ${error}`)));
17443
- } else {
17444
- capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send(errorResponse).catch((error) => this._onerror(new Error(`Failed to send an error response: ${error}`)));
17445
- }
17029
+ }).catch((error) => this._onerror(new Error(`Failed to send an error response: ${error}`)));
17446
17030
  return;
17447
17031
  }
17448
17032
  const abortController = new AbortController();
17449
17033
  this._requestHandlerAbortControllers.set(request.id, abortController);
17450
- const taskCreationParams = (_e = request.params) === null || _e === void 0 ? void 0 : _e.task;
17451
- const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.sessionId) : void 0;
17452
17034
  const fullExtra = {
17453
17035
  signal: abortController.signal,
17454
17036
  sessionId: capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.sessionId,
17455
- _meta: (_f = request.params) === null || _f === void 0 ? void 0 : _f._meta,
17456
- sendNotification: async (notification) => {
17457
- const notificationOptions = { relatedRequestId: request.id };
17458
- if (relatedTaskId) {
17459
- notificationOptions.relatedTask = { taskId: relatedTaskId };
17460
- }
17461
- await this.notification(notification, notificationOptions);
17462
- },
17463
- sendRequest: async (r, resultSchema, options) => {
17464
- var _a2, _b2;
17465
- const requestOptions = { ...options, relatedRequestId: request.id };
17466
- if (relatedTaskId && !requestOptions.relatedTask) {
17467
- requestOptions.relatedTask = { taskId: relatedTaskId };
17468
- }
17469
- const effectiveTaskId = (_b2 = (_a2 = requestOptions.relatedTask) === null || _a2 === void 0 ? void 0 : _a2.taskId) !== null && _b2 !== void 0 ? _b2 : relatedTaskId;
17470
- if (effectiveTaskId && taskStore) {
17471
- await taskStore.updateTaskStatus(effectiveTaskId, "input_required");
17472
- }
17473
- return await this.request(r, resultSchema, requestOptions);
17474
- },
17037
+ _meta: (_b = request.params) === null || _b === void 0 ? void 0 : _b._meta,
17038
+ sendNotification: (notification) => this.notification(notification, { relatedRequestId: request.id }),
17039
+ sendRequest: (r, resultSchema, options) => this.request(r, resultSchema, { ...options, relatedRequestId: request.id }),
17475
17040
  authInfo: extra === null || extra === void 0 ? void 0 : extra.authInfo,
17476
17041
  requestId: request.id,
17477
- requestInfo: extra === null || extra === void 0 ? void 0 : extra.requestInfo,
17478
- taskId: relatedTaskId,
17479
- taskStore,
17480
- taskRequestedTtl: taskCreationParams === null || taskCreationParams === void 0 ? void 0 : taskCreationParams.ttl,
17481
- closeSSEStream: extra === null || extra === void 0 ? void 0 : extra.closeSSEStream,
17482
- closeStandaloneSSEStream: extra === null || extra === void 0 ? void 0 : extra.closeStandaloneSSEStream
17042
+ requestInfo: extra === null || extra === void 0 ? void 0 : extra.requestInfo
17483
17043
  };
17484
- Promise.resolve().then(() => {
17485
- if (taskCreationParams) {
17486
- this.assertTaskHandlerCapability(request.method);
17487
- }
17488
- }).then(() => handler(request, fullExtra)).then(async (result) => {
17044
+ Promise.resolve().then(() => handler(request, fullExtra)).then((result) => {
17489
17045
  if (abortController.signal.aborted) {
17490
17046
  return;
17491
17047
  }
17492
- const response = {
17048
+ return capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({
17493
17049
  result,
17494
17050
  jsonrpc: "2.0",
17495
17051
  id: request.id
17496
- };
17497
- if (relatedTaskId && this._taskMessageQueue) {
17498
- await this._enqueueTaskMessage(relatedTaskId, {
17499
- type: "response",
17500
- message: response,
17501
- timestamp: Date.now()
17502
- }, capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.sessionId);
17503
- } else {
17504
- await (capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send(response));
17505
- }
17506
- }, async (error) => {
17052
+ });
17053
+ }, (error) => {
17507
17054
  var _a2;
17508
17055
  if (abortController.signal.aborted) {
17509
17056
  return;
17510
17057
  }
17511
- const errorResponse = {
17058
+ return capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({
17512
17059
  jsonrpc: "2.0",
17513
17060
  id: request.id,
17514
17061
  error: {
@@ -17516,16 +17063,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
17516
17063
  message: (_a2 = error.message) !== null && _a2 !== void 0 ? _a2 : "Internal error",
17517
17064
  ...error["data"] !== void 0 && { data: error["data"] }
17518
17065
  }
17519
- };
17520
- if (relatedTaskId && this._taskMessageQueue) {
17521
- await this._enqueueTaskMessage(relatedTaskId, {
17522
- type: "error",
17523
- message: errorResponse,
17524
- timestamp: Date.now()
17525
- }, capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.sessionId);
17526
- } else {
17527
- await (capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send(errorResponse));
17528
- }
17066
+ });
17529
17067
  }).catch((error) => this._onerror(new Error(`Failed to send response: ${error}`))).finally(() => {
17530
17068
  this._requestHandlerAbortControllers.delete(request.id);
17531
17069
  });
@@ -17544,9 +17082,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
17544
17082
  try {
17545
17083
  this._resetTimeout(messageId);
17546
17084
  } catch (error) {
17547
- this._responseHandlers.delete(messageId);
17548
- this._progressHandlers.delete(messageId);
17549
- this._cleanupTimeout(messageId);
17550
17085
  responseHandler(error);
17551
17086
  return;
17552
17087
  }
@@ -17555,38 +17090,14 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
17555
17090
  }
17556
17091
  _onresponse(response) {
17557
17092
  const messageId = Number(response.id);
17558
- const resolver = this._requestResolvers.get(messageId);
17559
- if (resolver) {
17560
- this._requestResolvers.delete(messageId);
17561
- if (isJSONRPCResponse(response)) {
17562
- resolver(response);
17563
- } else {
17564
- const error = new McpError(response.error.code, response.error.message, response.error.data);
17565
- resolver(error);
17566
- }
17567
- return;
17568
- }
17569
17093
  const handler = this._responseHandlers.get(messageId);
17570
17094
  if (handler === void 0) {
17571
17095
  this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
17572
17096
  return;
17573
17097
  }
17574
17098
  this._responseHandlers.delete(messageId);
17099
+ this._progressHandlers.delete(messageId);
17575
17100
  this._cleanupTimeout(messageId);
17576
- let isTaskResponse = false;
17577
- if (isJSONRPCResponse(response) && response.result && typeof response.result === "object") {
17578
- const result = response.result;
17579
- if (result.task && typeof result.task === "object") {
17580
- const task = result.task;
17581
- if (typeof task.taskId === "string") {
17582
- isTaskResponse = true;
17583
- this._taskProgressTokens.set(task.taskId, messageId);
17584
- }
17585
- }
17586
- }
17587
- if (!isTaskResponse) {
17588
- this._progressHandlers.delete(messageId);
17589
- }
17590
17101
  if (isJSONRPCResponse(response)) {
17591
17102
  handler(response);
17592
17103
  } else {
@@ -17605,118 +17116,20 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
17605
17116
  await ((_a = this._transport) === null || _a === void 0 ? void 0 : _a.close());
17606
17117
  }
17607
17118
  /**
17608
- * Sends a request and returns an AsyncGenerator that yields response messages.
17609
- * The generator is guaranteed to end with either a 'result' or 'error' message.
17610
- *
17611
- * @example
17612
- * ```typescript
17613
- * const stream = protocol.requestStream(request, resultSchema, options);
17614
- * for await (const message of stream) {
17615
- * switch (message.type) {
17616
- * case 'taskCreated':
17617
- * console.log('Task created:', message.task.taskId);
17618
- * break;
17619
- * case 'taskStatus':
17620
- * console.log('Task status:', message.task.status);
17621
- * break;
17622
- * case 'result':
17623
- * console.log('Final result:', message.result);
17624
- * break;
17625
- * case 'error':
17626
- * console.error('Error:', message.error);
17627
- * break;
17628
- * }
17629
- * }
17630
- * ```
17631
- *
17632
- * @experimental Use `client.experimental.tasks.requestStream()` to access this method.
17633
- */
17634
- async *requestStream(request, resultSchema, options) {
17635
- var _a, _b, _c, _d;
17636
- const { task } = options !== null && options !== void 0 ? options : {};
17637
- if (!task) {
17638
- try {
17639
- const result = await this.request(request, resultSchema, options);
17640
- yield { type: "result", result };
17641
- } catch (error) {
17642
- yield {
17643
- type: "error",
17644
- error: error instanceof McpError ? error : new McpError(exports2.ErrorCode.InternalError, String(error))
17645
- };
17646
- }
17647
- return;
17648
- }
17649
- let taskId;
17650
- try {
17651
- const createResult = await this.request(request, CreateTaskResultSchema, options);
17652
- if (createResult.task) {
17653
- taskId = createResult.task.taskId;
17654
- yield { type: "taskCreated", task: createResult.task };
17655
- } else {
17656
- throw new McpError(exports2.ErrorCode.InternalError, "Task creation did not return a task");
17657
- }
17658
- while (true) {
17659
- const task2 = await this.getTask({ taskId }, options);
17660
- yield { type: "taskStatus", task: task2 };
17661
- if (isTerminal(task2.status)) {
17662
- if (task2.status === "completed") {
17663
- const result = await this.getTaskResult({ taskId }, resultSchema, options);
17664
- yield { type: "result", result };
17665
- } else if (task2.status === "failed") {
17666
- yield {
17667
- type: "error",
17668
- error: new McpError(exports2.ErrorCode.InternalError, `Task ${taskId} failed`)
17669
- };
17670
- } else if (task2.status === "cancelled") {
17671
- yield {
17672
- type: "error",
17673
- error: new McpError(exports2.ErrorCode.InternalError, `Task ${taskId} was cancelled`)
17674
- };
17675
- }
17676
- return;
17677
- }
17678
- if (task2.status === "input_required") {
17679
- const result = await this.getTaskResult({ taskId }, resultSchema, options);
17680
- yield { type: "result", result };
17681
- return;
17682
- }
17683
- const pollInterval = (_c = (_a = task2.pollInterval) !== null && _a !== void 0 ? _a : (_b = this._options) === null || _b === void 0 ? void 0 : _b.defaultTaskPollInterval) !== null && _c !== void 0 ? _c : 1e3;
17684
- await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
17685
- (_d = options === null || options === void 0 ? void 0 : options.signal) === null || _d === void 0 ? void 0 : _d.throwIfAborted();
17686
- }
17687
- } catch (error) {
17688
- yield {
17689
- type: "error",
17690
- error: error instanceof McpError ? error : new McpError(exports2.ErrorCode.InternalError, String(error))
17691
- };
17692
- }
17693
- }
17694
- /**
17695
- * Sends a request and waits for a response.
17119
+ * Sends a request and wait for a response.
17696
17120
  *
17697
17121
  * Do not use this method to emit notifications! Use notification() instead.
17698
17122
  */
17699
17123
  request(request, resultSchema, options) {
17700
- const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options !== null && options !== void 0 ? options : {};
17124
+ const { relatedRequestId, resumptionToken, onresumptiontoken } = options !== null && options !== void 0 ? options : {};
17701
17125
  return new Promise((resolve2, reject) => {
17702
- var _a, _b, _c, _d, _e, _f, _g;
17703
- const earlyReject = (error) => {
17704
- reject(error);
17705
- };
17126
+ var _a, _b, _c, _d, _e, _f;
17706
17127
  if (!this._transport) {
17707
- earlyReject(new Error("Not connected"));
17128
+ reject(new Error("Not connected"));
17708
17129
  return;
17709
17130
  }
17710
17131
  if (((_a = this._options) === null || _a === void 0 ? void 0 : _a.enforceStrictCapabilities) === true) {
17711
- try {
17712
- this.assertCapabilityForMethod(request.method);
17713
- if (task) {
17714
- this.assertTaskCapability(request.method);
17715
- }
17716
- } catch (e) {
17717
- earlyReject(e);
17718
- return;
17719
- }
17132
+ this.assertCapabilityForMethod(request.method);
17720
17133
  }
17721
17134
  (_b = options === null || options === void 0 ? void 0 : options.signal) === null || _b === void 0 ? void 0 : _b.throwIfAborted();
17722
17135
  const messageId = this._requestMessageId++;
@@ -17735,21 +17148,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
17735
17148
  }
17736
17149
  };
17737
17150
  }
17738
- if (task) {
17739
- jsonrpcRequest.params = {
17740
- ...jsonrpcRequest.params,
17741
- task
17742
- };
17743
- }
17744
- if (relatedTask) {
17745
- jsonrpcRequest.params = {
17746
- ...jsonrpcRequest.params,
17747
- _meta: {
17748
- ...((_d = jsonrpcRequest.params) === null || _d === void 0 ? void 0 : _d._meta) || {},
17749
- [RELATED_TASK_META_KEY]: relatedTask
17750
- }
17751
- };
17752
- }
17753
17151
  const cancel = (reason) => {
17754
17152
  var _a2;
17755
17153
  this._responseHandlers.delete(messageId);
@@ -17762,9 +17160,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
17762
17160
  requestId: messageId,
17763
17161
  reason: String(reason)
17764
17162
  }
17765
- }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => this._onerror(new Error(`Failed to send cancellation: ${error2}`)));
17766
- const error = reason instanceof McpError ? reason : new McpError(exports2.ErrorCode.RequestTimeout, String(reason));
17767
- reject(error);
17163
+ }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => this._onerror(new Error(`Failed to send cancellation: ${error}`)));
17164
+ reject(reason);
17768
17165
  };
17769
17166
  this._responseHandlers.set(messageId, (response) => {
17770
17167
  var _a2;
@@ -17785,150 +17182,53 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
17785
17182
  reject(error);
17786
17183
  }
17787
17184
  });
17788
- (_e = options === null || options === void 0 ? void 0 : options.signal) === null || _e === void 0 ? void 0 : _e.addEventListener("abort", () => {
17185
+ (_d = options === null || options === void 0 ? void 0 : options.signal) === null || _d === void 0 ? void 0 : _d.addEventListener("abort", () => {
17789
17186
  var _a2;
17790
17187
  cancel((_a2 = options === null || options === void 0 ? void 0 : options.signal) === null || _a2 === void 0 ? void 0 : _a2.reason);
17791
17188
  });
17792
- const timeout = (_f = options === null || options === void 0 ? void 0 : options.timeout) !== null && _f !== void 0 ? _f : DEFAULT_REQUEST_TIMEOUT_MSEC;
17189
+ const timeout = (_e = options === null || options === void 0 ? void 0 : options.timeout) !== null && _e !== void 0 ? _e : DEFAULT_REQUEST_TIMEOUT_MSEC;
17793
17190
  const timeoutHandler = () => cancel(McpError.fromError(exports2.ErrorCode.RequestTimeout, "Request timed out", { timeout }));
17794
- this._setupTimeout(messageId, timeout, options === null || options === void 0 ? void 0 : options.maxTotalTimeout, timeoutHandler, (_g = options === null || options === void 0 ? void 0 : options.resetTimeoutOnProgress) !== null && _g !== void 0 ? _g : false);
17795
- const relatedTaskId = relatedTask === null || relatedTask === void 0 ? void 0 : relatedTask.taskId;
17796
- if (relatedTaskId) {
17797
- const responseResolver = (response) => {
17798
- const handler = this._responseHandlers.get(messageId);
17799
- if (handler) {
17800
- handler(response);
17801
- } else {
17802
- this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));
17803
- }
17804
- };
17805
- this._requestResolvers.set(messageId, responseResolver);
17806
- this._enqueueTaskMessage(relatedTaskId, {
17807
- type: "request",
17808
- message: jsonrpcRequest,
17809
- timestamp: Date.now()
17810
- }).catch((error) => {
17811
- this._cleanupTimeout(messageId);
17812
- reject(error);
17813
- });
17814
- } else {
17815
- this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => {
17816
- this._cleanupTimeout(messageId);
17817
- reject(error);
17818
- });
17819
- }
17191
+ 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);
17192
+ this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => {
17193
+ this._cleanupTimeout(messageId);
17194
+ reject(error);
17195
+ });
17820
17196
  });
17821
17197
  }
17822
- /**
17823
- * Gets the current status of a task.
17824
- *
17825
- * @experimental Use `client.experimental.tasks.getTask()` to access this method.
17826
- */
17827
- async getTask(params, options) {
17828
- return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options);
17829
- }
17830
- /**
17831
- * Retrieves the result of a completed task.
17832
- *
17833
- * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.
17834
- */
17835
- async getTaskResult(params, resultSchema, options) {
17836
- return this.request({ method: "tasks/result", params }, resultSchema, options);
17837
- }
17838
- /**
17839
- * Lists tasks, optionally starting from a pagination cursor.
17840
- *
17841
- * @experimental Use `client.experimental.tasks.listTasks()` to access this method.
17842
- */
17843
- async listTasks(params, options) {
17844
- return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options);
17845
- }
17846
- /**
17847
- * Cancels a specific task.
17848
- *
17849
- * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.
17850
- */
17851
- async cancelTask(params, options) {
17852
- return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options);
17853
- }
17854
17198
  /**
17855
17199
  * Emits a notification, which is a one-way message that does not expect a response.
17856
17200
  */
17857
17201
  async notification(notification, options) {
17858
- var _a, _b, _c, _d, _e;
17202
+ var _a, _b;
17859
17203
  if (!this._transport) {
17860
17204
  throw new Error("Not connected");
17861
17205
  }
17862
17206
  this.assertNotificationCapability(notification.method);
17863
- const relatedTaskId = (_a = options === null || options === void 0 ? void 0 : options.relatedTask) === null || _a === void 0 ? void 0 : _a.taskId;
17864
- if (relatedTaskId) {
17865
- const jsonrpcNotification2 = {
17866
- ...notification,
17867
- jsonrpc: "2.0",
17868
- params: {
17869
- ...notification.params,
17870
- _meta: {
17871
- ...((_b = notification.params) === null || _b === void 0 ? void 0 : _b._meta) || {},
17872
- [RELATED_TASK_META_KEY]: options.relatedTask
17873
- }
17874
- }
17875
- };
17876
- await this._enqueueTaskMessage(relatedTaskId, {
17877
- type: "notification",
17878
- message: jsonrpcNotification2,
17879
- timestamp: Date.now()
17880
- });
17881
- return;
17882
- }
17883
- const debouncedMethods = (_d = (_c = this._options) === null || _c === void 0 ? void 0 : _c.debouncedNotificationMethods) !== null && _d !== void 0 ? _d : [];
17884
- const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !(options === null || options === void 0 ? void 0 : options.relatedRequestId) && !(options === null || options === void 0 ? void 0 : options.relatedTask);
17207
+ const debouncedMethods = (_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.debouncedNotificationMethods) !== null && _b !== void 0 ? _b : [];
17208
+ const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !(options === null || options === void 0 ? void 0 : options.relatedRequestId);
17885
17209
  if (canDebounce) {
17886
17210
  if (this._pendingDebouncedNotifications.has(notification.method)) {
17887
17211
  return;
17888
17212
  }
17889
17213
  this._pendingDebouncedNotifications.add(notification.method);
17890
17214
  Promise.resolve().then(() => {
17891
- var _a2, _b2;
17215
+ var _a2;
17892
17216
  this._pendingDebouncedNotifications.delete(notification.method);
17893
17217
  if (!this._transport) {
17894
17218
  return;
17895
17219
  }
17896
- let jsonrpcNotification2 = {
17220
+ const jsonrpcNotification2 = {
17897
17221
  ...notification,
17898
17222
  jsonrpc: "2.0"
17899
17223
  };
17900
- if (options === null || options === void 0 ? void 0 : options.relatedTask) {
17901
- jsonrpcNotification2 = {
17902
- ...jsonrpcNotification2,
17903
- params: {
17904
- ...jsonrpcNotification2.params,
17905
- _meta: {
17906
- ...((_a2 = jsonrpcNotification2.params) === null || _a2 === void 0 ? void 0 : _a2._meta) || {},
17907
- [RELATED_TASK_META_KEY]: options.relatedTask
17908
- }
17909
- }
17910
- };
17911
- }
17912
- (_b2 = this._transport) === null || _b2 === void 0 ? void 0 : _b2.send(jsonrpcNotification2, options).catch((error) => this._onerror(error));
17224
+ (_a2 = this._transport) === null || _a2 === void 0 ? void 0 : _a2.send(jsonrpcNotification2, options).catch((error) => this._onerror(error));
17913
17225
  });
17914
17226
  return;
17915
17227
  }
17916
- let jsonrpcNotification = {
17228
+ const jsonrpcNotification = {
17917
17229
  ...notification,
17918
17230
  jsonrpc: "2.0"
17919
17231
  };
17920
- if (options === null || options === void 0 ? void 0 : options.relatedTask) {
17921
- jsonrpcNotification = {
17922
- ...jsonrpcNotification,
17923
- params: {
17924
- ...jsonrpcNotification.params,
17925
- _meta: {
17926
- ...((_e = jsonrpcNotification.params) === null || _e === void 0 ? void 0 : _e._meta) || {},
17927
- [RELATED_TASK_META_KEY]: options.relatedTask
17928
- }
17929
- }
17930
- };
17931
- }
17932
17232
  await this._transport.send(jsonrpcNotification, options);
17933
17233
  }
17934
17234
  /**
@@ -17976,152 +17276,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
17976
17276
  removeNotificationHandler(method) {
17977
17277
  this._notificationHandlers.delete(method);
17978
17278
  }
17979
- /**
17980
- * Cleans up the progress handler associated with a task.
17981
- * This should be called when a task reaches a terminal status.
17982
- */
17983
- _cleanupTaskProgressHandler(taskId) {
17984
- const progressToken = this._taskProgressTokens.get(taskId);
17985
- if (progressToken !== void 0) {
17986
- this._progressHandlers.delete(progressToken);
17987
- this._taskProgressTokens.delete(taskId);
17988
- }
17989
- }
17990
- /**
17991
- * Enqueues a task-related message for side-channel delivery via tasks/result.
17992
- * @param taskId The task ID to associate the message with
17993
- * @param message The message to enqueue
17994
- * @param sessionId Optional session ID for binding the operation to a specific session
17995
- * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)
17996
- *
17997
- * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle
17998
- * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer
17999
- * simply propagates the error.
18000
- */
18001
- async _enqueueTaskMessage(taskId, message, sessionId) {
18002
- var _a;
18003
- if (!this._taskStore || !this._taskMessageQueue) {
18004
- throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
18005
- }
18006
- const maxQueueSize = (_a = this._options) === null || _a === void 0 ? void 0 : _a.maxTaskQueueSize;
18007
- await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
18008
- }
18009
- /**
18010
- * Clears the message queue for a task and rejects any pending request resolvers.
18011
- * @param taskId The task ID whose queue should be cleared
18012
- * @param sessionId Optional session ID for binding the operation to a specific session
18013
- */
18014
- async _clearTaskQueue(taskId, sessionId) {
18015
- if (this._taskMessageQueue) {
18016
- const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);
18017
- for (const message of messages) {
18018
- if (message.type === "request" && isJSONRPCRequest(message.message)) {
18019
- const requestId = message.message.id;
18020
- const resolver = this._requestResolvers.get(requestId);
18021
- if (resolver) {
18022
- resolver(new McpError(exports2.ErrorCode.InternalError, "Task cancelled or completed"));
18023
- this._requestResolvers.delete(requestId);
18024
- } else {
18025
- this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));
18026
- }
18027
- }
18028
- }
18029
- }
18030
- }
18031
- /**
18032
- * Waits for a task update (new messages or status change) with abort signal support.
18033
- * Uses polling to check for updates at the task's configured poll interval.
18034
- * @param taskId The task ID to wait for
18035
- * @param signal Abort signal to cancel the wait
18036
- * @returns Promise that resolves when an update occurs or rejects if aborted
18037
- */
18038
- async _waitForTaskUpdate(taskId, signal) {
18039
- var _a, _b, _c;
18040
- let interval = (_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.defaultTaskPollInterval) !== null && _b !== void 0 ? _b : 1e3;
18041
- try {
18042
- const task = await ((_c = this._taskStore) === null || _c === void 0 ? void 0 : _c.getTask(taskId));
18043
- if (task === null || task === void 0 ? void 0 : task.pollInterval) {
18044
- interval = task.pollInterval;
18045
- }
18046
- } catch (_d) {
18047
- }
18048
- return new Promise((resolve2, reject) => {
18049
- if (signal.aborted) {
18050
- reject(new McpError(exports2.ErrorCode.InvalidRequest, "Request cancelled"));
18051
- return;
18052
- }
18053
- const timeoutId = setTimeout(resolve2, interval);
18054
- signal.addEventListener("abort", () => {
18055
- clearTimeout(timeoutId);
18056
- reject(new McpError(exports2.ErrorCode.InvalidRequest, "Request cancelled"));
18057
- }, { once: true });
18058
- });
18059
- }
18060
- requestTaskStore(request, sessionId) {
18061
- const taskStore = this._taskStore;
18062
- if (!taskStore) {
18063
- throw new Error("No task store configured");
18064
- }
18065
- return {
18066
- createTask: async (taskParams) => {
18067
- if (!request) {
18068
- throw new Error("No request provided");
18069
- }
18070
- return await taskStore.createTask(taskParams, request.id, {
18071
- method: request.method,
18072
- params: request.params
18073
- }, sessionId);
18074
- },
18075
- getTask: async (taskId) => {
18076
- const task = await taskStore.getTask(taskId, sessionId);
18077
- if (!task) {
18078
- throw new McpError(exports2.ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
18079
- }
18080
- return task;
18081
- },
18082
- storeTaskResult: async (taskId, status, result) => {
18083
- await taskStore.storeTaskResult(taskId, status, result, sessionId);
18084
- const task = await taskStore.getTask(taskId, sessionId);
18085
- if (task) {
18086
- const notification = TaskStatusNotificationSchema.parse({
18087
- method: "notifications/tasks/status",
18088
- params: task
18089
- });
18090
- await this.notification(notification);
18091
- if (isTerminal(task.status)) {
18092
- this._cleanupTaskProgressHandler(taskId);
18093
- }
18094
- }
18095
- },
18096
- getTaskResult: (taskId) => {
18097
- return taskStore.getTaskResult(taskId, sessionId);
18098
- },
18099
- updateTaskStatus: async (taskId, status, statusMessage) => {
18100
- const task = await taskStore.getTask(taskId, sessionId);
18101
- if (!task) {
18102
- throw new McpError(exports2.ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`);
18103
- }
18104
- if (isTerminal(task.status)) {
18105
- throw new McpError(exports2.ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);
18106
- }
18107
- await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);
18108
- const updatedTask = await taskStore.getTask(taskId, sessionId);
18109
- if (updatedTask) {
18110
- const notification = TaskStatusNotificationSchema.parse({
18111
- method: "notifications/tasks/status",
18112
- params: updatedTask
18113
- });
18114
- await this.notification(notification);
18115
- if (isTerminal(updatedTask.status)) {
18116
- this._cleanupTaskProgressHandler(taskId);
18117
- }
18118
- }
18119
- },
18120
- listTasks: (cursor) => {
18121
- return taskStore.listTasks(cursor, sessionId);
18122
- }
18123
- };
18124
- }
18125
17279
  }
18126
17280
  function isPlainObject(value) {
18127
17281
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -18532,190 +17686,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
18532
17686
  };
18533
17687
  }
18534
17688
  }
18535
- class ExperimentalClientTasks {
18536
- constructor(_client) {
18537
- this._client = _client;
18538
- }
18539
- /**
18540
- * Calls a tool and returns an AsyncGenerator that yields response messages.
18541
- * The generator is guaranteed to end with either a 'result' or 'error' message.
18542
- *
18543
- * This method provides streaming access to tool execution, allowing you to
18544
- * observe intermediate task status updates for long-running tool calls.
18545
- * Automatically validates structured output if the tool has an outputSchema.
18546
- *
18547
- * @example
18548
- * ```typescript
18549
- * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });
18550
- * for await (const message of stream) {
18551
- * switch (message.type) {
18552
- * case 'taskCreated':
18553
- * console.log('Tool execution started:', message.task.taskId);
18554
- * break;
18555
- * case 'taskStatus':
18556
- * console.log('Tool status:', message.task.status);
18557
- * break;
18558
- * case 'result':
18559
- * console.log('Tool result:', message.result);
18560
- * break;
18561
- * case 'error':
18562
- * console.error('Tool error:', message.error);
18563
- * break;
18564
- * }
18565
- * }
18566
- * ```
18567
- *
18568
- * @param params - Tool call parameters (name and arguments)
18569
- * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)
18570
- * @param options - Optional request options (timeout, signal, task creation params, etc.)
18571
- * @returns AsyncGenerator that yields ResponseMessage objects
18572
- *
18573
- * @experimental
18574
- */
18575
- async *callToolStream(params, resultSchema = CallToolResultSchema, options) {
18576
- var _a;
18577
- const clientInternal = this._client;
18578
- const optionsWithTask = {
18579
- ...options,
18580
- // We check if the tool is known to be a task during auto-configuration, but assume
18581
- // the caller knows what they're doing if they pass this explicitly
18582
- task: (_a = options === null || options === void 0 ? void 0 : options.task) !== null && _a !== void 0 ? _a : clientInternal.isToolTask(params.name) ? {} : void 0
18583
- };
18584
- const stream = clientInternal.requestStream({ method: "tools/call", params }, resultSchema, optionsWithTask);
18585
- const validator = clientInternal.getToolOutputValidator(params.name);
18586
- for await (const message of stream) {
18587
- if (message.type === "result" && validator) {
18588
- const result = message.result;
18589
- if (!result.structuredContent && !result.isError) {
18590
- yield {
18591
- type: "error",
18592
- error: new McpError(exports2.ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)
18593
- };
18594
- return;
18595
- }
18596
- if (result.structuredContent) {
18597
- try {
18598
- const validationResult = validator(result.structuredContent);
18599
- if (!validationResult.valid) {
18600
- yield {
18601
- type: "error",
18602
- error: new McpError(exports2.ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)
18603
- };
18604
- return;
18605
- }
18606
- } catch (error) {
18607
- if (error instanceof McpError) {
18608
- yield { type: "error", error };
18609
- return;
18610
- }
18611
- yield {
18612
- type: "error",
18613
- error: new McpError(exports2.ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`)
18614
- };
18615
- return;
18616
- }
18617
- }
18618
- }
18619
- yield message;
18620
- }
18621
- }
18622
- /**
18623
- * Gets the current status of a task.
18624
- *
18625
- * @param taskId - The task identifier
18626
- * @param options - Optional request options
18627
- * @returns The task status
18628
- *
18629
- * @experimental
18630
- */
18631
- async getTask(taskId, options) {
18632
- return this._client.getTask({ taskId }, options);
18633
- }
18634
- /**
18635
- * Retrieves the result of a completed task.
18636
- *
18637
- * @param taskId - The task identifier
18638
- * @param resultSchema - Zod schema for validating the result
18639
- * @param options - Optional request options
18640
- * @returns The task result
18641
- *
18642
- * @experimental
18643
- */
18644
- async getTaskResult(taskId, resultSchema, options) {
18645
- return this._client.getTaskResult({ taskId }, resultSchema, options);
18646
- }
18647
- /**
18648
- * Lists tasks with optional pagination.
18649
- *
18650
- * @param cursor - Optional pagination cursor
18651
- * @param options - Optional request options
18652
- * @returns List of tasks with optional next cursor
18653
- *
18654
- * @experimental
18655
- */
18656
- async listTasks(cursor, options) {
18657
- return this._client.listTasks(cursor ? { cursor } : void 0, options);
18658
- }
18659
- /**
18660
- * Cancels a running task.
18661
- *
18662
- * @param taskId - The task identifier
18663
- * @param options - Optional request options
18664
- *
18665
- * @experimental
18666
- */
18667
- async cancelTask(taskId, options) {
18668
- return this._client.cancelTask({ taskId }, options);
18669
- }
18670
- /**
18671
- * Sends a request and returns an AsyncGenerator that yields response messages.
18672
- * The generator is guaranteed to end with either a 'result' or 'error' message.
18673
- *
18674
- * This method provides streaming access to request processing, allowing you to
18675
- * observe intermediate task status updates for task-augmented requests.
18676
- *
18677
- * @param request - The request to send
18678
- * @param resultSchema - Zod schema for validating the result
18679
- * @param options - Optional request options (timeout, signal, task creation params, etc.)
18680
- * @returns AsyncGenerator that yields ResponseMessage objects
18681
- *
18682
- * @experimental
18683
- */
18684
- requestStream(request, resultSchema, options) {
18685
- return this._client.requestStream(request, resultSchema, options);
18686
- }
18687
- }
18688
- function assertToolsCallTaskCapability(requests, method, entityName) {
18689
- var _a;
18690
- if (!requests) {
18691
- throw new Error(`${entityName} does not support task creation (required for ${method})`);
18692
- }
18693
- switch (method) {
18694
- case "tools/call":
18695
- if (!((_a = requests.tools) === null || _a === void 0 ? void 0 : _a.call)) {
18696
- throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);
18697
- }
18698
- break;
18699
- }
18700
- }
18701
- function assertClientRequestTaskCapability(requests, method, entityName) {
18702
- var _a, _b;
18703
- if (!requests) {
18704
- throw new Error(`${entityName} does not support task creation (required for ${method})`);
18705
- }
18706
- switch (method) {
18707
- case "sampling/createMessage":
18708
- if (!((_a = requests.sampling) === null || _a === void 0 ? void 0 : _a.createMessage)) {
18709
- throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);
18710
- }
18711
- break;
18712
- case "elicitation/create":
18713
- if (!((_b = requests.elicitation) === null || _b === void 0 ? void 0 : _b.create)) {
18714
- throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);
18715
- }
18716
- break;
18717
- }
18718
- }
18719
17689
  function applyElicitationDefaults(schema, data) {
18720
17690
  if (!schema || data === null || typeof data !== "object")
18721
17691
  return;
@@ -18762,26 +17732,9 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
18762
17732
  super(options);
18763
17733
  this._clientInfo = _clientInfo;
18764
17734
  this._cachedToolOutputValidators = /* @__PURE__ */ new Map();
18765
- this._cachedKnownTaskTools = /* @__PURE__ */ new Set();
18766
- this._cachedRequiredTaskTools = /* @__PURE__ */ new Set();
18767
17735
  this._capabilities = (_a = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a !== void 0 ? _a : {};
18768
17736
  this._jsonSchemaValidator = (_b = options === null || options === void 0 ? void 0 : options.jsonSchemaValidator) !== null && _b !== void 0 ? _b : new AjvJsonSchemaValidator();
18769
17737
  }
18770
- /**
18771
- * Access experimental features.
18772
- *
18773
- * WARNING: These APIs are experimental and may change without notice.
18774
- *
18775
- * @experimental
18776
- */
18777
- get experimental() {
18778
- if (!this._experimental) {
18779
- this._experimental = {
18780
- tasks: new ExperimentalClientTasks(this)
18781
- };
18782
- }
18783
- return this._experimental;
18784
- }
18785
17738
  /**
18786
17739
  * Registers new capabilities. This can only be called before connecting to a transport.
18787
17740
  *
@@ -18835,14 +17788,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
18835
17788
  throw new McpError(exports2.ErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests");
18836
17789
  }
18837
17790
  const result = await Promise.resolve(handler(request, extra));
18838
- if (params.task) {
18839
- const taskValidationResult = safeParse(CreateTaskResultSchema, result);
18840
- if (!taskValidationResult.success) {
18841
- const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
18842
- throw new McpError(exports2.ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
18843
- }
18844
- return taskValidationResult.data;
18845
- }
18846
17791
  const validationResult = safeParse(ElicitResultSchema, result);
18847
17792
  if (!validationResult.success) {
18848
17793
  const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
@@ -18862,32 +17807,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
18862
17807
  };
18863
17808
  return super.setRequestHandler(requestSchema, wrappedHandler);
18864
17809
  }
18865
- if (method === "sampling/createMessage") {
18866
- const wrappedHandler = async (request, extra) => {
18867
- const validatedRequest = safeParse(CreateMessageRequestSchema, request);
18868
- if (!validatedRequest.success) {
18869
- const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
18870
- throw new McpError(exports2.ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);
18871
- }
18872
- const { params } = validatedRequest.data;
18873
- const result = await Promise.resolve(handler(request, extra));
18874
- if (params.task) {
18875
- const taskValidationResult = safeParse(CreateTaskResultSchema, result);
18876
- if (!taskValidationResult.success) {
18877
- const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
18878
- throw new McpError(exports2.ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
18879
- }
18880
- return taskValidationResult.data;
18881
- }
18882
- const validationResult = safeParse(CreateMessageResultSchema, result);
18883
- if (!validationResult.success) {
18884
- const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
18885
- throw new McpError(exports2.ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);
18886
- }
18887
- return validationResult.data;
18888
- };
18889
- return super.setRequestHandler(requestSchema, wrappedHandler);
18890
- }
18891
17810
  return super.setRequestHandler(requestSchema, handler);
18892
17811
  }
18893
17812
  assertCapability(capability, method) {
@@ -18998,9 +17917,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
18998
17917
  }
18999
17918
  }
19000
17919
  assertRequestHandlerCapability(method) {
19001
- if (!this._capabilities) {
19002
- return;
19003
- }
19004
17920
  switch (method) {
19005
17921
  case "sampling/createMessage":
19006
17922
  if (!this._capabilities.sampling) {
@@ -19017,26 +17933,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
19017
17933
  throw new Error(`Client does not support roots capability (required for ${method})`);
19018
17934
  }
19019
17935
  break;
19020
- case "tasks/get":
19021
- case "tasks/list":
19022
- case "tasks/result":
19023
- case "tasks/cancel":
19024
- if (!this._capabilities.tasks) {
19025
- throw new Error(`Client does not support tasks capability (required for ${method})`);
19026
- }
19027
- break;
19028
- }
19029
- }
19030
- assertTaskCapability(method) {
19031
- var _a, _b;
19032
- assertToolsCallTaskCapability((_b = (_a = this._serverCapabilities) === null || _a === void 0 ? void 0 : _a.tasks) === null || _b === void 0 ? void 0 : _b.requests, method, "Server");
19033
- }
19034
- assertTaskHandlerCapability(method) {
19035
- var _a;
19036
- if (!this._capabilities) {
19037
- return;
19038
17936
  }
19039
- assertClientRequestTaskCapability((_a = this._capabilities.tasks) === null || _a === void 0 ? void 0 : _a.requests, method, "Client");
19040
17937
  }
19041
17938
  async ping(options) {
19042
17939
  return this.request({ method: "ping" }, EmptyResultSchema, options);
@@ -19068,15 +17965,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
19068
17965
  async unsubscribeResource(params, options) {
19069
17966
  return this.request({ method: "resources/unsubscribe", params }, EmptyResultSchema, options);
19070
17967
  }
19071
- /**
19072
- * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.
19073
- *
19074
- * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
19075
- */
19076
17968
  async callTool(params, resultSchema = CallToolResultSchema, options) {
19077
- if (this.isToolTaskRequired(params.name)) {
19078
- throw new McpError(exports2.ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);
19079
- }
19080
17969
  const result = await this.request({ method: "tools/call", params }, resultSchema, options);
19081
17970
  const validator = this.getToolOutputValidator(params.name);
19082
17971
  if (validator) {
@@ -19099,41 +17988,17 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
19099
17988
  }
19100
17989
  return result;
19101
17990
  }
19102
- isToolTask(toolName) {
19103
- var _a, _b, _c, _d;
19104
- if (!((_d = (_c = (_b = (_a = this._serverCapabilities) === null || _a === void 0 ? void 0 : _a.tasks) === null || _b === void 0 ? void 0 : _b.requests) === null || _c === void 0 ? void 0 : _c.tools) === null || _d === void 0 ? void 0 : _d.call)) {
19105
- return false;
19106
- }
19107
- return this._cachedKnownTaskTools.has(toolName);
19108
- }
19109
- /**
19110
- * Check if a tool requires task-based execution.
19111
- * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.
19112
- */
19113
- isToolTaskRequired(toolName) {
19114
- return this._cachedRequiredTaskTools.has(toolName);
19115
- }
19116
17991
  /**
19117
17992
  * Cache validators for tool output schemas.
19118
17993
  * Called after listTools() to pre-compile validators for better performance.
19119
17994
  */
19120
- cacheToolMetadata(tools) {
19121
- var _a;
17995
+ cacheToolOutputSchemas(tools) {
19122
17996
  this._cachedToolOutputValidators.clear();
19123
- this._cachedKnownTaskTools.clear();
19124
- this._cachedRequiredTaskTools.clear();
19125
17997
  for (const tool of tools) {
19126
17998
  if (tool.outputSchema) {
19127
17999
  const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
19128
18000
  this._cachedToolOutputValidators.set(tool.name, toolValidator);
19129
18001
  }
19130
- const taskSupport = (_a = tool.execution) === null || _a === void 0 ? void 0 : _a.taskSupport;
19131
- if (taskSupport === "required" || taskSupport === "optional") {
19132
- this._cachedKnownTaskTools.add(tool.name);
19133
- }
19134
- if (taskSupport === "required") {
19135
- this._cachedRequiredTaskTools.add(tool.name);
19136
- }
19137
18002
  }
19138
18003
  }
19139
18004
  /**
@@ -19144,7 +18009,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
19144
18009
  }
19145
18010
  async listTools(params, options) {
19146
18011
  const result = await this.request({ method: "tools/list", params }, ListToolsResultSchema, options);
19147
- this.cacheToolMetadata(result.tools);
18012
+ this.cacheToolOutputSchemas(result.tools);
19148
18013
  return result;
19149
18014
  }
19150
18015
  async sendRootsListChanged() {
@@ -19320,8 +18185,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
19320
18185
  const OAuthClientInformationSchema = object$1({
19321
18186
  client_id: string(),
19322
18187
  client_secret: string().optional(),
19323
- client_id_issued_at: number$1().optional(),
19324
- client_secret_expires_at: number$1().optional()
18188
+ client_id_issued_at: number().optional(),
18189
+ client_secret_expires_at: number().optional()
19325
18190
  }).strip();
19326
18191
  const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
19327
18192
  object$1({
@@ -19421,9 +18286,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
19421
18286
  class InsufficientScopeError extends OAuthError {
19422
18287
  }
19423
18288
  InsufficientScopeError.errorCode = "insufficient_scope";
19424
- class InvalidTargetError extends OAuthError {
19425
- }
19426
- InvalidTargetError.errorCode = "invalid_target";
19427
18289
  const OAUTH_ERRORS = {
19428
18290
  [InvalidRequestError.errorCode]: InvalidRequestError,
19429
18291
  [InvalidClientError.errorCode]: InvalidClientError,
@@ -19440,8 +18302,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
19440
18302
  [MethodNotAllowedError.errorCode]: MethodNotAllowedError,
19441
18303
  [TooManyRequestsError.errorCode]: TooManyRequestsError,
19442
18304
  [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,
19443
- [InsufficientScopeError.errorCode]: InsufficientScopeError,
19444
- [InvalidTargetError.errorCode]: InvalidTargetError
18305
+ [InsufficientScopeError.errorCode]: InsufficientScopeError
19445
18306
  };
19446
18307
  class UnauthorizedError extends Error {
19447
18308
  constructor(message) {
@@ -19579,12 +18440,16 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
19579
18440
  clientInformation = fullInformation;
19580
18441
  }
19581
18442
  }
19582
- const nonInteractiveFlow = !provider.redirectUrl;
19583
- if (authorizationCode !== void 0 || nonInteractiveFlow) {
19584
- const tokens2 = await fetchToken(provider, authorizationServerUrl, {
18443
+ if (authorizationCode !== void 0) {
18444
+ const codeVerifier2 = await provider.codeVerifier();
18445
+ const tokens2 = await exchangeAuthorization(authorizationServerUrl, {
19585
18446
  metadata: metadata2,
19586
- resource,
18447
+ clientInformation,
19587
18448
  authorizationCode,
18449
+ codeVerifier: codeVerifier2,
18450
+ redirectUri: provider.redirectUrl,
18451
+ resource,
18452
+ addClientAuthentication: provider.addClientAuthentication,
19588
18453
  fetchFn
19589
18454
  });
19590
18455
  await provider.saveTokens(tokens2);
@@ -19704,17 +18569,14 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
19704
18569
  }
19705
18570
  }
19706
18571
  async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
19707
- var _a, _b;
19708
18572
  const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, {
19709
18573
  protocolVersion: opts === null || opts === void 0 ? void 0 : opts.protocolVersion,
19710
18574
  metadataUrl: opts === null || opts === void 0 ? void 0 : opts.resourceMetadataUrl
19711
18575
  });
19712
18576
  if (!response || response.status === 404) {
19713
- await ((_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.cancel());
19714
18577
  throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);
19715
18578
  }
19716
18579
  if (!response.ok) {
19717
- await ((_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel());
19718
18580
  throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);
19719
18581
  }
19720
18582
  return OAuthProtectedResourceMetadataSchema.parse(await response.json());
@@ -19768,7 +18630,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
19768
18630
  return response;
19769
18631
  }
19770
18632
  async function discoverOAuthMetadata(issuer, { authorizationServerUrl, protocolVersion } = {}, fetchFn = fetch) {
19771
- var _a, _b;
19772
18633
  if (typeof issuer === "string") {
19773
18634
  issuer = new URL(issuer);
19774
18635
  }
@@ -19784,11 +18645,9 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
19784
18645
  metadataServerUrl: authorizationServerUrl
19785
18646
  });
19786
18647
  if (!response || response.status === 404) {
19787
- await ((_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.cancel());
19788
18648
  return void 0;
19789
18649
  }
19790
18650
  if (!response.ok) {
19791
- await ((_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel());
19792
18651
  throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`);
19793
18652
  }
19794
18653
  return OAuthMetadataSchema.parse(await response.json());
@@ -19827,7 +18686,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
19827
18686
  return urlsToTry;
19828
18687
  }
19829
18688
  async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) {
19830
- var _a;
19831
18689
  const headers = {
19832
18690
  "MCP-Protocol-Version": protocolVersion,
19833
18691
  Accept: "application/json"
@@ -19839,7 +18697,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
19839
18697
  continue;
19840
18698
  }
19841
18699
  if (!response.ok) {
19842
- await ((_a = response.body) === null || _a === void 0 ? void 0 : _a.cancel());
19843
18700
  if (response.status >= 400 && response.status < 500) {
19844
18701
  continue;
19845
18702
  }
@@ -19888,92 +18745,81 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
19888
18745
  }
19889
18746
  return { authorizationUrl, codeVerifier };
19890
18747
  }
19891
- function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {
19892
- return new URLSearchParams({
19893
- grant_type: "authorization_code",
19894
- code: authorizationCode,
19895
- code_verifier: codeVerifier,
19896
- redirect_uri: String(redirectUri)
19897
- });
19898
- }
19899
- async function executeTokenRequest(authorizationServerUrl, { metadata: metadata2, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {
18748
+ async function exchangeAuthorization(authorizationServerUrl, { metadata: metadata2, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) {
19900
18749
  var _a;
18750
+ const grantType = "authorization_code";
19901
18751
  const tokenUrl = (metadata2 === null || metadata2 === void 0 ? void 0 : metadata2.token_endpoint) ? new URL(metadata2.token_endpoint) : new URL("/token", authorizationServerUrl);
18752
+ if ((metadata2 === null || metadata2 === void 0 ? void 0 : metadata2.grant_types_supported) && !metadata2.grant_types_supported.includes(grantType)) {
18753
+ throw new Error(`Incompatible auth server: does not support grant type ${grantType}`);
18754
+ }
19902
18755
  const headers = new Headers({
19903
18756
  "Content-Type": "application/x-www-form-urlencoded",
19904
18757
  Accept: "application/json"
19905
18758
  });
19906
- if (resource) {
19907
- tokenRequestParams.set("resource", resource.href);
19908
- }
18759
+ const params = new URLSearchParams({
18760
+ grant_type: grantType,
18761
+ code: authorizationCode,
18762
+ code_verifier: codeVerifier,
18763
+ redirect_uri: String(redirectUri)
18764
+ });
19909
18765
  if (addClientAuthentication) {
19910
- await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata2);
19911
- } else if (clientInformation) {
18766
+ addClientAuthentication(headers, params, authorizationServerUrl, metadata2);
18767
+ } else {
19912
18768
  const supportedMethods = (_a = metadata2 === null || metadata2 === void 0 ? void 0 : metadata2.token_endpoint_auth_methods_supported) !== null && _a !== void 0 ? _a : [];
19913
18769
  const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
19914
- applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);
18770
+ applyClientAuthentication(authMethod, clientInformation, headers, params);
18771
+ }
18772
+ if (resource) {
18773
+ params.set("resource", resource.href);
19915
18774
  }
19916
18775
  const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, {
19917
18776
  method: "POST",
19918
18777
  headers,
19919
- body: tokenRequestParams
18778
+ body: params
19920
18779
  });
19921
18780
  if (!response.ok) {
19922
18781
  throw await parseErrorResponse(response);
19923
18782
  }
19924
18783
  return OAuthTokensSchema.parse(await response.json());
19925
18784
  }
19926
- async function exchangeAuthorization(authorizationServerUrl, { metadata: metadata2, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) {
19927
- const tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri);
19928
- return executeTokenRequest(authorizationServerUrl, {
19929
- metadata: metadata2,
19930
- tokenRequestParams,
19931
- clientInformation,
19932
- addClientAuthentication,
19933
- resource,
19934
- fetchFn
19935
- });
19936
- }
19937
18785
  async function refreshAuthorization(authorizationServerUrl, { metadata: metadata2, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
19938
- const tokenRequestParams = new URLSearchParams({
19939
- grant_type: "refresh_token",
19940
- refresh_token: refreshToken
18786
+ var _a;
18787
+ const grantType = "refresh_token";
18788
+ let tokenUrl;
18789
+ if (metadata2) {
18790
+ tokenUrl = new URL(metadata2.token_endpoint);
18791
+ if (metadata2.grant_types_supported && !metadata2.grant_types_supported.includes(grantType)) {
18792
+ throw new Error(`Incompatible auth server: does not support grant type ${grantType}`);
18793
+ }
18794
+ } else {
18795
+ tokenUrl = new URL("/token", authorizationServerUrl);
18796
+ }
18797
+ const headers = new Headers({
18798
+ "Content-Type": "application/x-www-form-urlencoded"
19941
18799
  });
19942
- const tokens = await executeTokenRequest(authorizationServerUrl, {
19943
- metadata: metadata2,
19944
- tokenRequestParams,
19945
- clientInformation,
19946
- addClientAuthentication,
19947
- resource,
19948
- fetchFn
18800
+ const params = new URLSearchParams({
18801
+ grant_type: grantType,
18802
+ refresh_token: refreshToken
19949
18803
  });
19950
- return { refresh_token: refreshToken, ...tokens };
19951
- }
19952
- async function fetchToken(provider, authorizationServerUrl, { metadata: metadata2, resource, authorizationCode, fetchFn } = {}) {
19953
- const scope2 = provider.clientMetadata.scope;
19954
- let tokenRequestParams;
19955
- if (provider.prepareTokenRequest) {
19956
- tokenRequestParams = await provider.prepareTokenRequest(scope2);
18804
+ if (addClientAuthentication) {
18805
+ addClientAuthentication(headers, params, authorizationServerUrl, metadata2);
18806
+ } else {
18807
+ const supportedMethods = (_a = metadata2 === null || metadata2 === void 0 ? void 0 : metadata2.token_endpoint_auth_methods_supported) !== null && _a !== void 0 ? _a : [];
18808
+ const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
18809
+ applyClientAuthentication(authMethod, clientInformation, headers, params);
19957
18810
  }
19958
- if (!tokenRequestParams) {
19959
- if (!authorizationCode) {
19960
- throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");
19961
- }
19962
- if (!provider.redirectUrl) {
19963
- throw new Error("redirectUrl is required for authorization_code flow");
19964
- }
19965
- const codeVerifier = await provider.codeVerifier();
19966
- tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);
18811
+ if (resource) {
18812
+ params.set("resource", resource.href);
19967
18813
  }
19968
- const clientInformation = await provider.clientInformation();
19969
- return executeTokenRequest(authorizationServerUrl, {
19970
- metadata: metadata2,
19971
- tokenRequestParams,
19972
- clientInformation: clientInformation !== null && clientInformation !== void 0 ? clientInformation : void 0,
19973
- addClientAuthentication: provider.addClientAuthentication,
19974
- resource,
19975
- fetchFn
18814
+ const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, {
18815
+ method: "POST",
18816
+ headers,
18817
+ body: params
19976
18818
  });
18819
+ if (!response.ok) {
18820
+ throw await parseErrorResponse(response);
18821
+ }
18822
+ return OAuthTokensSchema.parse({ refresh_token: refreshToken, ...await response.json() });
19977
18823
  }
19978
18824
  async function registerClient(authorizationServerUrl, { metadata: metadata2, clientMetadata, fetchFn }) {
19979
18825
  let registrationUrl;
@@ -20442,11 +19288,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20442
19288
  if (this._protocolVersion) {
20443
19289
  headers["mcp-protocol-version"] = this._protocolVersion;
20444
19290
  }
20445
- const extraHeaders = normalizeHeaders((_a = this._requestInit) === null || _a === void 0 ? void 0 : _a.headers);
20446
- return new Headers({
20447
- ...headers,
20448
- ...extraHeaders
20449
- });
19291
+ return new Headers({ ...headers, ...(_a = this._requestInit) === null || _a === void 0 ? void 0 : _a.headers });
20450
19292
  }
20451
19293
  _startOrAuth() {
20452
19294
  var _a, _b, _c;
@@ -20543,7 +19385,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20543
19385
  (_c = this.onclose) === null || _c === void 0 ? void 0 : _c.call(this);
20544
19386
  }
20545
19387
  async send(message) {
20546
- var _a, _b, _c, _d;
19388
+ var _a, _b, _c;
20547
19389
  if (!this._endpoint) {
20548
19390
  throw new Error("Not connected");
20549
19391
  }
@@ -20559,7 +19401,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20559
19401
  };
20560
19402
  const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._endpoint, init);
20561
19403
  if (!response.ok) {
20562
- const text = await response.text().catch(() => null);
20563
19404
  if (response.status === 401 && this._authProvider) {
20564
19405
  const { resourceMetadataUrl, scope: scope2 } = extractWWWAuthenticateParams(response);
20565
19406
  this._resourceMetadataUrl = resourceMetadataUrl;
@@ -20575,11 +19416,11 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20575
19416
  }
20576
19417
  return this.send(message);
20577
19418
  }
19419
+ const text = await response.text().catch(() => null);
20578
19420
  throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
20579
19421
  }
20580
- await ((_c = response.body) === null || _c === void 0 ? void 0 : _c.cancel());
20581
19422
  } catch (error) {
20582
- (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, error);
19423
+ (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error);
20583
19424
  throw error;
20584
19425
  }
20585
19426
  }
@@ -20679,7 +19520,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20679
19520
  });
20680
19521
  }
20681
19522
  async _startOrAuthSse(options) {
20682
- var _a, _b, _c, _d;
19523
+ var _a, _b, _c;
20683
19524
  const { resumptionToken } = options;
20684
19525
  try {
20685
19526
  const headers = await this._commonHeaders();
@@ -20693,7 +19534,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20693
19534
  signal: (_b = this._abortController) === null || _b === void 0 ? void 0 : _b.signal
20694
19535
  });
20695
19536
  if (!response.ok) {
20696
- await ((_c = response.body) === null || _c === void 0 ? void 0 : _c.cancel());
20697
19537
  if (response.status === 401 && this._authProvider) {
20698
19538
  return await this._authThenStart();
20699
19539
  }
@@ -20704,7 +19544,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20704
19544
  }
20705
19545
  this._handleSseStream(response.body, options, true);
20706
19546
  } catch (error) {
20707
- (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, error);
19547
+ (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error);
20708
19548
  throw error;
20709
19549
  }
20710
19550
  }
@@ -20732,12 +19572,12 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20732
19572
  _scheduleReconnection(options, attemptCount = 0) {
20733
19573
  var _a;
20734
19574
  const maxRetries = this._reconnectionOptions.maxRetries;
20735
- if (attemptCount >= maxRetries) {
19575
+ if (maxRetries > 0 && attemptCount >= maxRetries) {
20736
19576
  (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
20737
19577
  return;
20738
19578
  }
20739
19579
  const delay = this._getNextReconnectionDelay(attemptCount);
20740
- this._reconnectionTimeout = setTimeout(() => {
19580
+ setTimeout(() => {
20741
19581
  this._startOrAuthSse(options).catch((error) => {
20742
19582
  var _a2;
20743
19583
  (_a2 = this.onerror) === null || _a2 === void 0 ? void 0 : _a2.call(this, new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));
@@ -20752,7 +19592,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20752
19592
  const { onresumptiontoken, replayMessageId } = options;
20753
19593
  let lastEventId;
20754
19594
  let hasPrimingEvent = false;
20755
- let receivedResponse = false;
20756
19595
  const processStream = async () => {
20757
19596
  var _a, _b, _c, _d;
20758
19597
  try {
@@ -20771,17 +19610,11 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20771
19610
  hasPrimingEvent = true;
20772
19611
  onresumptiontoken === null || onresumptiontoken === void 0 ? void 0 : onresumptiontoken(event.id);
20773
19612
  }
20774
- if (!event.data) {
20775
- continue;
20776
- }
20777
19613
  if (!event.event || event.event === "message") {
20778
19614
  try {
20779
19615
  const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
20780
- if (isJSONRPCResponse(message)) {
20781
- receivedResponse = true;
20782
- if (replayMessageId !== void 0) {
20783
- message.id = replayMessageId;
20784
- }
19616
+ if (replayMessageId !== void 0 && isJSONRPCResponse(message)) {
19617
+ message.id = replayMessageId;
20785
19618
  }
20786
19619
  (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message);
20787
19620
  } catch (error) {
@@ -20790,8 +19623,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20790
19623
  }
20791
19624
  }
20792
19625
  const canResume = isReconnectable || hasPrimingEvent;
20793
- const needsReconnect = canResume && !receivedResponse;
20794
- if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
19626
+ if (canResume && this._abortController && !this._abortController.signal.aborted) {
20795
19627
  this._scheduleReconnection({
20796
19628
  resumptionToken: lastEventId,
20797
19629
  onresumptiontoken,
@@ -20801,8 +19633,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20801
19633
  } catch (error) {
20802
19634
  (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, new Error(`SSE stream disconnected: ${error}`));
20803
19635
  const canResume = isReconnectable || hasPrimingEvent;
20804
- const needsReconnect = canResume && !receivedResponse;
20805
- if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
19636
+ if (canResume && this._abortController && !this._abortController.signal.aborted) {
20806
19637
  try {
20807
19638
  this._scheduleReconnection({
20808
19639
  resumptionToken: lastEventId,
@@ -20843,15 +19674,11 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20843
19674
  }
20844
19675
  async close() {
20845
19676
  var _a, _b;
20846
- if (this._reconnectionTimeout) {
20847
- clearTimeout(this._reconnectionTimeout);
20848
- this._reconnectionTimeout = void 0;
20849
- }
20850
19677
  (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.abort();
20851
19678
  (_b = this.onclose) === null || _b === void 0 ? void 0 : _b.call(this);
20852
19679
  }
20853
19680
  async send(message, options) {
20854
- var _a, _b, _c, _d, _e, _f, _g;
19681
+ var _a, _b, _c, _d;
20855
19682
  try {
20856
19683
  const { resumptionToken, onresumptiontoken } = options || {};
20857
19684
  if (resumptionToken) {
@@ -20877,7 +19704,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20877
19704
  this._sessionId = sessionId;
20878
19705
  }
20879
19706
  if (!response.ok) {
20880
- const text = await response.text().catch(() => null);
20881
19707
  if (response.status === 401 && this._authProvider) {
20882
19708
  if (this._hasCompletedAuthFlow) {
20883
19709
  throw new StreamableHTTPError(401, "Server returned 401 after successful authentication");
@@ -20923,12 +19749,12 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20923
19749
  return this.send(message);
20924
19750
  }
20925
19751
  }
20926
- throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);
19752
+ const text = await response.text().catch(() => null);
19753
+ throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
20927
19754
  }
20928
19755
  this._hasCompletedAuthFlow = false;
20929
19756
  this._lastUpscopingHeader = void 0;
20930
19757
  if (response.status === 202) {
20931
- await ((_c = response.body) === null || _c === void 0 ? void 0 : _c.cancel());
20932
19758
  if (isInitializedNotification(message)) {
20933
19759
  this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => {
20934
19760
  var _a2;
@@ -20947,17 +19773,14 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20947
19773
  const data = await response.json();
20948
19774
  const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)];
20949
19775
  for (const msg of responseMessages) {
20950
- (_d = this.onmessage) === null || _d === void 0 ? void 0 : _d.call(this, msg);
19776
+ (_c = this.onmessage) === null || _c === void 0 ? void 0 : _c.call(this, msg);
20951
19777
  }
20952
19778
  } else {
20953
- await ((_e = response.body) === null || _e === void 0 ? void 0 : _e.cancel());
20954
19779
  throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);
20955
19780
  }
20956
- } else {
20957
- await ((_f = response.body) === null || _f === void 0 ? void 0 : _f.cancel());
20958
19781
  }
20959
19782
  } catch (error) {
20960
- (_g = this.onerror) === null || _g === void 0 ? void 0 : _g.call(this, error);
19783
+ (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, error);
20961
19784
  throw error;
20962
19785
  }
20963
19786
  }
@@ -20976,7 +19799,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20976
19799
  * the server does not allow clients to terminate sessions.
20977
19800
  */
20978
19801
  async terminateSession() {
20979
- var _a, _b, _c, _d;
19802
+ var _a, _b, _c;
20980
19803
  if (!this._sessionId) {
20981
19804
  return;
20982
19805
  }
@@ -20989,13 +19812,12 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20989
19812
  signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal
20990
19813
  };
20991
19814
  const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._url, init);
20992
- await ((_c = response.body) === null || _c === void 0 ? void 0 : _c.cancel());
20993
19815
  if (!response.ok && response.status !== 405) {
20994
19816
  throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);
20995
19817
  }
20996
19818
  this._sessionId = void 0;
20997
19819
  } catch (error) {
20998
- (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, error);
19820
+ (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error);
20999
19821
  throw error;
21000
19822
  }
21001
19823
  }
@@ -21019,76 +19841,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
21019
19841
  });
21020
19842
  }
21021
19843
  }
21022
- class ExperimentalServerTasks {
21023
- constructor(_server) {
21024
- this._server = _server;
21025
- }
21026
- /**
21027
- * Sends a request and returns an AsyncGenerator that yields response messages.
21028
- * The generator is guaranteed to end with either a 'result' or 'error' message.
21029
- *
21030
- * This method provides streaming access to request processing, allowing you to
21031
- * observe intermediate task status updates for task-augmented requests.
21032
- *
21033
- * @param request - The request to send
21034
- * @param resultSchema - Zod schema for validating the result
21035
- * @param options - Optional request options (timeout, signal, task creation params, etc.)
21036
- * @returns AsyncGenerator that yields ResponseMessage objects
21037
- *
21038
- * @experimental
21039
- */
21040
- requestStream(request, resultSchema, options) {
21041
- return this._server.requestStream(request, resultSchema, options);
21042
- }
21043
- /**
21044
- * Gets the current status of a task.
21045
- *
21046
- * @param taskId - The task identifier
21047
- * @param options - Optional request options
21048
- * @returns The task status
21049
- *
21050
- * @experimental
21051
- */
21052
- async getTask(taskId, options) {
21053
- return this._server.getTask({ taskId }, options);
21054
- }
21055
- /**
21056
- * Retrieves the result of a completed task.
21057
- *
21058
- * @param taskId - The task identifier
21059
- * @param resultSchema - Zod schema for validating the result
21060
- * @param options - Optional request options
21061
- * @returns The task result
21062
- *
21063
- * @experimental
21064
- */
21065
- async getTaskResult(taskId, resultSchema, options) {
21066
- return this._server.getTaskResult({ taskId }, resultSchema, options);
21067
- }
21068
- /**
21069
- * Lists tasks with optional pagination.
21070
- *
21071
- * @param cursor - Optional pagination cursor
21072
- * @param options - Optional request options
21073
- * @returns List of tasks with optional next cursor
21074
- *
21075
- * @experimental
21076
- */
21077
- async listTasks(cursor, options) {
21078
- return this._server.listTasks(cursor ? { cursor } : void 0, options);
21079
- }
21080
- /**
21081
- * Cancels a running task.
21082
- *
21083
- * @param taskId - The task identifier
21084
- * @param options - Optional request options
21085
- *
21086
- * @experimental
21087
- */
21088
- async cancelTask(taskId, options) {
21089
- return this._server.cancelTask({ taskId }, options);
21090
- }
21091
- }
21092
19844
  class Server extends Protocol {
21093
19845
  /**
21094
19846
  * Initializes this server with the given name and version information.
@@ -21124,21 +19876,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
21124
19876
  });
21125
19877
  }
21126
19878
  }
21127
- /**
21128
- * Access experimental features.
21129
- *
21130
- * WARNING: These APIs are experimental and may change without notice.
21131
- *
21132
- * @experimental
21133
- */
21134
- get experimental() {
21135
- if (!this._experimental) {
21136
- this._experimental = {
21137
- tasks: new ExperimentalServerTasks(this)
21138
- };
21139
- }
21140
- return this._experimental;
21141
- }
21142
19879
  /**
21143
19880
  * Registers new capabilities. This can only be called before connecting to a transport.
21144
19881
  *
@@ -21150,58 +19887,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
21150
19887
  }
21151
19888
  this._capabilities = mergeCapabilities(this._capabilities, capabilities);
21152
19889
  }
21153
- /**
21154
- * Override request handler registration to enforce server-side validation for tools/call.
21155
- */
21156
- setRequestHandler(requestSchema, handler) {
21157
- var _a, _b, _c;
21158
- const shape = getObjectShape(requestSchema);
21159
- const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method;
21160
- if (!methodSchema) {
21161
- throw new Error("Schema is missing a method literal");
21162
- }
21163
- let methodValue;
21164
- if (isZ4Schema(methodSchema)) {
21165
- const v4Schema = methodSchema;
21166
- const v4Def = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def;
21167
- methodValue = (_b = v4Def === null || v4Def === void 0 ? void 0 : v4Def.value) !== null && _b !== void 0 ? _b : v4Schema.value;
21168
- } else {
21169
- const v3Schema = methodSchema;
21170
- const legacyDef = v3Schema._def;
21171
- methodValue = (_c = legacyDef === null || legacyDef === void 0 ? void 0 : legacyDef.value) !== null && _c !== void 0 ? _c : v3Schema.value;
21172
- }
21173
- if (typeof methodValue !== "string") {
21174
- throw new Error("Schema method literal must be a string");
21175
- }
21176
- const method = methodValue;
21177
- if (method === "tools/call") {
21178
- const wrappedHandler = async (request, extra) => {
21179
- const validatedRequest = safeParse(CallToolRequestSchema, request);
21180
- if (!validatedRequest.success) {
21181
- const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
21182
- throw new McpError(exports2.ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`);
21183
- }
21184
- const { params } = validatedRequest.data;
21185
- const result = await Promise.resolve(handler(request, extra));
21186
- if (params.task) {
21187
- const taskValidationResult = safeParse(CreateTaskResultSchema, result);
21188
- if (!taskValidationResult.success) {
21189
- const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
21190
- throw new McpError(exports2.ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
21191
- }
21192
- return taskValidationResult.data;
21193
- }
21194
- const validationResult = safeParse(CallToolResultSchema, result);
21195
- if (!validationResult.success) {
21196
- const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
21197
- throw new McpError(exports2.ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`);
21198
- }
21199
- return validationResult.data;
21200
- };
21201
- return super.setRequestHandler(requestSchema, wrappedHandler);
21202
- }
21203
- return super.setRequestHandler(requestSchema, handler);
21204
- }
21205
19890
  assertCapabilityForMethod(method) {
21206
19891
  var _a, _b, _c;
21207
19892
  switch (method) {
@@ -21254,9 +19939,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
21254
19939
  }
21255
19940
  }
21256
19941
  assertRequestHandlerCapability(method) {
21257
- if (!this._capabilities) {
21258
- return;
21259
- }
21260
19942
  switch (method) {
21261
19943
  case "completion/complete":
21262
19944
  if (!this._capabilities.completions) {
@@ -21287,26 +19969,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
21287
19969
  throw new Error(`Server does not support tools (required for ${method})`);
21288
19970
  }
21289
19971
  break;
21290
- case "tasks/get":
21291
- case "tasks/list":
21292
- case "tasks/result":
21293
- case "tasks/cancel":
21294
- if (!this._capabilities.tasks) {
21295
- throw new Error(`Server does not support tasks capability (required for ${method})`);
21296
- }
21297
- break;
21298
- }
21299
- }
21300
- assertTaskCapability(method) {
21301
- var _a, _b;
21302
- assertClientRequestTaskCapability((_b = (_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.tasks) === null || _b === void 0 ? void 0 : _b.requests, method, "Client");
21303
- }
21304
- assertTaskHandlerCapability(method) {
21305
- var _a;
21306
- if (!this._capabilities) {
21307
- return;
21308
19972
  }
21309
- assertToolsCallTaskCapability((_a = this._capabilities.tasks) === null || _a === void 0 ? void 0 : _a.requests, method, "Server");
21310
19973
  }
21311
19974
  async _oninitialize(request) {
21312
19975
  const requestedVersion = request.params.protocolVersion;
@@ -21338,7 +20001,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
21338
20001
  async ping() {
21339
20002
  return this.request({ method: "ping" }, EmptyResultSchema);
21340
20003
  }
21341
- // Implementation
21342
20004
  async createMessage(params, options) {
21343
20005
  var _a, _b;
21344
20006
  if (params.tools || params.toolChoice) {
@@ -21369,9 +20031,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
21369
20031
  }
21370
20032
  }
21371
20033
  }
21372
- if (params.tools) {
21373
- return this.request({ method: "sampling/createMessage", params }, CreateMessageResultWithToolsSchema, options);
21374
- }
21375
20034
  return this.request({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options);
21376
20035
  }
21377
20036
  /**
@@ -21527,19 +20186,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
21527
20186
  issueToolNameWarning(name, result.warnings);
21528
20187
  return result.isValid;
21529
20188
  }
21530
- class ExperimentalMcpServerTasks {
21531
- constructor(_mcpServer) {
21532
- this._mcpServer = _mcpServer;
21533
- }
21534
- registerToolTask(name, config2, handler) {
21535
- const execution = { taskSupport: "required", ...config2.execution };
21536
- if (execution.taskSupport === "forbidden") {
21537
- throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`);
21538
- }
21539
- const mcpServerInternal = this._mcpServer;
21540
- return mcpServerInternal._createRegisteredTool(name, config2.title, config2.description, config2.inputSchema, config2.outputSchema, config2.annotations, execution, config2._meta, handler);
21541
- }
21542
- }
21543
20189
  class McpServer {
21544
20190
  constructor(serverInfo, options) {
21545
20191
  this._registeredResources = {};
@@ -21552,21 +20198,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
21552
20198
  this._promptHandlersInitialized = false;
21553
20199
  this.server = new Server(serverInfo, options);
21554
20200
  }
21555
- /**
21556
- * Access experimental features.
21557
- *
21558
- * WARNING: These APIs are experimental and may change without notice.
21559
- *
21560
- * @experimental
21561
- */
21562
- get experimental() {
21563
- if (!this._experimental) {
21564
- this._experimental = {
21565
- tasks: new ExperimentalMcpServerTasks(this)
21566
- };
21567
- }
21568
- return this._experimental;
21569
- }
21570
20201
  /**
21571
20202
  * Attaches to the given transport, starts it, and starts listening for messages.
21572
20203
  *
@@ -21606,7 +20237,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
21606
20237
  }) : EMPTY_OBJECT_JSON_SCHEMA;
21607
20238
  })(),
21608
20239
  annotations: tool.annotations,
21609
- execution: tool.execution,
21610
20240
  _meta: tool._meta
21611
20241
  };
21612
20242
  if (tool.outputSchema) {
@@ -21622,34 +20252,39 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
21622
20252
  })
21623
20253
  }));
21624
20254
  this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
21625
- var _a;
20255
+ const tool = this._registeredTools[request.params.name];
20256
+ let result;
21626
20257
  try {
21627
- const tool = this._registeredTools[request.params.name];
21628
20258
  if (!tool) {
21629
20259
  throw new McpError(exports2.ErrorCode.InvalidParams, `Tool ${request.params.name} not found`);
21630
20260
  }
21631
20261
  if (!tool.enabled) {
21632
20262
  throw new McpError(exports2.ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);
21633
20263
  }
21634
- const isTaskRequest = !!request.params.task;
21635
- const taskSupport = (_a = tool.execution) === null || _a === void 0 ? void 0 : _a.taskSupport;
21636
- const isTaskHandler = "createTask" in tool.handler;
21637
- if ((taskSupport === "required" || taskSupport === "optional") && !isTaskHandler) {
21638
- throw new McpError(exports2.ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`);
21639
- }
21640
- if (taskSupport === "required" && !isTaskRequest) {
21641
- throw new McpError(exports2.ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`);
21642
- }
21643
- if (taskSupport === "optional" && !isTaskRequest && isTaskHandler) {
21644
- return await this.handleAutomaticTaskPolling(tool, request, extra);
20264
+ if (tool.inputSchema) {
20265
+ const cb = tool.callback;
20266
+ const inputObj = normalizeObjectSchema(tool.inputSchema);
20267
+ const schemaToParse = inputObj !== null && inputObj !== void 0 ? inputObj : tool.inputSchema;
20268
+ const parseResult = await safeParseAsync(schemaToParse, request.params.arguments);
20269
+ if (!parseResult.success) {
20270
+ throw new McpError(exports2.ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${request.params.name}: ${getParseErrorMessage(parseResult.error)}`);
20271
+ }
20272
+ const args = parseResult.data;
20273
+ result = await Promise.resolve(cb(args, extra));
20274
+ } else {
20275
+ const cb = tool.callback;
20276
+ result = await Promise.resolve(cb(extra));
21645
20277
  }
21646
- const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
21647
- const result = await this.executeToolHandler(tool, args, extra);
21648
- if (isTaskRequest) {
21649
- return result;
20278
+ if (tool.outputSchema && !result.isError) {
20279
+ if (!result.structuredContent) {
20280
+ throw new McpError(exports2.ErrorCode.InvalidParams, `Output validation error: Tool ${request.params.name} has an output schema but no structured content was provided`);
20281
+ }
20282
+ const outputObj = normalizeObjectSchema(tool.outputSchema);
20283
+ const parseResult = await safeParseAsync(outputObj, result.structuredContent);
20284
+ if (!parseResult.success) {
20285
+ throw new McpError(exports2.ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${request.params.name}: ${getParseErrorMessage(parseResult.error)}`);
20286
+ }
21650
20287
  }
21651
- await this.validateToolOutput(tool, result, request.params.name);
21652
- return result;
21653
20288
  } catch (error) {
21654
20289
  if (error instanceof McpError) {
21655
20290
  if (error.code === exports2.ErrorCode.UrlElicitationRequired) {
@@ -21658,6 +20293,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
21658
20293
  }
21659
20294
  return this.createToolError(error instanceof Error ? error.message : String(error));
21660
20295
  }
20296
+ return result;
21661
20297
  });
21662
20298
  this._toolHandlersInitialized = true;
21663
20299
  }
@@ -21678,102 +20314,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
21678
20314
  isError: true
21679
20315
  };
21680
20316
  }
21681
- /**
21682
- * Validates tool input arguments against the tool's input schema.
21683
- */
21684
- async validateToolInput(tool, args, toolName) {
21685
- if (!tool.inputSchema) {
21686
- return void 0;
21687
- }
21688
- const inputObj = normalizeObjectSchema(tool.inputSchema);
21689
- const schemaToParse = inputObj !== null && inputObj !== void 0 ? inputObj : tool.inputSchema;
21690
- const parseResult = await safeParseAsync(schemaToParse, args);
21691
- if (!parseResult.success) {
21692
- const error = "error" in parseResult ? parseResult.error : "Unknown error";
21693
- const errorMessage = getParseErrorMessage(error);
21694
- throw new McpError(exports2.ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`);
21695
- }
21696
- return parseResult.data;
21697
- }
21698
- /**
21699
- * Validates tool output against the tool's output schema.
21700
- */
21701
- async validateToolOutput(tool, result, toolName) {
21702
- if (!tool.outputSchema) {
21703
- return;
21704
- }
21705
- if (!("content" in result)) {
21706
- return;
21707
- }
21708
- if (result.isError) {
21709
- return;
21710
- }
21711
- if (!result.structuredContent) {
21712
- throw new McpError(exports2.ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);
21713
- }
21714
- const outputObj = normalizeObjectSchema(tool.outputSchema);
21715
- const parseResult = await safeParseAsync(outputObj, result.structuredContent);
21716
- if (!parseResult.success) {
21717
- const error = "error" in parseResult ? parseResult.error : "Unknown error";
21718
- const errorMessage = getParseErrorMessage(error);
21719
- throw new McpError(exports2.ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`);
21720
- }
21721
- }
21722
- /**
21723
- * Executes a tool handler (either regular or task-based).
21724
- */
21725
- async executeToolHandler(tool, args, extra) {
21726
- const handler = tool.handler;
21727
- const isTaskHandler = "createTask" in handler;
21728
- if (isTaskHandler) {
21729
- if (!extra.taskStore) {
21730
- throw new Error("No task store provided.");
21731
- }
21732
- const taskExtra = { ...extra, taskStore: extra.taskStore };
21733
- if (tool.inputSchema) {
21734
- const typedHandler = handler;
21735
- return await Promise.resolve(typedHandler.createTask(args, taskExtra));
21736
- } else {
21737
- const typedHandler = handler;
21738
- return await Promise.resolve(typedHandler.createTask(taskExtra));
21739
- }
21740
- }
21741
- if (tool.inputSchema) {
21742
- const typedHandler = handler;
21743
- return await Promise.resolve(typedHandler(args, extra));
21744
- } else {
21745
- const typedHandler = handler;
21746
- return await Promise.resolve(typedHandler(extra));
21747
- }
21748
- }
21749
- /**
21750
- * Handles automatic task polling for tools with taskSupport 'optional'.
21751
- */
21752
- async handleAutomaticTaskPolling(tool, request, extra) {
21753
- var _a;
21754
- if (!extra.taskStore) {
21755
- throw new Error("No task store provided for task-capable tool.");
21756
- }
21757
- const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
21758
- const handler = tool.handler;
21759
- const taskExtra = { ...extra, taskStore: extra.taskStore };
21760
- const createTaskResult = args ? await Promise.resolve(handler.createTask(args, taskExtra)) : (
21761
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
21762
- await Promise.resolve(handler.createTask(taskExtra))
21763
- );
21764
- const taskId = createTaskResult.task.taskId;
21765
- let task = createTaskResult.task;
21766
- const pollInterval = (_a = task.pollInterval) !== null && _a !== void 0 ? _a : 5e3;
21767
- while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {
21768
- await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
21769
- const updatedTask = await extra.taskStore.getTask(taskId);
21770
- if (!updatedTask) {
21771
- throw new McpError(exports2.ErrorCode.InternalError, `Task ${taskId} not found during polling`);
21772
- }
21773
- task = updatedTask;
21774
- }
21775
- return await extra.taskStore.getTaskResult(taskId);
21776
- }
21777
20317
  setCompletionRequestHandler() {
21778
20318
  if (this._completionHandlerInitialized) {
21779
20319
  return;
@@ -21929,9 +20469,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
21929
20469
  const argsObj = normalizeObjectSchema(prompt.argsSchema);
21930
20470
  const parseResult = await safeParseAsync(argsObj, request.params.arguments);
21931
20471
  if (!parseResult.success) {
21932
- const error = "error" in parseResult ? parseResult.error : "Unknown error";
21933
- const errorMessage = getParseErrorMessage(error);
21934
- throw new McpError(exports2.ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage}`);
20472
+ throw new McpError(exports2.ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${getParseErrorMessage(parseResult.error)}`);
21935
20473
  }
21936
20474
  const args = parseResult.data;
21937
20475
  const cb = prompt.callback;
@@ -22083,7 +20621,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22083
20621
  this._registeredPrompts[name] = registeredPrompt;
22084
20622
  return registeredPrompt;
22085
20623
  }
22086
- _createRegisteredTool(name, title2, description2, inputSchema, outputSchema, annotations, execution, _meta, handler) {
20624
+ _createRegisteredTool(name, title2, description2, inputSchema, outputSchema, annotations, _meta, callback) {
22087
20625
  validateAndWarnToolName(name);
22088
20626
  const registeredTool = {
22089
20627
  title: title2,
@@ -22091,9 +20629,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22091
20629
  inputSchema: getZodSchemaObject(inputSchema),
22092
20630
  outputSchema: getZodSchemaObject(outputSchema),
22093
20631
  annotations,
22094
- execution,
22095
20632
  _meta,
22096
- handler,
20633
+ callback,
22097
20634
  enabled: true,
22098
20635
  disable: () => registeredTool.update({ enabled: false }),
22099
20636
  enable: () => registeredTool.update({ enabled: true }),
@@ -22114,7 +20651,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22114
20651
  if (typeof updates.paramsSchema !== "undefined")
22115
20652
  registeredTool.inputSchema = objectFromShape(updates.paramsSchema);
22116
20653
  if (typeof updates.callback !== "undefined")
22117
- registeredTool.handler = updates.callback;
20654
+ registeredTool.callback = updates.callback;
22118
20655
  if (typeof updates.annotations !== "undefined")
22119
20656
  registeredTool.annotations = updates.annotations;
22120
20657
  if (typeof updates._meta !== "undefined")
@@ -22145,9 +20682,9 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22145
20682
  }
22146
20683
  if (rest.length > 1) {
22147
20684
  const firstArg = rest[0];
22148
- if (isZodRawShapeCompat(firstArg)) {
20685
+ if (isZodRawShape(firstArg)) {
22149
20686
  inputSchema = rest.shift();
22150
- if (rest.length > 1 && typeof rest[0] === "object" && rest[0] !== null && !isZodRawShapeCompat(rest[0])) {
20687
+ if (rest.length > 1 && typeof rest[0] === "object" && rest[0] !== null && !isZodRawShape(rest[0])) {
22151
20688
  annotations = rest.shift();
22152
20689
  }
22153
20690
  } else if (typeof firstArg === "object" && firstArg !== null) {
@@ -22155,7 +20692,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22155
20692
  }
22156
20693
  }
22157
20694
  const callback = rest[0];
22158
- return this._createRegisteredTool(name, void 0, description2, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, void 0, callback);
20695
+ return this._createRegisteredTool(name, void 0, description2, inputSchema, outputSchema, annotations, void 0, callback);
22159
20696
  }
22160
20697
  /**
22161
20698
  * Registers a tool with a config object and callback.
@@ -22165,7 +20702,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22165
20702
  throw new Error(`Tool ${name} is already registered`);
22166
20703
  }
22167
20704
  const { title: title2, description: description2, inputSchema, outputSchema, annotations, _meta } = config2;
22168
- return this._createRegisteredTool(name, title2, description2, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, _meta, cb);
20705
+ return this._createRegisteredTool(name, title2, description2, inputSchema, outputSchema, annotations, _meta, cb);
22169
20706
  }
22170
20707
  prompt(name, ...rest) {
22171
20708
  if (this._registeredPrompts[name]) {
@@ -22269,29 +20806,20 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22269
20806
  type: "object",
22270
20807
  properties: {}
22271
20808
  };
20809
+ function isZodRawShape(obj) {
20810
+ if (typeof obj !== "object" || obj === null)
20811
+ return false;
20812
+ const isEmptyObject = Object.keys(obj).length === 0;
20813
+ return isEmptyObject || Object.values(obj).some(isZodTypeLike);
20814
+ }
22272
20815
  function isZodTypeLike(value) {
22273
20816
  return value !== null && typeof value === "object" && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
22274
20817
  }
22275
- function isZodSchemaInstance(obj) {
22276
- return "_def" in obj || "_zod" in obj || isZodTypeLike(obj);
22277
- }
22278
- function isZodRawShapeCompat(obj) {
22279
- if (typeof obj !== "object" || obj === null) {
22280
- return false;
22281
- }
22282
- if (isZodSchemaInstance(obj)) {
22283
- return false;
22284
- }
22285
- if (Object.keys(obj).length === 0) {
22286
- return true;
22287
- }
22288
- return Object.values(obj).some(isZodTypeLike);
22289
- }
22290
20818
  function getZodSchemaObject(schema) {
22291
20819
  if (!schema) {
22292
20820
  return void 0;
22293
20821
  }
22294
- if (isZodRawShapeCompat(schema)) {
20822
+ if (isZodRawShape(schema)) {
22295
20823
  return objectFromShape(schema);
22296
20824
  }
22297
20825
  return schema;
@@ -22338,7 +20866,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22338
20866
  }
22339
20867
  };
22340
20868
  exports2.Ajv = ajv;
22341
- exports2.AnnotationsSchema = AnnotationsSchema;
22342
20869
  exports2.AudioContentSchema = AudioContentSchema;
22343
20870
  exports2.BaseMetadataSchema = BaseMetadataSchema;
22344
20871
  exports2.BlobResourceContentsSchema = BlobResourceContentsSchema;
@@ -22347,8 +20874,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22347
20874
  exports2.CallToolRequestParamsSchema = CallToolRequestParamsSchema;
22348
20875
  exports2.CallToolRequestSchema = CallToolRequestSchema;
22349
20876
  exports2.CallToolResultSchema = CallToolResultSchema;
22350
- exports2.CancelTaskRequestSchema = CancelTaskRequestSchema;
22351
- exports2.CancelTaskResultSchema = CancelTaskResultSchema;
22352
20877
  exports2.CancelledNotificationParamsSchema = CancelledNotificationParamsSchema;
22353
20878
  exports2.CancelledNotificationSchema = CancelledNotificationSchema;
22354
20879
  exports2.Client = Client;
@@ -22356,7 +20881,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22356
20881
  exports2.ClientNotificationSchema = ClientNotificationSchema;
22357
20882
  exports2.ClientRequestSchema = ClientRequestSchema;
22358
20883
  exports2.ClientResultSchema = ClientResultSchema;
22359
- exports2.ClientTasksCapabilitySchema = ClientTasksCapabilitySchema;
22360
20884
  exports2.CompatibilityCallToolResultSchema = CompatibilityCallToolResultSchema;
22361
20885
  exports2.CompleteRequestParamsSchema = CompleteRequestParamsSchema;
22362
20886
  exports2.CompleteRequestSchema = CompleteRequestSchema;
@@ -22365,8 +20889,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22365
20889
  exports2.CreateMessageRequestParamsSchema = CreateMessageRequestParamsSchema;
22366
20890
  exports2.CreateMessageRequestSchema = CreateMessageRequestSchema;
22367
20891
  exports2.CreateMessageResultSchema = CreateMessageResultSchema;
22368
- exports2.CreateMessageResultWithToolsSchema = CreateMessageResultWithToolsSchema;
22369
- exports2.CreateTaskResultSchema = CreateTaskResultSchema;
22370
20892
  exports2.CursorSchema = CursorSchema;
22371
20893
  exports2.DEFAULT_NEGOTIATED_PROTOCOL_VERSION = DEFAULT_NEGOTIATED_PROTOCOL_VERSION;
22372
20894
  exports2.DEFAULT_REQUEST_TIMEOUT_MSEC = DEFAULT_REQUEST_TIMEOUT_MSEC;
@@ -22383,9 +20905,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22383
20905
  exports2.GetPromptRequestParamsSchema = GetPromptRequestParamsSchema;
22384
20906
  exports2.GetPromptRequestSchema = GetPromptRequestSchema;
22385
20907
  exports2.GetPromptResultSchema = GetPromptResultSchema;
22386
- exports2.GetTaskPayloadRequestSchema = GetTaskPayloadRequestSchema;
22387
- exports2.GetTaskRequestSchema = GetTaskRequestSchema;
22388
- exports2.GetTaskResultSchema = GetTaskResultSchema;
22389
20908
  exports2.IconSchema = IconSchema;
22390
20909
  exports2.IconsSchema = IconsSchema;
22391
20910
  exports2.ImageContentSchema = ImageContentSchema;
@@ -22410,8 +20929,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22410
20929
  exports2.ListResourcesResultSchema = ListResourcesResultSchema;
22411
20930
  exports2.ListRootsRequestSchema = ListRootsRequestSchema;
22412
20931
  exports2.ListRootsResultSchema = ListRootsResultSchema;
22413
- exports2.ListTasksRequestSchema = ListTasksRequestSchema;
22414
- exports2.ListTasksResultSchema = ListTasksResultSchema;
22415
20932
  exports2.ListToolsRequestSchema = ListToolsRequestSchema;
22416
20933
  exports2.ListToolsResultSchema = ListToolsResultSchema;
22417
20934
  exports2.LoggingLevelSchema = LoggingLevelSchema;
@@ -22439,11 +20956,9 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22439
20956
  exports2.PromptReferenceSchema = PromptReferenceSchema;
22440
20957
  exports2.PromptSchema = PromptSchema;
22441
20958
  exports2.Protocol = Protocol;
22442
- exports2.RELATED_TASK_META_KEY = RELATED_TASK_META_KEY;
22443
20959
  exports2.ReadResourceRequestParamsSchema = ReadResourceRequestParamsSchema;
22444
20960
  exports2.ReadResourceRequestSchema = ReadResourceRequestSchema;
22445
20961
  exports2.ReadResourceResultSchema = ReadResourceResultSchema;
22446
- exports2.RelatedTaskMetadataSchema = RelatedTaskMetadataSchema;
22447
20962
  exports2.RequestIdSchema = RequestIdSchema;
22448
20963
  exports2.RequestSchema = RequestSchema;
22449
20964
  exports2.ResourceContentsSchema = ResourceContentsSchema;
@@ -22462,14 +20977,12 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22462
20977
  exports2.RootsListChangedNotificationSchema = RootsListChangedNotificationSchema;
22463
20978
  exports2.SSEClientTransport = SSEClientTransport;
22464
20979
  exports2.SUPPORTED_PROTOCOL_VERSIONS = SUPPORTED_PROTOCOL_VERSIONS;
22465
- exports2.SamplingContentSchema = SamplingContentSchema;
22466
20980
  exports2.SamplingMessageContentBlockSchema = SamplingMessageContentBlockSchema;
22467
20981
  exports2.SamplingMessageSchema = SamplingMessageSchema;
22468
20982
  exports2.ServerCapabilitiesSchema = ServerCapabilitiesSchema;
22469
20983
  exports2.ServerNotificationSchema = ServerNotificationSchema;
22470
20984
  exports2.ServerRequestSchema = ServerRequestSchema;
22471
20985
  exports2.ServerResultSchema = ServerResultSchema;
22472
- exports2.ServerTasksCapabilitySchema = ServerTasksCapabilitySchema;
22473
20986
  exports2.SetLevelRequestParamsSchema = SetLevelRequestParamsSchema;
22474
20987
  exports2.SetLevelRequestSchema = SetLevelRequestSchema;
22475
20988
  exports2.SingleSelectEnumSchemaSchema = SingleSelectEnumSchemaSchema;
@@ -22479,17 +20992,12 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22479
20992
  exports2.StringSchemaSchema = StringSchemaSchema;
22480
20993
  exports2.SubscribeRequestParamsSchema = SubscribeRequestParamsSchema;
22481
20994
  exports2.SubscribeRequestSchema = SubscribeRequestSchema;
22482
- exports2.TaskCreationParamsSchema = TaskCreationParamsSchema;
22483
- exports2.TaskSchema = TaskSchema;
22484
- exports2.TaskStatusNotificationParamsSchema = TaskStatusNotificationParamsSchema;
22485
- exports2.TaskStatusNotificationSchema = TaskStatusNotificationSchema;
22486
20995
  exports2.TextContentSchema = TextContentSchema;
22487
20996
  exports2.TextResourceContentsSchema = TextResourceContentsSchema;
22488
20997
  exports2.TitledMultiSelectEnumSchemaSchema = TitledMultiSelectEnumSchemaSchema;
22489
20998
  exports2.TitledSingleSelectEnumSchemaSchema = TitledSingleSelectEnumSchemaSchema;
22490
20999
  exports2.ToolAnnotationsSchema = ToolAnnotationsSchema;
22491
21000
  exports2.ToolChoiceSchema = ToolChoiceSchema;
22492
- exports2.ToolExecutionSchema = ToolExecutionSchema;
22493
21001
  exports2.ToolListChangedNotificationSchema = ToolListChangedNotificationSchema;
22494
21002
  exports2.ToolResultContentSchema = ToolResultContentSchema;
22495
21003
  exports2.ToolSchema = ToolSchema;
@@ -22513,7 +21021,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22513
21021
  exports2.exchangeAuthorization = exchangeAuthorization;
22514
21022
  exports2.extractResourceMetadataUrl = extractResourceMetadataUrl;
22515
21023
  exports2.extractWWWAuthenticateParams = extractWWWAuthenticateParams;
22516
- exports2.fetchToken = fetchToken;
22517
21024
  exports2.getCompleter = getCompleter;
22518
21025
  exports2.getDisplayName = getDisplayName;
22519
21026
  exports2.getSupportedElicitationModes = getSupportedElicitationModes;
@@ -22528,7 +21035,6 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22528
21035
  exports2.mergeCapabilities = mergeCapabilities;
22529
21036
  exports2.normalizeHeaders = normalizeHeaders;
22530
21037
  exports2.parseErrorResponse = parseErrorResponse;
22531
- exports2.prepareAuthorizationCodeRequest = prepareAuthorizationCodeRequest;
22532
21038
  exports2.refreshAuthorization = refreshAuthorization;
22533
21039
  exports2.registerClient = registerClient;
22534
21040
  exports2.selectClientAuthMethod = selectClientAuthMethod;