@google-cloud/storage-mcp 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bundle.js CHANGED
@@ -4725,6 +4725,7 @@ var require_pattern = __commonJS({
4725
4725
  "use strict";
4726
4726
  Object.defineProperty(exports, "__esModule", { value: true });
4727
4727
  var code_1 = require_code2();
4728
+ var util_1 = require_util();
4728
4729
  var codegen_1 = require_codegen();
4729
4730
  var error2 = {
4730
4731
  message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`,
@@ -4737,10 +4738,18 @@ var require_pattern = __commonJS({
4737
4738
  $data: true,
4738
4739
  error: error2,
4739
4740
  code(cxt) {
4740
- const { data, $data, schema, schemaCode, it } = cxt;
4741
+ const { gen, data, $data, schema, schemaCode, it } = cxt;
4741
4742
  const u = it.opts.unicodeRegExp ? "u" : "";
4742
- const regExp = $data ? (0, codegen_1._)`(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema);
4743
- cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`);
4743
+ if ($data) {
4744
+ const { regExp } = it.opts.code;
4745
+ const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp);
4746
+ const valid = gen.let("valid");
4747
+ gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false));
4748
+ cxt.fail$data((0, codegen_1._)`!${valid}`);
4749
+ } else {
4750
+ const regExp = (0, code_1.usePattern)(cxt, schema);
4751
+ cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`);
4752
+ }
4744
4753
  }
4745
4754
  };
4746
4755
  exports.default = def;
@@ -10614,6 +10623,7 @@ var require_pattern2 = __commonJS({
10614
10623
  "use strict";
10615
10624
  Object.defineProperty(exports, "__esModule", { value: true });
10616
10625
  var code_1 = require_code4();
10626
+ var util_1 = require_util2();
10617
10627
  var codegen_1 = require_codegen2();
10618
10628
  var error2 = {
10619
10629
  message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`,
@@ -10626,10 +10636,18 @@ var require_pattern2 = __commonJS({
10626
10636
  $data: true,
10627
10637
  error: error2,
10628
10638
  code(cxt) {
10629
- const { data, $data, schema, schemaCode, it } = cxt;
10639
+ const { gen, data, $data, schema, schemaCode, it } = cxt;
10630
10640
  const u = it.opts.unicodeRegExp ? "u" : "";
10631
- const regExp = $data ? (0, codegen_1._)`(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema);
10632
- cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`);
10641
+ if ($data) {
10642
+ const { regExp } = it.opts.code;
10643
+ const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp);
10644
+ const valid = gen.let("valid");
10645
+ gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false));
10646
+ cxt.fail$data((0, codegen_1._)`!${valid}`);
10647
+ } else {
10648
+ const regExp = (0, code_1.usePattern)(cxt, schema);
10649
+ cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`);
10650
+ }
10633
10651
  }
10634
10652
  };
10635
10653
  exports.default = def;
@@ -12462,12 +12480,12 @@ var require_dist = __commonJS({
12462
12480
  throw new Error(`Unknown format "${name}"`);
12463
12481
  return f;
12464
12482
  };
12465
- function addFormats(ajv, list, fs3, exportName) {
12483
+ function addFormats(ajv, list, fs4, exportName) {
12466
12484
  var _a2;
12467
12485
  var _b2;
12468
12486
  (_a2 = (_b2 = ajv.opts.code).formats) !== null && _a2 !== void 0 ? _a2 : _b2.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
12469
12487
  for (const f of list)
12470
- ajv.addFormat(f, fs3[f]);
12488
+ ajv.addFormat(f, fs4[f]);
12471
12489
  }
12472
12490
  module.exports = exports = formatsPlugin;
12473
12491
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -20520,13 +20538,12 @@ async function safeParseAsync2(schema, data) {
20520
20538
  return result;
20521
20539
  }
20522
20540
  function getObjectShape(schema) {
20523
- var _a2, _b2;
20524
20541
  if (!schema)
20525
20542
  return void 0;
20526
20543
  let rawShape;
20527
20544
  if (isZ4Schema(schema)) {
20528
20545
  const v4Schema = schema;
20529
- rawShape = (_b2 = (_a2 = v4Schema._zod) === null || _a2 === void 0 ? void 0 : _a2.def) === null || _b2 === void 0 ? void 0 : _b2.shape;
20546
+ rawShape = v4Schema._zod?.def?.shape;
20530
20547
  } else {
20531
20548
  const v3Schema = schema;
20532
20549
  rawShape = v3Schema.shape;
@@ -20536,14 +20553,13 @@ function getObjectShape(schema) {
20536
20553
  if (typeof rawShape === "function") {
20537
20554
  try {
20538
20555
  return rawShape();
20539
- } catch (_c2) {
20556
+ } catch {
20540
20557
  return void 0;
20541
20558
  }
20542
20559
  }
20543
20560
  return rawShape;
20544
20561
  }
20545
20562
  function normalizeObjectSchema(schema) {
20546
- var _a2;
20547
20563
  if (!schema)
20548
20564
  return void 0;
20549
20565
  if (typeof schema === "object") {
@@ -20558,7 +20574,7 @@ function normalizeObjectSchema(schema) {
20558
20574
  }
20559
20575
  if (isZ4Schema(schema)) {
20560
20576
  const v4Schema = schema;
20561
- const def = (_a2 = v4Schema._zod) === null || _a2 === void 0 ? void 0 : _a2.def;
20577
+ const def = v4Schema._zod?.def;
20562
20578
  if (def && (def.type === "object" || def.shape !== void 0)) {
20563
20579
  return schema;
20564
20580
  }
@@ -20583,38 +20599,30 @@ function getParseErrorMessage(error2) {
20583
20599
  }
20584
20600
  try {
20585
20601
  return JSON.stringify(error2);
20586
- } catch (_a2) {
20602
+ } catch {
20587
20603
  return String(error2);
20588
20604
  }
20589
20605
  }
20590
20606
  return String(error2);
20591
20607
  }
20592
20608
  function getSchemaDescription(schema) {
20593
- var _a2, _b2, _c2, _d;
20594
- if (isZ4Schema(schema)) {
20595
- const v4Schema = schema;
20596
- return (_b2 = (_a2 = v4Schema._zod) === null || _a2 === void 0 ? void 0 : _a2.def) === null || _b2 === void 0 ? void 0 : _b2.description;
20597
- }
20598
- const v3Schema = schema;
20599
- return (_c2 = schema.description) !== null && _c2 !== void 0 ? _c2 : (_d = v3Schema._def) === null || _d === void 0 ? void 0 : _d.description;
20609
+ return schema.description;
20600
20610
  }
20601
20611
  function isSchemaOptional(schema) {
20602
- var _a2, _b2, _c2;
20603
20612
  if (isZ4Schema(schema)) {
20604
20613
  const v4Schema = schema;
20605
- return ((_b2 = (_a2 = v4Schema._zod) === null || _a2 === void 0 ? void 0 : _a2.def) === null || _b2 === void 0 ? void 0 : _b2.type) === "optional";
20614
+ return v4Schema._zod?.def?.type === "optional";
20606
20615
  }
20607
20616
  const v3Schema = schema;
20608
20617
  if (typeof schema.isOptional === "function") {
20609
20618
  return schema.isOptional();
20610
20619
  }
20611
- return ((_c2 = v3Schema._def) === null || _c2 === void 0 ? void 0 : _c2.typeName) === "ZodOptional";
20620
+ return v3Schema._def?.typeName === "ZodOptional";
20612
20621
  }
20613
20622
  function getLiteralValue(schema) {
20614
- var _a2;
20615
20623
  if (isZ4Schema(schema)) {
20616
20624
  const v4Schema = schema;
20617
- const def2 = (_a2 = v4Schema._zod) === null || _a2 === void 0 ? void 0 : _a2.def;
20625
+ const def2 = v4Schema._zod?.def;
20618
20626
  if (def2) {
20619
20627
  if (def2.value !== void 0)
20620
20628
  return def2.value;
@@ -21352,7 +21360,10 @@ var TaskCreationParamsSchema = looseObject({
21352
21360
  */
21353
21361
  pollInterval: number2().optional()
21354
21362
  });
21355
- var RelatedTaskMetadataSchema = looseObject({
21363
+ var TaskMetadataSchema = object2({
21364
+ ttl: number2().optional()
21365
+ });
21366
+ var RelatedTaskMetadataSchema = object2({
21356
21367
  taskId: string2()
21357
21368
  });
21358
21369
  var RequestMetaSchema = looseObject({
@@ -21365,48 +21376,45 @@ var RequestMetaSchema = looseObject({
21365
21376
  */
21366
21377
  [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
21367
21378
  });
21368
- var BaseRequestParamsSchema = looseObject({
21369
- /**
21370
- * If specified, the caller is requesting that the receiver create a task to represent the request.
21371
- * Task creation parameters are now at the top level instead of in _meta.
21372
- */
21373
- task: TaskCreationParamsSchema.optional(),
21379
+ var BaseRequestParamsSchema = object2({
21374
21380
  /**
21375
21381
  * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.
21376
21382
  */
21377
21383
  _meta: RequestMetaSchema.optional()
21378
21384
  });
21385
+ var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({
21386
+ /**
21387
+ * If specified, the caller is requesting task-augmented execution for this request.
21388
+ * The request will return a CreateTaskResult immediately, and the actual result can be
21389
+ * retrieved later via tasks/result.
21390
+ *
21391
+ * Task augmentation is subject to capability negotiation - receivers MUST declare support
21392
+ * for task augmentation of specific request types in their capabilities.
21393
+ */
21394
+ task: TaskMetadataSchema.optional()
21395
+ });
21396
+ var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;
21379
21397
  var RequestSchema = object2({
21380
21398
  method: string2(),
21381
- params: BaseRequestParamsSchema.optional()
21399
+ params: BaseRequestParamsSchema.loose().optional()
21382
21400
  });
21383
- var NotificationsParamsSchema = looseObject({
21401
+ var NotificationsParamsSchema = object2({
21384
21402
  /**
21385
21403
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
21386
21404
  * for notes on _meta usage.
21387
21405
  */
21388
- _meta: object2({
21389
- /**
21390
- * If specified, this notification is related to the provided task.
21391
- */
21392
- [RELATED_TASK_META_KEY]: optional(RelatedTaskMetadataSchema)
21393
- }).passthrough().optional()
21406
+ _meta: RequestMetaSchema.optional()
21394
21407
  });
21395
21408
  var NotificationSchema = object2({
21396
21409
  method: string2(),
21397
- params: NotificationsParamsSchema.optional()
21410
+ params: NotificationsParamsSchema.loose().optional()
21398
21411
  });
21399
21412
  var ResultSchema = looseObject({
21400
21413
  /**
21401
21414
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
21402
21415
  * for notes on _meta usage.
21403
21416
  */
21404
- _meta: looseObject({
21405
- /**
21406
- * If specified, this result is related to the provided task.
21407
- */
21408
- [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
21409
- }).optional()
21417
+ _meta: RequestMetaSchema.optional()
21410
21418
  });
21411
21419
  var RequestIdSchema = union([string2(), number2().int()]);
21412
21420
  var JSONRPCRequestSchema = object2({
@@ -21420,12 +21428,12 @@ var JSONRPCNotificationSchema = object2({
21420
21428
  ...NotificationSchema.shape
21421
21429
  }).strict();
21422
21430
  var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;
21423
- var JSONRPCResponseSchema = object2({
21431
+ var JSONRPCResultResponseSchema = object2({
21424
21432
  jsonrpc: literal(JSONRPC_VERSION),
21425
21433
  id: RequestIdSchema,
21426
21434
  result: ResultSchema
21427
21435
  }).strict();
21428
- var isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success;
21436
+ var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;
21429
21437
  var ErrorCode;
21430
21438
  (function(ErrorCode2) {
21431
21439
  ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed";
@@ -21437,9 +21445,9 @@ var ErrorCode;
21437
21445
  ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError";
21438
21446
  ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
21439
21447
  })(ErrorCode || (ErrorCode = {}));
21440
- var JSONRPCErrorSchema = object2({
21448
+ var JSONRPCErrorResponseSchema = object2({
21441
21449
  jsonrpc: literal(JSONRPC_VERSION),
21442
- id: RequestIdSchema,
21450
+ id: RequestIdSchema.optional(),
21443
21451
  error: object2({
21444
21452
  /**
21445
21453
  * The error type that occurred.
@@ -21452,11 +21460,17 @@ var JSONRPCErrorSchema = object2({
21452
21460
  /**
21453
21461
  * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
21454
21462
  */
21455
- data: optional(unknown())
21463
+ data: unknown().optional()
21456
21464
  })
21457
21465
  }).strict();
21458
- var isJSONRPCError = (value) => JSONRPCErrorSchema.safeParse(value).success;
21459
- var JSONRPCMessageSchema = union([JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResponseSchema, JSONRPCErrorSchema]);
21466
+ var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;
21467
+ var JSONRPCMessageSchema = union([
21468
+ JSONRPCRequestSchema,
21469
+ JSONRPCNotificationSchema,
21470
+ JSONRPCResultResponseSchema,
21471
+ JSONRPCErrorResponseSchema
21472
+ ]);
21473
+ var JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
21460
21474
  var EmptyResultSchema = ResultSchema.strict();
21461
21475
  var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
21462
21476
  /**
@@ -21464,7 +21478,7 @@ var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
21464
21478
  *
21465
21479
  * This MUST correspond to the ID of a request previously issued in the same direction.
21466
21480
  */
21467
- requestId: RequestIdSchema,
21481
+ requestId: RequestIdSchema.optional(),
21468
21482
  /**
21469
21483
  * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
21470
21484
  */
@@ -21489,7 +21503,15 @@ var IconSchema = object2({
21489
21503
  *
21490
21504
  * If not provided, the client should assume that the icon can be used at any size.
21491
21505
  */
21492
- sizes: array(string2()).optional()
21506
+ sizes: array(string2()).optional(),
21507
+ /**
21508
+ * Optional specifier for the theme this icon is designed for. `light` indicates
21509
+ * the icon is designed to be used with a light background, and `dark` indicates
21510
+ * the icon is designed to be used with a dark background.
21511
+ *
21512
+ * If not provided, the client should assume the icon can be used with any theme.
21513
+ */
21514
+ theme: _enum(["light", "dark"]).optional()
21493
21515
  });
21494
21516
  var IconsSchema = object2({
21495
21517
  /**
@@ -21525,7 +21547,15 @@ var ImplementationSchema = BaseMetadataSchema.extend({
21525
21547
  /**
21526
21548
  * An optional URL of the website for this implementation.
21527
21549
  */
21528
- websiteUrl: string2().optional()
21550
+ websiteUrl: string2().optional(),
21551
+ /**
21552
+ * An optional human-readable description of what this implementation does.
21553
+ *
21554
+ * This can be used by clients or servers to provide context about their purpose
21555
+ * and capabilities. For example, a server might describe the types of resources
21556
+ * or tools it provides, while a client might describe its intended use case.
21557
+ */
21558
+ description: string2().optional()
21529
21559
  });
21530
21560
  var FormElicitationCapabilitySchema = intersection(object2({
21531
21561
  applyDefaults: boolean2().optional()
@@ -21541,54 +21571,54 @@ var ElicitationCapabilitySchema = preprocess((value) => {
21541
21571
  form: FormElicitationCapabilitySchema.optional(),
21542
21572
  url: AssertObjectSchema.optional()
21543
21573
  }), record(string2(), unknown()).optional()));
21544
- var ClientTasksCapabilitySchema = object2({
21574
+ var ClientTasksCapabilitySchema = looseObject({
21545
21575
  /**
21546
21576
  * Present if the client supports listing tasks.
21547
21577
  */
21548
- list: optional(object2({}).passthrough()),
21578
+ list: AssertObjectSchema.optional(),
21549
21579
  /**
21550
21580
  * Present if the client supports cancelling tasks.
21551
21581
  */
21552
- cancel: optional(object2({}).passthrough()),
21582
+ cancel: AssertObjectSchema.optional(),
21553
21583
  /**
21554
21584
  * Capabilities for task creation on specific request types.
21555
21585
  */
21556
- requests: optional(object2({
21586
+ requests: looseObject({
21557
21587
  /**
21558
21588
  * Task support for sampling requests.
21559
21589
  */
21560
- sampling: optional(object2({
21561
- createMessage: optional(object2({}).passthrough())
21562
- }).passthrough()),
21590
+ sampling: looseObject({
21591
+ createMessage: AssertObjectSchema.optional()
21592
+ }).optional(),
21563
21593
  /**
21564
21594
  * Task support for elicitation requests.
21565
21595
  */
21566
- elicitation: optional(object2({
21567
- create: optional(object2({}).passthrough())
21568
- }).passthrough())
21569
- }).passthrough())
21570
- }).passthrough();
21571
- var ServerTasksCapabilitySchema = object2({
21596
+ elicitation: looseObject({
21597
+ create: AssertObjectSchema.optional()
21598
+ }).optional()
21599
+ }).optional()
21600
+ });
21601
+ var ServerTasksCapabilitySchema = looseObject({
21572
21602
  /**
21573
21603
  * Present if the server supports listing tasks.
21574
21604
  */
21575
- list: optional(object2({}).passthrough()),
21605
+ list: AssertObjectSchema.optional(),
21576
21606
  /**
21577
21607
  * Present if the server supports cancelling tasks.
21578
21608
  */
21579
- cancel: optional(object2({}).passthrough()),
21609
+ cancel: AssertObjectSchema.optional(),
21580
21610
  /**
21581
21611
  * Capabilities for task creation on specific request types.
21582
21612
  */
21583
- requests: optional(object2({
21613
+ requests: looseObject({
21584
21614
  /**
21585
21615
  * Task support for tool requests.
21586
21616
  */
21587
- tools: optional(object2({
21588
- call: optional(object2({}).passthrough())
21589
- }).passthrough())
21590
- }).passthrough())
21591
- }).passthrough();
21617
+ tools: looseObject({
21618
+ call: AssertObjectSchema.optional()
21619
+ }).optional()
21620
+ }).optional()
21621
+ });
21592
21622
  var ClientCapabilitiesSchema = object2({
21593
21623
  /**
21594
21624
  * Experimental, non-standard capabilities that the client supports.
@@ -21624,7 +21654,7 @@ var ClientCapabilitiesSchema = object2({
21624
21654
  /**
21625
21655
  * Present if the client supports task creation.
21626
21656
  */
21627
- tasks: optional(ClientTasksCapabilitySchema)
21657
+ tasks: ClientTasksCapabilitySchema.optional()
21628
21658
  });
21629
21659
  var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
21630
21660
  /**
@@ -21654,12 +21684,12 @@ var ServerCapabilitiesSchema = object2({
21654
21684
  /**
21655
21685
  * Present if the server offers any prompt templates.
21656
21686
  */
21657
- prompts: optional(object2({
21687
+ prompts: object2({
21658
21688
  /**
21659
21689
  * Whether this server supports issuing notifications for changes to the prompt list.
21660
21690
  */
21661
- listChanged: optional(boolean2())
21662
- })),
21691
+ listChanged: boolean2().optional()
21692
+ }).optional(),
21663
21693
  /**
21664
21694
  * Present if the server offers any resources to read.
21665
21695
  */
@@ -21685,8 +21715,8 @@ var ServerCapabilitiesSchema = object2({
21685
21715
  /**
21686
21716
  * Present if the server supports task creation.
21687
21717
  */
21688
- tasks: optional(ServerTasksCapabilitySchema)
21689
- }).passthrough();
21718
+ tasks: ServerTasksCapabilitySchema.optional()
21719
+ });
21690
21720
  var InitializeResultSchema = ResultSchema.extend({
21691
21721
  /**
21692
21722
  * 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.
@@ -21702,10 +21732,12 @@ var InitializeResultSchema = ResultSchema.extend({
21702
21732
  instructions: string2().optional()
21703
21733
  });
21704
21734
  var InitializedNotificationSchema = NotificationSchema.extend({
21705
- method: literal("notifications/initialized")
21735
+ method: literal("notifications/initialized"),
21736
+ params: NotificationsParamsSchema.optional()
21706
21737
  });
21707
21738
  var PingRequestSchema = RequestSchema.extend({
21708
- method: literal("ping")
21739
+ method: literal("ping"),
21740
+ params: BaseRequestParamsSchema.optional()
21709
21741
  });
21710
21742
  var ProgressSchema = object2({
21711
21743
  /**
@@ -21748,11 +21780,12 @@ var PaginatedResultSchema = ResultSchema.extend({
21748
21780
  * An opaque token representing the pagination position after the last returned result.
21749
21781
  * If present, there may be more results available.
21750
21782
  */
21751
- nextCursor: optional(CursorSchema)
21783
+ nextCursor: CursorSchema.optional()
21752
21784
  });
21785
+ var TaskStatusSchema = _enum(["working", "input_required", "completed", "failed", "cancelled"]);
21753
21786
  var TaskSchema = object2({
21754
21787
  taskId: string2(),
21755
- status: _enum(["working", "input_required", "completed", "failed", "cancelled"]),
21788
+ status: TaskStatusSchema,
21756
21789
  /**
21757
21790
  * Time in milliseconds to keep task results available after completion.
21758
21791
  * If null, the task has unlimited lifetime until manually cleaned up.
@@ -21793,6 +21826,7 @@ var GetTaskPayloadRequestSchema = RequestSchema.extend({
21793
21826
  taskId: string2()
21794
21827
  })
21795
21828
  });
21829
+ var GetTaskPayloadResultSchema = ResultSchema.loose();
21796
21830
  var ListTasksRequestSchema = PaginatedRequestSchema.extend({
21797
21831
  method: literal("tasks/list")
21798
21832
  });
@@ -21831,7 +21865,7 @@ var Base64Schema = string2().refine((val) => {
21831
21865
  try {
21832
21866
  atob(val);
21833
21867
  return true;
21834
- } catch (_a2) {
21868
+ } catch {
21835
21869
  return false;
21836
21870
  }
21837
21871
  }, { message: "Invalid Base64 string" });
@@ -21841,11 +21875,12 @@ var BlobResourceContentsSchema = ResourceContentsSchema.extend({
21841
21875
  */
21842
21876
  blob: Base64Schema
21843
21877
  });
21878
+ var RoleSchema = _enum(["user", "assistant"]);
21844
21879
  var AnnotationsSchema = object2({
21845
21880
  /**
21846
21881
  * Intended audience(s) for the resource.
21847
21882
  */
21848
- audience: array(_enum(["user", "assistant"])).optional(),
21883
+ audience: array(RoleSchema).optional(),
21849
21884
  /**
21850
21885
  * Importance hint for the resource, from 0 (least) to 1 (most).
21851
21886
  */
@@ -21938,7 +21973,8 @@ var ReadResourceResultSchema = ResultSchema.extend({
21938
21973
  contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema]))
21939
21974
  });
21940
21975
  var ResourceListChangedNotificationSchema = NotificationSchema.extend({
21941
- method: literal("notifications/resources/list_changed")
21976
+ method: literal("notifications/resources/list_changed"),
21977
+ params: NotificationsParamsSchema.optional()
21942
21978
  });
21943
21979
  var SubscribeRequestParamsSchema = ResourceRequestParamsSchema;
21944
21980
  var SubscribeRequestSchema = RequestSchema.extend({
@@ -22083,13 +22119,13 @@ var ToolUseContentSchema = object2({
22083
22119
  * Arguments to pass to the tool.
22084
22120
  * Must conform to the tool's inputSchema.
22085
22121
  */
22086
- input: object2({}).passthrough(),
22122
+ input: record(string2(), unknown()),
22087
22123
  /**
22088
22124
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
22089
22125
  * for notes on _meta usage.
22090
22126
  */
22091
- _meta: optional(object2({}).passthrough())
22092
- }).passthrough();
22127
+ _meta: record(string2(), unknown()).optional()
22128
+ });
22093
22129
  var EmbeddedResourceSchema = object2({
22094
22130
  type: literal("resource"),
22095
22131
  resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
@@ -22114,18 +22150,19 @@ var ContentBlockSchema = union([
22114
22150
  EmbeddedResourceSchema
22115
22151
  ]);
22116
22152
  var PromptMessageSchema = object2({
22117
- role: _enum(["user", "assistant"]),
22153
+ role: RoleSchema,
22118
22154
  content: ContentBlockSchema
22119
22155
  });
22120
22156
  var GetPromptResultSchema = ResultSchema.extend({
22121
22157
  /**
22122
22158
  * An optional description for the prompt.
22123
22159
  */
22124
- description: optional(string2()),
22160
+ description: string2().optional(),
22125
22161
  messages: array(PromptMessageSchema)
22126
22162
  });
22127
22163
  var PromptListChangedNotificationSchema = NotificationSchema.extend({
22128
- method: literal("notifications/prompts/list_changed")
22164
+ method: literal("notifications/prompts/list_changed"),
22165
+ params: NotificationsParamsSchema.optional()
22129
22166
  });
22130
22167
  var ToolAnnotationsSchema = object2({
22131
22168
  /**
@@ -22206,11 +22243,11 @@ var ToolSchema = object2({
22206
22243
  /**
22207
22244
  * Optional additional tool information.
22208
22245
  */
22209
- annotations: optional(ToolAnnotationsSchema),
22246
+ annotations: ToolAnnotationsSchema.optional(),
22210
22247
  /**
22211
22248
  * Execution-related properties for this tool.
22212
22249
  */
22213
- execution: optional(ToolExecutionSchema),
22250
+ execution: ToolExecutionSchema.optional(),
22214
22251
  /**
22215
22252
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
22216
22253
  * for notes on _meta usage.
@@ -22251,12 +22288,12 @@ var CallToolResultSchema = ResultSchema.extend({
22251
22288
  * server does not support tool calls, or any other exceptional conditions,
22252
22289
  * should be reported as an MCP error response.
22253
22290
  */
22254
- isError: optional(boolean2())
22291
+ isError: boolean2().optional()
22255
22292
  });
22256
22293
  var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({
22257
22294
  toolResult: unknown()
22258
22295
  }));
22259
- var CallToolRequestParamsSchema = BaseRequestParamsSchema.extend({
22296
+ var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
22260
22297
  /**
22261
22298
  * The name of the tool to call.
22262
22299
  */
@@ -22264,14 +22301,35 @@ var CallToolRequestParamsSchema = BaseRequestParamsSchema.extend({
22264
22301
  /**
22265
22302
  * Arguments to pass to the tool.
22266
22303
  */
22267
- arguments: optional(record(string2(), unknown()))
22304
+ arguments: record(string2(), unknown()).optional()
22268
22305
  });
22269
22306
  var CallToolRequestSchema = RequestSchema.extend({
22270
22307
  method: literal("tools/call"),
22271
22308
  params: CallToolRequestParamsSchema
22272
22309
  });
22273
22310
  var ToolListChangedNotificationSchema = NotificationSchema.extend({
22274
- method: literal("notifications/tools/list_changed")
22311
+ method: literal("notifications/tools/list_changed"),
22312
+ params: NotificationsParamsSchema.optional()
22313
+ });
22314
+ var ListChangedOptionsBaseSchema = object2({
22315
+ /**
22316
+ * If true, the list will be refreshed automatically when a list changed notification is received.
22317
+ * The callback will be called with the updated list.
22318
+ *
22319
+ * If false, the callback will be called with null items, allowing manual refresh.
22320
+ *
22321
+ * @default true
22322
+ */
22323
+ autoRefresh: boolean2().default(true),
22324
+ /**
22325
+ * Debounce time in milliseconds for list changed notification processing.
22326
+ *
22327
+ * Multiple notifications received within this timeframe will only trigger one refresh.
22328
+ * Set to 0 to disable debouncing.
22329
+ *
22330
+ * @default 300
22331
+ */
22332
+ debounceMs: number2().int().nonnegative().default(300)
22275
22333
  });
22276
22334
  var LoggingLevelSchema = _enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
22277
22335
  var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({
@@ -22312,19 +22370,19 @@ var ModelPreferencesSchema = object2({
22312
22370
  /**
22313
22371
  * Optional hints to use for model selection.
22314
22372
  */
22315
- hints: optional(array(ModelHintSchema)),
22373
+ hints: array(ModelHintSchema).optional(),
22316
22374
  /**
22317
22375
  * How much to prioritize cost when selecting a model.
22318
22376
  */
22319
- costPriority: optional(number2().min(0).max(1)),
22377
+ costPriority: number2().min(0).max(1).optional(),
22320
22378
  /**
22321
22379
  * How much to prioritize sampling speed (latency) when selecting a model.
22322
22380
  */
22323
- speedPriority: optional(number2().min(0).max(1)),
22381
+ speedPriority: number2().min(0).max(1).optional(),
22324
22382
  /**
22325
22383
  * How much to prioritize intelligence and capabilities when selecting a model.
22326
22384
  */
22327
- intelligencePriority: optional(number2().min(0).max(1))
22385
+ intelligencePriority: number2().min(0).max(1).optional()
22328
22386
  });
22329
22387
  var ToolChoiceSchema = object2({
22330
22388
  /**
@@ -22333,20 +22391,20 @@ var ToolChoiceSchema = object2({
22333
22391
  * - "required": Model MUST use at least one tool before completing
22334
22392
  * - "none": Model MUST NOT use any tools
22335
22393
  */
22336
- mode: optional(_enum(["auto", "required", "none"]))
22394
+ mode: _enum(["auto", "required", "none"]).optional()
22337
22395
  });
22338
22396
  var ToolResultContentSchema = object2({
22339
22397
  type: literal("tool_result"),
22340
22398
  toolUseId: string2().describe("The unique identifier for the corresponding tool call."),
22341
22399
  content: array(ContentBlockSchema).default([]),
22342
- structuredContent: object2({}).passthrough().optional(),
22343
- isError: optional(boolean2()),
22400
+ structuredContent: object2({}).loose().optional(),
22401
+ isError: boolean2().optional(),
22344
22402
  /**
22345
22403
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
22346
22404
  * for notes on _meta usage.
22347
22405
  */
22348
- _meta: optional(object2({}).passthrough())
22349
- }).passthrough();
22406
+ _meta: record(string2(), unknown()).optional()
22407
+ });
22350
22408
  var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);
22351
22409
  var SamplingMessageContentBlockSchema = discriminatedUnion("type", [
22352
22410
  TextContentSchema,
@@ -22356,15 +22414,15 @@ var SamplingMessageContentBlockSchema = discriminatedUnion("type", [
22356
22414
  ToolResultContentSchema
22357
22415
  ]);
22358
22416
  var SamplingMessageSchema = object2({
22359
- role: _enum(["user", "assistant"]),
22417
+ role: RoleSchema,
22360
22418
  content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),
22361
22419
  /**
22362
22420
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
22363
22421
  * for notes on _meta usage.
22364
22422
  */
22365
- _meta: optional(object2({}).passthrough())
22366
- }).passthrough();
22367
- var CreateMessageRequestParamsSchema = BaseRequestParamsSchema.extend({
22423
+ _meta: record(string2(), unknown()).optional()
22424
+ });
22425
+ var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
22368
22426
  messages: array(SamplingMessageSchema),
22369
22427
  /**
22370
22428
  * The server's preferences for which model to select. The client MAY modify or omit this request.
@@ -22398,13 +22456,13 @@ var CreateMessageRequestParamsSchema = BaseRequestParamsSchema.extend({
22398
22456
  * Tools that the model may use during generation.
22399
22457
  * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
22400
22458
  */
22401
- tools: optional(array(ToolSchema)),
22459
+ tools: array(ToolSchema).optional(),
22402
22460
  /**
22403
22461
  * Controls how the model uses tools.
22404
22462
  * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
22405
22463
  * Default is `{ mode: "auto" }`.
22406
22464
  */
22407
- toolChoice: optional(ToolChoiceSchema)
22465
+ toolChoice: ToolChoiceSchema.optional()
22408
22466
  });
22409
22467
  var CreateMessageRequestSchema = RequestSchema.extend({
22410
22468
  method: literal("sampling/createMessage"),
@@ -22426,7 +22484,7 @@ var CreateMessageResultSchema = ResultSchema.extend({
22426
22484
  * This field is an open string to allow for provider-specific stop reasons.
22427
22485
  */
22428
22486
  stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens"]).or(string2())),
22429
- role: _enum(["user", "assistant"]),
22487
+ role: RoleSchema,
22430
22488
  /**
22431
22489
  * Response content. Single content block (text, image, or audio).
22432
22490
  */
@@ -22449,7 +22507,7 @@ var CreateMessageResultWithToolsSchema = ResultSchema.extend({
22449
22507
  * This field is an open string to allow for provider-specific stop reasons.
22450
22508
  */
22451
22509
  stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())),
22452
- role: _enum(["user", "assistant"]),
22510
+ role: RoleSchema,
22453
22511
  /**
22454
22512
  * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse".
22455
22513
  */
@@ -22533,7 +22591,7 @@ var TitledMultiSelectEnumSchemaSchema = object2({
22533
22591
  var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
22534
22592
  var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
22535
22593
  var PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
22536
- var ElicitRequestFormParamsSchema = BaseRequestParamsSchema.extend({
22594
+ var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
22537
22595
  /**
22538
22596
  * The elicitation mode.
22539
22597
  *
@@ -22554,7 +22612,7 @@ var ElicitRequestFormParamsSchema = BaseRequestParamsSchema.extend({
22554
22612
  required: array(string2()).optional()
22555
22613
  })
22556
22614
  });
22557
- var ElicitRequestURLParamsSchema = BaseRequestParamsSchema.extend({
22615
+ var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({
22558
22616
  /**
22559
22617
  * The elicitation mode.
22560
22618
  */
@@ -22688,13 +22746,15 @@ var RootSchema = object2({
22688
22746
  _meta: record(string2(), unknown()).optional()
22689
22747
  });
22690
22748
  var ListRootsRequestSchema = RequestSchema.extend({
22691
- method: literal("roots/list")
22749
+ method: literal("roots/list"),
22750
+ params: BaseRequestParamsSchema.optional()
22692
22751
  });
22693
22752
  var ListRootsResultSchema = ResultSchema.extend({
22694
22753
  roots: array(RootSchema)
22695
22754
  });
22696
22755
  var RootsListChangedNotificationSchema = NotificationSchema.extend({
22697
- method: literal("notifications/roots/list_changed")
22756
+ method: literal("notifications/roots/list_changed"),
22757
+ params: NotificationsParamsSchema.optional()
22698
22758
  });
22699
22759
  var ClientRequestSchema = union([
22700
22760
  PingRequestSchema,
@@ -22712,7 +22772,8 @@ var ClientRequestSchema = union([
22712
22772
  ListToolsRequestSchema,
22713
22773
  GetTaskRequestSchema,
22714
22774
  GetTaskPayloadRequestSchema,
22715
- ListTasksRequestSchema
22775
+ ListTasksRequestSchema,
22776
+ CancelTaskRequestSchema
22716
22777
  ]);
22717
22778
  var ClientNotificationSchema = union([
22718
22779
  CancelledNotificationSchema,
@@ -22738,7 +22799,8 @@ var ServerRequestSchema = union([
22738
22799
  ListRootsRequestSchema,
22739
22800
  GetTaskRequestSchema,
22740
22801
  GetTaskPayloadRequestSchema,
22741
- ListTasksRequestSchema
22802
+ ListTasksRequestSchema,
22803
+ CancelTaskRequestSchema
22742
22804
  ]);
22743
22805
  var ServerNotificationSchema = union([
22744
22806
  CancelledNotificationSchema,
@@ -22793,8 +22855,7 @@ var UrlElicitationRequiredError = class extends McpError {
22793
22855
  });
22794
22856
  }
22795
22857
  get elicitations() {
22796
- var _a2, _b2;
22797
- return (_b2 = (_a2 = this.data) === null || _a2 === void 0 ? void 0 : _a2.elicitations) !== null && _b2 !== void 0 ? _b2 : [];
22858
+ return this.data?.elicitations ?? [];
22798
22859
  }
22799
22860
  };
22800
22861
 
@@ -24098,21 +24159,20 @@ function mapMiniTarget(t) {
24098
24159
  return "draft-7";
24099
24160
  }
24100
24161
  function toJsonSchemaCompat(schema, opts) {
24101
- var _a2, _b2, _c2;
24102
24162
  if (isZ4Schema(schema)) {
24103
24163
  return toJSONSchema(schema, {
24104
- target: mapMiniTarget(opts === null || opts === void 0 ? void 0 : opts.target),
24105
- io: (_a2 = opts === null || opts === void 0 ? void 0 : opts.pipeStrategy) !== null && _a2 !== void 0 ? _a2 : "input"
24164
+ target: mapMiniTarget(opts?.target),
24165
+ io: opts?.pipeStrategy ?? "input"
24106
24166
  });
24107
24167
  }
24108
24168
  return zodToJsonSchema(schema, {
24109
- strictUnions: (_b2 = opts === null || opts === void 0 ? void 0 : opts.strictUnions) !== null && _b2 !== void 0 ? _b2 : true,
24110
- pipeStrategy: (_c2 = opts === null || opts === void 0 ? void 0 : opts.pipeStrategy) !== null && _c2 !== void 0 ? _c2 : "input"
24169
+ strictUnions: opts?.strictUnions ?? true,
24170
+ pipeStrategy: opts?.pipeStrategy ?? "input"
24111
24171
  });
24112
24172
  }
24113
24173
  function getMethodLiteral(schema) {
24114
24174
  const shape = getObjectShape(schema);
24115
- const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method;
24175
+ const methodSchema = shape?.method;
24116
24176
  if (!methodSchema) {
24117
24177
  throw new Error("Schema is missing a method literal");
24118
24178
  }
@@ -24156,8 +24216,8 @@ var Protocol = class {
24156
24216
  // Automatic pong by default.
24157
24217
  (_request) => ({})
24158
24218
  );
24159
- this._taskStore = _options === null || _options === void 0 ? void 0 : _options.taskStore;
24160
- this._taskMessageQueue = _options === null || _options === void 0 ? void 0 : _options.taskMessageQueue;
24219
+ this._taskStore = _options?.taskStore;
24220
+ this._taskMessageQueue = _options?.taskMessageQueue;
24161
24221
  if (this._taskStore) {
24162
24222
  this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {
24163
24223
  const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
@@ -24170,7 +24230,6 @@ var Protocol = class {
24170
24230
  });
24171
24231
  this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
24172
24232
  const handleTaskResult = async () => {
24173
- var _a2;
24174
24233
  const taskId = request.params.taskId;
24175
24234
  if (this._taskMessageQueue) {
24176
24235
  let queuedMessage;
@@ -24194,7 +24253,7 @@ var Protocol = class {
24194
24253
  }
24195
24254
  continue;
24196
24255
  }
24197
- await ((_a2 = this._transport) === null || _a2 === void 0 ? void 0 : _a2.send(queuedMessage.message, { relatedRequestId: extra.requestId }));
24256
+ await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });
24198
24257
  }
24199
24258
  }
24200
24259
  const task = await this._taskStore.getTask(taskId, extra.sessionId);
@@ -24223,9 +24282,8 @@ var Protocol = class {
24223
24282
  return await handleTaskResult();
24224
24283
  });
24225
24284
  this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {
24226
- var _a2;
24227
24285
  try {
24228
- const { tasks, nextCursor } = await this._taskStore.listTasks((_a2 = request.params) === null || _a2 === void 0 ? void 0 : _a2.cursor, extra.sessionId);
24286
+ const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId);
24229
24287
  return {
24230
24288
  tasks,
24231
24289
  nextCursor,
@@ -24264,8 +24322,11 @@ var Protocol = class {
24264
24322
  }
24265
24323
  }
24266
24324
  async _oncancel(notification) {
24325
+ if (!notification.params.requestId) {
24326
+ return;
24327
+ }
24267
24328
  const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
24268
- controller === null || controller === void 0 ? void 0 : controller.abort(notification.params.reason);
24329
+ controller?.abort(notification.params.reason);
24269
24330
  }
24270
24331
  _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
24271
24332
  this._timeoutInfo.set(messageId, {
@@ -24306,22 +24367,24 @@ var Protocol = class {
24306
24367
  * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
24307
24368
  */
24308
24369
  async connect(transport) {
24309
- var _a2, _b2, _c2;
24370
+ if (this._transport) {
24371
+ throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");
24372
+ }
24310
24373
  this._transport = transport;
24311
- const _onclose = (_a2 = this.transport) === null || _a2 === void 0 ? void 0 : _a2.onclose;
24374
+ const _onclose = this.transport?.onclose;
24312
24375
  this._transport.onclose = () => {
24313
- _onclose === null || _onclose === void 0 ? void 0 : _onclose();
24376
+ _onclose?.();
24314
24377
  this._onclose();
24315
24378
  };
24316
- const _onerror = (_b2 = this.transport) === null || _b2 === void 0 ? void 0 : _b2.onerror;
24379
+ const _onerror = this.transport?.onerror;
24317
24380
  this._transport.onerror = (error2) => {
24318
- _onerror === null || _onerror === void 0 ? void 0 : _onerror(error2);
24381
+ _onerror?.(error2);
24319
24382
  this._onerror(error2);
24320
24383
  };
24321
- const _onmessage = (_c2 = this._transport) === null || _c2 === void 0 ? void 0 : _c2.onmessage;
24384
+ const _onmessage = this._transport?.onmessage;
24322
24385
  this._transport.onmessage = (message, extra) => {
24323
- _onmessage === null || _onmessage === void 0 ? void 0 : _onmessage(message, extra);
24324
- if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
24386
+ _onmessage?.(message, extra);
24387
+ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
24325
24388
  this._onresponse(message);
24326
24389
  } else if (isJSONRPCRequest(message)) {
24327
24390
  this._onrequest(message, extra);
@@ -24334,36 +24397,36 @@ var Protocol = class {
24334
24397
  await this._transport.start();
24335
24398
  }
24336
24399
  _onclose() {
24337
- var _a2;
24338
24400
  const responseHandlers = this._responseHandlers;
24339
24401
  this._responseHandlers = /* @__PURE__ */ new Map();
24340
24402
  this._progressHandlers.clear();
24341
24403
  this._taskProgressTokens.clear();
24342
24404
  this._pendingDebouncedNotifications.clear();
24405
+ for (const controller of this._requestHandlerAbortControllers.values()) {
24406
+ controller.abort();
24407
+ }
24408
+ this._requestHandlerAbortControllers.clear();
24343
24409
  const error2 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");
24344
24410
  this._transport = void 0;
24345
- (_a2 = this.onclose) === null || _a2 === void 0 ? void 0 : _a2.call(this);
24411
+ this.onclose?.();
24346
24412
  for (const handler of responseHandlers.values()) {
24347
24413
  handler(error2);
24348
24414
  }
24349
24415
  }
24350
24416
  _onerror(error2) {
24351
- var _a2;
24352
- (_a2 = this.onerror) === null || _a2 === void 0 ? void 0 : _a2.call(this, error2);
24417
+ this.onerror?.(error2);
24353
24418
  }
24354
24419
  _onnotification(notification) {
24355
- var _a2;
24356
- const handler = (_a2 = this._notificationHandlers.get(notification.method)) !== null && _a2 !== void 0 ? _a2 : this.fallbackNotificationHandler;
24420
+ const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;
24357
24421
  if (handler === void 0) {
24358
24422
  return;
24359
24423
  }
24360
24424
  Promise.resolve().then(() => handler(notification)).catch((error2) => this._onerror(new Error(`Uncaught error in notification handler: ${error2}`)));
24361
24425
  }
24362
24426
  _onrequest(request, extra) {
24363
- var _a2, _b2, _c2, _d, _e, _f;
24364
- const handler = (_a2 = this._requestHandlers.get(request.method)) !== null && _a2 !== void 0 ? _a2 : this.fallbackRequestHandler;
24427
+ const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
24365
24428
  const capturedTransport = this._transport;
24366
- const relatedTaskId = (_d = (_c2 = (_b2 = request.params) === null || _b2 === void 0 ? void 0 : _b2._meta) === null || _c2 === void 0 ? void 0 : _c2[RELATED_TASK_META_KEY]) === null || _d === void 0 ? void 0 : _d.taskId;
24429
+ const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
24367
24430
  if (handler === void 0) {
24368
24431
  const errorResponse = {
24369
24432
  jsonrpc: "2.0",
@@ -24378,21 +24441,23 @@ var Protocol = class {
24378
24441
  type: "error",
24379
24442
  message: errorResponse,
24380
24443
  timestamp: Date.now()
24381
- }, capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.sessionId).catch((error2) => this._onerror(new Error(`Failed to enqueue error response: ${error2}`)));
24444
+ }, capturedTransport?.sessionId).catch((error2) => this._onerror(new Error(`Failed to enqueue error response: ${error2}`)));
24382
24445
  } else {
24383
- capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send(errorResponse).catch((error2) => this._onerror(new Error(`Failed to send an error response: ${error2}`)));
24446
+ capturedTransport?.send(errorResponse).catch((error2) => this._onerror(new Error(`Failed to send an error response: ${error2}`)));
24384
24447
  }
24385
24448
  return;
24386
24449
  }
24387
24450
  const abortController = new AbortController();
24388
24451
  this._requestHandlerAbortControllers.set(request.id, abortController);
24389
- const taskCreationParams = (_e = request.params) === null || _e === void 0 ? void 0 : _e.task;
24390
- const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.sessionId) : void 0;
24452
+ const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0;
24453
+ const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : void 0;
24391
24454
  const fullExtra = {
24392
24455
  signal: abortController.signal,
24393
- sessionId: capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.sessionId,
24394
- _meta: (_f = request.params) === null || _f === void 0 ? void 0 : _f._meta,
24456
+ sessionId: capturedTransport?.sessionId,
24457
+ _meta: request.params?._meta,
24395
24458
  sendNotification: async (notification) => {
24459
+ if (abortController.signal.aborted)
24460
+ return;
24396
24461
  const notificationOptions = { relatedRequestId: request.id };
24397
24462
  if (relatedTaskId) {
24398
24463
  notificationOptions.relatedTask = { taskId: relatedTaskId };
@@ -24400,25 +24465,27 @@ var Protocol = class {
24400
24465
  await this.notification(notification, notificationOptions);
24401
24466
  },
24402
24467
  sendRequest: async (r, resultSchema, options) => {
24403
- var _a3, _b3;
24468
+ if (abortController.signal.aborted) {
24469
+ throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
24470
+ }
24404
24471
  const requestOptions = { ...options, relatedRequestId: request.id };
24405
24472
  if (relatedTaskId && !requestOptions.relatedTask) {
24406
24473
  requestOptions.relatedTask = { taskId: relatedTaskId };
24407
24474
  }
24408
- const effectiveTaskId = (_b3 = (_a3 = requestOptions.relatedTask) === null || _a3 === void 0 ? void 0 : _a3.taskId) !== null && _b3 !== void 0 ? _b3 : relatedTaskId;
24475
+ const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;
24409
24476
  if (effectiveTaskId && taskStore) {
24410
24477
  await taskStore.updateTaskStatus(effectiveTaskId, "input_required");
24411
24478
  }
24412
24479
  return await this.request(r, resultSchema, requestOptions);
24413
24480
  },
24414
- authInfo: extra === null || extra === void 0 ? void 0 : extra.authInfo,
24481
+ authInfo: extra?.authInfo,
24415
24482
  requestId: request.id,
24416
- requestInfo: extra === null || extra === void 0 ? void 0 : extra.requestInfo,
24483
+ requestInfo: extra?.requestInfo,
24417
24484
  taskId: relatedTaskId,
24418
24485
  taskStore,
24419
- taskRequestedTtl: taskCreationParams === null || taskCreationParams === void 0 ? void 0 : taskCreationParams.ttl,
24420
- closeSSEStream: extra === null || extra === void 0 ? void 0 : extra.closeSSEStream,
24421
- closeStandaloneSSEStream: extra === null || extra === void 0 ? void 0 : extra.closeStandaloneSSEStream
24486
+ taskRequestedTtl: taskCreationParams?.ttl,
24487
+ closeSSEStream: extra?.closeSSEStream,
24488
+ closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
24422
24489
  };
24423
24490
  Promise.resolve().then(() => {
24424
24491
  if (taskCreationParams) {
@@ -24438,12 +24505,11 @@ var Protocol = class {
24438
24505
  type: "response",
24439
24506
  message: response,
24440
24507
  timestamp: Date.now()
24441
- }, capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.sessionId);
24508
+ }, capturedTransport?.sessionId);
24442
24509
  } else {
24443
- await (capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send(response));
24510
+ await capturedTransport?.send(response);
24444
24511
  }
24445
24512
  }, async (error2) => {
24446
- var _a3;
24447
24513
  if (abortController.signal.aborted) {
24448
24514
  return;
24449
24515
  }
@@ -24452,7 +24518,7 @@ var Protocol = class {
24452
24518
  id: request.id,
24453
24519
  error: {
24454
24520
  code: Number.isSafeInteger(error2["code"]) ? error2["code"] : ErrorCode.InternalError,
24455
- message: (_a3 = error2.message) !== null && _a3 !== void 0 ? _a3 : "Internal error",
24521
+ message: error2.message ?? "Internal error",
24456
24522
  ...error2["data"] !== void 0 && { data: error2["data"] }
24457
24523
  }
24458
24524
  };
@@ -24461,9 +24527,9 @@ var Protocol = class {
24461
24527
  type: "error",
24462
24528
  message: errorResponse,
24463
24529
  timestamp: Date.now()
24464
- }, capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.sessionId);
24530
+ }, capturedTransport?.sessionId);
24465
24531
  } else {
24466
- await (capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send(errorResponse));
24532
+ await capturedTransport?.send(errorResponse);
24467
24533
  }
24468
24534
  }).catch((error2) => this._onerror(new Error(`Failed to send response: ${error2}`))).finally(() => {
24469
24535
  this._requestHandlerAbortControllers.delete(request.id);
@@ -24497,7 +24563,7 @@ var Protocol = class {
24497
24563
  const resolver = this._requestResolvers.get(messageId);
24498
24564
  if (resolver) {
24499
24565
  this._requestResolvers.delete(messageId);
24500
- if (isJSONRPCResponse(response)) {
24566
+ if (isJSONRPCResultResponse(response)) {
24501
24567
  resolver(response);
24502
24568
  } else {
24503
24569
  const error2 = new McpError(response.error.code, response.error.message, response.error.data);
@@ -24513,7 +24579,7 @@ var Protocol = class {
24513
24579
  this._responseHandlers.delete(messageId);
24514
24580
  this._cleanupTimeout(messageId);
24515
24581
  let isTaskResponse = false;
24516
- if (isJSONRPCResponse(response) && response.result && typeof response.result === "object") {
24582
+ if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") {
24517
24583
  const result = response.result;
24518
24584
  if (result.task && typeof result.task === "object") {
24519
24585
  const task = result.task;
@@ -24526,7 +24592,7 @@ var Protocol = class {
24526
24592
  if (!isTaskResponse) {
24527
24593
  this._progressHandlers.delete(messageId);
24528
24594
  }
24529
- if (isJSONRPCResponse(response)) {
24595
+ if (isJSONRPCResultResponse(response)) {
24530
24596
  handler(response);
24531
24597
  } else {
24532
24598
  const error2 = McpError.fromError(response.error.code, response.error.message, response.error.data);
@@ -24540,8 +24606,7 @@ var Protocol = class {
24540
24606
  * Closes the connection.
24541
24607
  */
24542
24608
  async close() {
24543
- var _a2;
24544
- await ((_a2 = this._transport) === null || _a2 === void 0 ? void 0 : _a2.close());
24609
+ await this._transport?.close();
24545
24610
  }
24546
24611
  /**
24547
24612
  * Sends a request and returns an AsyncGenerator that yields response messages.
@@ -24571,8 +24636,7 @@ var Protocol = class {
24571
24636
  * @experimental Use `client.experimental.tasks.requestStream()` to access this method.
24572
24637
  */
24573
24638
  async *requestStream(request, resultSchema, options) {
24574
- var _a2, _b2, _c2, _d;
24575
- const { task } = options !== null && options !== void 0 ? options : {};
24639
+ const { task } = options ?? {};
24576
24640
  if (!task) {
24577
24641
  try {
24578
24642
  const result = await this.request(request, resultSchema, options);
@@ -24619,9 +24683,9 @@ var Protocol = class {
24619
24683
  yield { type: "result", result };
24620
24684
  return;
24621
24685
  }
24622
- const pollInterval = (_c2 = (_a2 = task2.pollInterval) !== null && _a2 !== void 0 ? _a2 : (_b2 = this._options) === null || _b2 === void 0 ? void 0 : _b2.defaultTaskPollInterval) !== null && _c2 !== void 0 ? _c2 : 1e3;
24686
+ const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
24623
24687
  await new Promise((resolve5) => setTimeout(resolve5, pollInterval));
24624
- (_d = options === null || options === void 0 ? void 0 : options.signal) === null || _d === void 0 ? void 0 : _d.throwIfAborted();
24688
+ options?.signal?.throwIfAborted();
24625
24689
  }
24626
24690
  } catch (error2) {
24627
24691
  yield {
@@ -24636,9 +24700,8 @@ var Protocol = class {
24636
24700
  * Do not use this method to emit notifications! Use notification() instead.
24637
24701
  */
24638
24702
  request(request, resultSchema, options) {
24639
- const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options !== null && options !== void 0 ? options : {};
24703
+ const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
24640
24704
  return new Promise((resolve5, reject) => {
24641
- var _a2, _b2, _c2, _d, _e, _f, _g;
24642
24705
  const earlyReject = (error2) => {
24643
24706
  reject(error2);
24644
24707
  };
@@ -24646,7 +24709,7 @@ var Protocol = class {
24646
24709
  earlyReject(new Error("Not connected"));
24647
24710
  return;
24648
24711
  }
24649
- if (((_a2 = this._options) === null || _a2 === void 0 ? void 0 : _a2.enforceStrictCapabilities) === true) {
24712
+ if (this._options?.enforceStrictCapabilities === true) {
24650
24713
  try {
24651
24714
  this.assertCapabilityForMethod(request.method);
24652
24715
  if (task) {
@@ -24657,19 +24720,19 @@ var Protocol = class {
24657
24720
  return;
24658
24721
  }
24659
24722
  }
24660
- (_b2 = options === null || options === void 0 ? void 0 : options.signal) === null || _b2 === void 0 ? void 0 : _b2.throwIfAborted();
24723
+ options?.signal?.throwIfAborted();
24661
24724
  const messageId = this._requestMessageId++;
24662
24725
  const jsonrpcRequest = {
24663
24726
  ...request,
24664
24727
  jsonrpc: "2.0",
24665
24728
  id: messageId
24666
24729
  };
24667
- if (options === null || options === void 0 ? void 0 : options.onprogress) {
24730
+ if (options?.onprogress) {
24668
24731
  this._progressHandlers.set(messageId, options.onprogress);
24669
24732
  jsonrpcRequest.params = {
24670
24733
  ...request.params,
24671
24734
  _meta: {
24672
- ...((_c2 = request.params) === null || _c2 === void 0 ? void 0 : _c2._meta) || {},
24735
+ ...request.params?._meta || {},
24673
24736
  progressToken: messageId
24674
24737
  }
24675
24738
  };
@@ -24684,17 +24747,16 @@ var Protocol = class {
24684
24747
  jsonrpcRequest.params = {
24685
24748
  ...jsonrpcRequest.params,
24686
24749
  _meta: {
24687
- ...((_d = jsonrpcRequest.params) === null || _d === void 0 ? void 0 : _d._meta) || {},
24750
+ ...jsonrpcRequest.params?._meta || {},
24688
24751
  [RELATED_TASK_META_KEY]: relatedTask
24689
24752
  }
24690
24753
  };
24691
24754
  }
24692
24755
  const cancel = (reason) => {
24693
- var _a3;
24694
24756
  this._responseHandlers.delete(messageId);
24695
24757
  this._progressHandlers.delete(messageId);
24696
24758
  this._cleanupTimeout(messageId);
24697
- (_a3 = this._transport) === null || _a3 === void 0 ? void 0 : _a3.send({
24759
+ this._transport?.send({
24698
24760
  jsonrpc: "2.0",
24699
24761
  method: "notifications/cancelled",
24700
24762
  params: {
@@ -24706,8 +24768,7 @@ var Protocol = class {
24706
24768
  reject(error2);
24707
24769
  };
24708
24770
  this._responseHandlers.set(messageId, (response) => {
24709
- var _a3;
24710
- if ((_a3 = options === null || options === void 0 ? void 0 : options.signal) === null || _a3 === void 0 ? void 0 : _a3.aborted) {
24771
+ if (options?.signal?.aborted) {
24711
24772
  return;
24712
24773
  }
24713
24774
  if (response instanceof Error) {
@@ -24724,14 +24785,13 @@ var Protocol = class {
24724
24785
  reject(error2);
24725
24786
  }
24726
24787
  });
24727
- (_e = options === null || options === void 0 ? void 0 : options.signal) === null || _e === void 0 ? void 0 : _e.addEventListener("abort", () => {
24728
- var _a3;
24729
- cancel((_a3 = options === null || options === void 0 ? void 0 : options.signal) === null || _a3 === void 0 ? void 0 : _a3.reason);
24788
+ options?.signal?.addEventListener("abort", () => {
24789
+ cancel(options?.signal?.reason);
24730
24790
  });
24731
- const timeout = (_f = options === null || options === void 0 ? void 0 : options.timeout) !== null && _f !== void 0 ? _f : DEFAULT_REQUEST_TIMEOUT_MSEC;
24791
+ const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
24732
24792
  const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));
24733
- 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);
24734
- const relatedTaskId = relatedTask === null || relatedTask === void 0 ? void 0 : relatedTask.taskId;
24793
+ this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);
24794
+ const relatedTaskId = relatedTask?.taskId;
24735
24795
  if (relatedTaskId) {
24736
24796
  const responseResolver = (response) => {
24737
24797
  const handler = this._responseHandlers.get(messageId);
@@ -24794,12 +24854,11 @@ var Protocol = class {
24794
24854
  * Emits a notification, which is a one-way message that does not expect a response.
24795
24855
  */
24796
24856
  async notification(notification, options) {
24797
- var _a2, _b2, _c2, _d, _e;
24798
24857
  if (!this._transport) {
24799
24858
  throw new Error("Not connected");
24800
24859
  }
24801
24860
  this.assertNotificationCapability(notification.method);
24802
- const relatedTaskId = (_a2 = options === null || options === void 0 ? void 0 : options.relatedTask) === null || _a2 === void 0 ? void 0 : _a2.taskId;
24861
+ const relatedTaskId = options?.relatedTask?.taskId;
24803
24862
  if (relatedTaskId) {
24804
24863
  const jsonrpcNotification2 = {
24805
24864
  ...notification,
@@ -24807,7 +24866,7 @@ var Protocol = class {
24807
24866
  params: {
24808
24867
  ...notification.params,
24809
24868
  _meta: {
24810
- ...((_b2 = notification.params) === null || _b2 === void 0 ? void 0 : _b2._meta) || {},
24869
+ ...notification.params?._meta || {},
24811
24870
  [RELATED_TASK_META_KEY]: options.relatedTask
24812
24871
  }
24813
24872
  }
@@ -24819,15 +24878,14 @@ var Protocol = class {
24819
24878
  });
24820
24879
  return;
24821
24880
  }
24822
- const debouncedMethods = (_d = (_c2 = this._options) === null || _c2 === void 0 ? void 0 : _c2.debouncedNotificationMethods) !== null && _d !== void 0 ? _d : [];
24823
- 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);
24881
+ const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];
24882
+ const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask;
24824
24883
  if (canDebounce) {
24825
24884
  if (this._pendingDebouncedNotifications.has(notification.method)) {
24826
24885
  return;
24827
24886
  }
24828
24887
  this._pendingDebouncedNotifications.add(notification.method);
24829
24888
  Promise.resolve().then(() => {
24830
- var _a3, _b3;
24831
24889
  this._pendingDebouncedNotifications.delete(notification.method);
24832
24890
  if (!this._transport) {
24833
24891
  return;
@@ -24836,19 +24894,19 @@ var Protocol = class {
24836
24894
  ...notification,
24837
24895
  jsonrpc: "2.0"
24838
24896
  };
24839
- if (options === null || options === void 0 ? void 0 : options.relatedTask) {
24897
+ if (options?.relatedTask) {
24840
24898
  jsonrpcNotification2 = {
24841
24899
  ...jsonrpcNotification2,
24842
24900
  params: {
24843
24901
  ...jsonrpcNotification2.params,
24844
24902
  _meta: {
24845
- ...((_a3 = jsonrpcNotification2.params) === null || _a3 === void 0 ? void 0 : _a3._meta) || {},
24903
+ ...jsonrpcNotification2.params?._meta || {},
24846
24904
  [RELATED_TASK_META_KEY]: options.relatedTask
24847
24905
  }
24848
24906
  }
24849
24907
  };
24850
24908
  }
24851
- (_b3 = this._transport) === null || _b3 === void 0 ? void 0 : _b3.send(jsonrpcNotification2, options).catch((error2) => this._onerror(error2));
24909
+ this._transport?.send(jsonrpcNotification2, options).catch((error2) => this._onerror(error2));
24852
24910
  });
24853
24911
  return;
24854
24912
  }
@@ -24856,13 +24914,13 @@ var Protocol = class {
24856
24914
  ...notification,
24857
24915
  jsonrpc: "2.0"
24858
24916
  };
24859
- if (options === null || options === void 0 ? void 0 : options.relatedTask) {
24917
+ if (options?.relatedTask) {
24860
24918
  jsonrpcNotification = {
24861
24919
  ...jsonrpcNotification,
24862
24920
  params: {
24863
24921
  ...jsonrpcNotification.params,
24864
24922
  _meta: {
24865
- ...((_e = jsonrpcNotification.params) === null || _e === void 0 ? void 0 : _e._meta) || {},
24923
+ ...jsonrpcNotification.params?._meta || {},
24866
24924
  [RELATED_TASK_META_KEY]: options.relatedTask
24867
24925
  }
24868
24926
  }
@@ -24938,11 +24996,10 @@ var Protocol = class {
24938
24996
  * simply propagates the error.
24939
24997
  */
24940
24998
  async _enqueueTaskMessage(taskId, message, sessionId) {
24941
- var _a2;
24942
24999
  if (!this._taskStore || !this._taskMessageQueue) {
24943
25000
  throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
24944
25001
  }
24945
- const maxQueueSize = (_a2 = this._options) === null || _a2 === void 0 ? void 0 : _a2.maxTaskQueueSize;
25002
+ const maxQueueSize = this._options?.maxTaskQueueSize;
24946
25003
  await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
24947
25004
  }
24948
25005
  /**
@@ -24975,14 +25032,13 @@ var Protocol = class {
24975
25032
  * @returns Promise that resolves when an update occurs or rejects if aborted
24976
25033
  */
24977
25034
  async _waitForTaskUpdate(taskId, signal) {
24978
- var _a2, _b2, _c2;
24979
- let interval = (_b2 = (_a2 = this._options) === null || _a2 === void 0 ? void 0 : _a2.defaultTaskPollInterval) !== null && _b2 !== void 0 ? _b2 : 1e3;
25035
+ let interval = this._options?.defaultTaskPollInterval ?? 1e3;
24980
25036
  try {
24981
- const task = await ((_c2 = this._taskStore) === null || _c2 === void 0 ? void 0 : _c2.getTask(taskId));
24982
- if (task === null || task === void 0 ? void 0 : task.pollInterval) {
25037
+ const task = await this._taskStore?.getTask(taskId);
25038
+ if (task?.pollInterval) {
24983
25039
  interval = task.pollInterval;
24984
25040
  }
24985
- } catch (_d) {
25041
+ } catch {
24986
25042
  }
24987
25043
  return new Promise((resolve5, reject) => {
24988
25044
  if (signal.aborted) {
@@ -25086,7 +25142,7 @@ function mergeCapabilities(base, additional) {
25086
25142
  var import_ajv = __toESM(require_ajv(), 1);
25087
25143
  var import_ajv_formats = __toESM(require_dist(), 1);
25088
25144
  function createDefaultAjvInstance() {
25089
- const ajv = new import_ajv.Ajv({
25145
+ const ajv = new import_ajv.default({
25090
25146
  strict: false,
25091
25147
  validateFormats: true,
25092
25148
  validateSchema: false,
@@ -25118,7 +25174,7 @@ var AjvJsonSchemaValidator = class {
25118
25174
  * ```
25119
25175
  */
25120
25176
  constructor(ajv) {
25121
- this._ajv = ajv !== null && ajv !== void 0 ? ajv : createDefaultAjvInstance();
25177
+ this._ajv = ajv ?? createDefaultAjvInstance();
25122
25178
  }
25123
25179
  /**
25124
25180
  * Create a validator for the given JSON Schema
@@ -25130,8 +25186,7 @@ var AjvJsonSchemaValidator = class {
25130
25186
  * @returns A validator function that validates input data
25131
25187
  */
25132
25188
  getValidator(schema) {
25133
- var _a2;
25134
- const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? (_a2 = this._ajv.getSchema(schema.$id)) !== null && _a2 !== void 0 ? _a2 : this._ajv.compile(schema) : this._ajv.compile(schema);
25189
+ const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema) : this._ajv.compile(schema);
25135
25190
  return (input) => {
25136
25191
  const valid = ajvValidator(input);
25137
25192
  if (valid) {
@@ -25225,13 +25280,12 @@ var ExperimentalServerTasks = class {
25225
25280
 
25226
25281
  // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js
25227
25282
  function assertToolsCallTaskCapability(requests, method, entityName) {
25228
- var _a2;
25229
25283
  if (!requests) {
25230
25284
  throw new Error(`${entityName} does not support task creation (required for ${method})`);
25231
25285
  }
25232
25286
  switch (method) {
25233
25287
  case "tools/call":
25234
- if (!((_a2 = requests.tools) === null || _a2 === void 0 ? void 0 : _a2.call)) {
25288
+ if (!requests.tools?.call) {
25235
25289
  throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);
25236
25290
  }
25237
25291
  break;
@@ -25240,18 +25294,17 @@ function assertToolsCallTaskCapability(requests, method, entityName) {
25240
25294
  }
25241
25295
  }
25242
25296
  function assertClientRequestTaskCapability(requests, method, entityName) {
25243
- var _a2, _b2;
25244
25297
  if (!requests) {
25245
25298
  throw new Error(`${entityName} does not support task creation (required for ${method})`);
25246
25299
  }
25247
25300
  switch (method) {
25248
25301
  case "sampling/createMessage":
25249
- if (!((_a2 = requests.sampling) === null || _a2 === void 0 ? void 0 : _a2.createMessage)) {
25302
+ if (!requests.sampling?.createMessage) {
25250
25303
  throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);
25251
25304
  }
25252
25305
  break;
25253
25306
  case "elicitation/create":
25254
- if (!((_b2 = requests.elicitation) === null || _b2 === void 0 ? void 0 : _b2.create)) {
25307
+ if (!requests.elicitation?.create) {
25255
25308
  throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);
25256
25309
  }
25257
25310
  break;
@@ -25266,7 +25319,6 @@ var Server = class extends Protocol {
25266
25319
  * Initializes this server with the given name and version information.
25267
25320
  */
25268
25321
  constructor(_serverInfo, options) {
25269
- var _a2, _b2;
25270
25322
  super(options);
25271
25323
  this._serverInfo = _serverInfo;
25272
25324
  this._loggingLevels = /* @__PURE__ */ new Map();
@@ -25275,18 +25327,14 @@ var Server = class extends Protocol {
25275
25327
  const currentLevel = this._loggingLevels.get(sessionId);
25276
25328
  return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false;
25277
25329
  };
25278
- this._capabilities = (_a2 = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a2 !== void 0 ? _a2 : {};
25279
- this._instructions = options === null || options === void 0 ? void 0 : options.instructions;
25280
- this._jsonSchemaValidator = (_b2 = options === null || options === void 0 ? void 0 : options.jsonSchemaValidator) !== null && _b2 !== void 0 ? _b2 : new AjvJsonSchemaValidator();
25330
+ this._capabilities = options?.capabilities ?? {};
25331
+ this._instructions = options?.instructions;
25332
+ this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
25281
25333
  this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request));
25282
- this.setNotificationHandler(InitializedNotificationSchema, () => {
25283
- var _a3;
25284
- return (_a3 = this.oninitialized) === null || _a3 === void 0 ? void 0 : _a3.call(this);
25285
- });
25334
+ this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.());
25286
25335
  if (this._capabilities.logging) {
25287
25336
  this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => {
25288
- var _a3;
25289
- const transportSessionId = extra.sessionId || ((_a3 = extra.requestInfo) === null || _a3 === void 0 ? void 0 : _a3.headers["mcp-session-id"]) || void 0;
25337
+ const transportSessionId = extra.sessionId || extra.requestInfo?.headers["mcp-session-id"] || void 0;
25290
25338
  const { level } = request.params;
25291
25339
  const parseResult = LoggingLevelSchema.safeParse(level);
25292
25340
  if (parseResult.success) {
@@ -25326,21 +25374,20 @@ var Server = class extends Protocol {
25326
25374
  * Override request handler registration to enforce server-side validation for tools/call.
25327
25375
  */
25328
25376
  setRequestHandler(requestSchema, handler) {
25329
- var _a2, _b2, _c2;
25330
25377
  const shape = getObjectShape(requestSchema);
25331
- const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method;
25378
+ const methodSchema = shape?.method;
25332
25379
  if (!methodSchema) {
25333
25380
  throw new Error("Schema is missing a method literal");
25334
25381
  }
25335
25382
  let methodValue;
25336
25383
  if (isZ4Schema(methodSchema)) {
25337
25384
  const v4Schema = methodSchema;
25338
- const v4Def = (_a2 = v4Schema._zod) === null || _a2 === void 0 ? void 0 : _a2.def;
25339
- methodValue = (_b2 = v4Def === null || v4Def === void 0 ? void 0 : v4Def.value) !== null && _b2 !== void 0 ? _b2 : v4Schema.value;
25385
+ const v4Def = v4Schema._zod?.def;
25386
+ methodValue = v4Def?.value ?? v4Schema.value;
25340
25387
  } else {
25341
25388
  const v3Schema = methodSchema;
25342
25389
  const legacyDef = v3Schema._def;
25343
- methodValue = (_c2 = legacyDef === null || legacyDef === void 0 ? void 0 : legacyDef.value) !== null && _c2 !== void 0 ? _c2 : v3Schema.value;
25390
+ methodValue = legacyDef?.value ?? v3Schema.value;
25344
25391
  }
25345
25392
  if (typeof methodValue !== "string") {
25346
25393
  throw new Error("Schema method literal must be a string");
@@ -25375,20 +25422,19 @@ var Server = class extends Protocol {
25375
25422
  return super.setRequestHandler(requestSchema, handler);
25376
25423
  }
25377
25424
  assertCapabilityForMethod(method) {
25378
- var _a2, _b2, _c2;
25379
25425
  switch (method) {
25380
25426
  case "sampling/createMessage":
25381
- if (!((_a2 = this._clientCapabilities) === null || _a2 === void 0 ? void 0 : _a2.sampling)) {
25427
+ if (!this._clientCapabilities?.sampling) {
25382
25428
  throw new Error(`Client does not support sampling (required for ${method})`);
25383
25429
  }
25384
25430
  break;
25385
25431
  case "elicitation/create":
25386
- if (!((_b2 = this._clientCapabilities) === null || _b2 === void 0 ? void 0 : _b2.elicitation)) {
25432
+ if (!this._clientCapabilities?.elicitation) {
25387
25433
  throw new Error(`Client does not support elicitation (required for ${method})`);
25388
25434
  }
25389
25435
  break;
25390
25436
  case "roots/list":
25391
- if (!((_c2 = this._clientCapabilities) === null || _c2 === void 0 ? void 0 : _c2.roots)) {
25437
+ if (!this._clientCapabilities?.roots) {
25392
25438
  throw new Error(`Client does not support listing roots (required for ${method})`);
25393
25439
  }
25394
25440
  break;
@@ -25397,7 +25443,6 @@ var Server = class extends Protocol {
25397
25443
  }
25398
25444
  }
25399
25445
  assertNotificationCapability(method) {
25400
- var _a2, _b2;
25401
25446
  switch (method) {
25402
25447
  case "notifications/message":
25403
25448
  if (!this._capabilities.logging) {
@@ -25421,7 +25466,7 @@ var Server = class extends Protocol {
25421
25466
  }
25422
25467
  break;
25423
25468
  case "notifications/elicitation/complete":
25424
- if (!((_b2 = (_a2 = this._clientCapabilities) === null || _a2 === void 0 ? void 0 : _a2.elicitation) === null || _b2 === void 0 ? void 0 : _b2.url)) {
25469
+ if (!this._clientCapabilities?.elicitation?.url) {
25425
25470
  throw new Error(`Client does not support URL elicitation (required for ${method})`);
25426
25471
  }
25427
25472
  break;
@@ -25479,15 +25524,13 @@ var Server = class extends Protocol {
25479
25524
  }
25480
25525
  }
25481
25526
  assertTaskCapability(method) {
25482
- var _a2, _b2;
25483
- assertClientRequestTaskCapability((_b2 = (_a2 = this._clientCapabilities) === null || _a2 === void 0 ? void 0 : _a2.tasks) === null || _b2 === void 0 ? void 0 : _b2.requests, method, "Client");
25527
+ assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, "Client");
25484
25528
  }
25485
25529
  assertTaskHandlerCapability(method) {
25486
- var _a2;
25487
25530
  if (!this._capabilities) {
25488
25531
  return;
25489
25532
  }
25490
- assertToolsCallTaskCapability((_a2 = this._capabilities.tasks) === null || _a2 === void 0 ? void 0 : _a2.requests, method, "Server");
25533
+ assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, "Server");
25491
25534
  }
25492
25535
  async _oninitialize(request) {
25493
25536
  const requestedVersion = request.params.protocolVersion;
@@ -25521,9 +25564,8 @@ var Server = class extends Protocol {
25521
25564
  }
25522
25565
  // Implementation
25523
25566
  async createMessage(params, options) {
25524
- var _a2, _b2;
25525
25567
  if (params.tools || params.toolChoice) {
25526
- if (!((_b2 = (_a2 = this._clientCapabilities) === null || _a2 === void 0 ? void 0 : _a2.sampling) === null || _b2 === void 0 ? void 0 : _b2.tools)) {
25568
+ if (!this._clientCapabilities?.sampling?.tools) {
25527
25569
  throw new Error("Client does not support sampling tools capability.");
25528
25570
  }
25529
25571
  }
@@ -25563,18 +25605,17 @@ var Server = class extends Protocol {
25563
25605
  * @returns The result of the elicitation request.
25564
25606
  */
25565
25607
  async elicitInput(params, options) {
25566
- var _a2, _b2, _c2, _d, _e;
25567
- const mode = (_a2 = params.mode) !== null && _a2 !== void 0 ? _a2 : "form";
25608
+ const mode = params.mode ?? "form";
25568
25609
  switch (mode) {
25569
25610
  case "url": {
25570
- if (!((_c2 = (_b2 = this._clientCapabilities) === null || _b2 === void 0 ? void 0 : _b2.elicitation) === null || _c2 === void 0 ? void 0 : _c2.url)) {
25611
+ if (!this._clientCapabilities?.elicitation?.url) {
25571
25612
  throw new Error("Client does not support url elicitation.");
25572
25613
  }
25573
25614
  const urlParams = params;
25574
25615
  return this.request({ method: "elicitation/create", params: urlParams }, ElicitResultSchema, options);
25575
25616
  }
25576
25617
  case "form": {
25577
- if (!((_e = (_d = this._clientCapabilities) === null || _d === void 0 ? void 0 : _d.elicitation) === null || _e === void 0 ? void 0 : _e.form)) {
25618
+ if (!this._clientCapabilities?.elicitation?.form) {
25578
25619
  throw new Error("Client does not support form elicitation.");
25579
25620
  }
25580
25621
  const formParams = params.mode === "form" ? params : { ...params, mode: "form" };
@@ -25606,8 +25647,7 @@ var Server = class extends Protocol {
25606
25647
  * @returns A function that emits the completion notification when awaited.
25607
25648
  */
25608
25649
  createElicitationCompletionNotifier(elicitationId, options) {
25609
- var _a2, _b2;
25610
- if (!((_b2 = (_a2 = this._clientCapabilities) === null || _a2 === void 0 ? void 0 : _a2.elicitation) === null || _b2 === void 0 ? void 0 : _b2.url)) {
25650
+ if (!this._clientCapabilities?.elicitation?.url) {
25611
25651
  throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");
25612
25652
  }
25613
25653
  return () => this.notification({
@@ -25660,7 +25700,7 @@ function isCompletable(schema) {
25660
25700
  }
25661
25701
  function getCompleter(schema) {
25662
25702
  const meta = schema[COMPLETABLE_SYMBOL];
25663
- return meta === null || meta === void 0 ? void 0 : meta.complete;
25703
+ return meta?.complete;
25664
25704
  }
25665
25705
  var McpZodTypeKind;
25666
25706
  (function(McpZodTypeKind2) {
@@ -25823,7 +25863,6 @@ var McpServer = class {
25823
25863
  })
25824
25864
  }));
25825
25865
  this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
25826
- var _a2;
25827
25866
  try {
25828
25867
  const tool = this._registeredTools[request.params.name];
25829
25868
  if (!tool) {
@@ -25833,7 +25872,7 @@ var McpServer = class {
25833
25872
  throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);
25834
25873
  }
25835
25874
  const isTaskRequest = !!request.params.task;
25836
- const taskSupport = (_a2 = tool.execution) === null || _a2 === void 0 ? void 0 : _a2.taskSupport;
25875
+ const taskSupport = tool.execution?.taskSupport;
25837
25876
  const isTaskHandler = "createTask" in tool.handler;
25838
25877
  if ((taskSupport === "required" || taskSupport === "optional") && !isTaskHandler) {
25839
25878
  throw new McpError(ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`);
@@ -25887,7 +25926,7 @@ var McpServer = class {
25887
25926
  return void 0;
25888
25927
  }
25889
25928
  const inputObj = normalizeObjectSchema(tool.inputSchema);
25890
- const schemaToParse = inputObj !== null && inputObj !== void 0 ? inputObj : tool.inputSchema;
25929
+ const schemaToParse = inputObj ?? tool.inputSchema;
25891
25930
  const parseResult = await safeParseAsync2(schemaToParse, args);
25892
25931
  if (!parseResult.success) {
25893
25932
  const error2 = "error" in parseResult ? parseResult.error : "Unknown error";
@@ -25951,7 +25990,6 @@ var McpServer = class {
25951
25990
  * Handles automatic task polling for tools with taskSupport 'optional'.
25952
25991
  */
25953
25992
  async handleAutomaticTaskPolling(tool, request, extra) {
25954
- var _a2;
25955
25993
  if (!extra.taskStore) {
25956
25994
  throw new Error("No task store provided for task-capable tool.");
25957
25995
  }
@@ -25964,7 +26002,7 @@ var McpServer = class {
25964
26002
  );
25965
26003
  const taskId = createTaskResult.task.taskId;
25966
26004
  let task = createTaskResult.task;
25967
- const pollInterval = (_a2 = task.pollInterval) !== null && _a2 !== void 0 ? _a2 : 5e3;
26005
+ const pollInterval = task.pollInterval ?? 5e3;
25968
26006
  while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {
25969
26007
  await new Promise((resolve5) => setTimeout(resolve5, pollInterval));
25970
26008
  const updatedTask = await extra.taskStore.getTask(taskId);
@@ -26009,7 +26047,7 @@ var McpServer = class {
26009
26047
  return EMPTY_COMPLETION_RESULT;
26010
26048
  }
26011
26049
  const promptShape = getObjectShape(prompt.argsSchema);
26012
- const field = promptShape === null || promptShape === void 0 ? void 0 : promptShape[request.params.argument.name];
26050
+ const field = promptShape?.[request.params.argument.name];
26013
26051
  if (!isCompletable(field)) {
26014
26052
  return EMPTY_COMPLETION_RESULT;
26015
26053
  }
@@ -26094,7 +26132,6 @@ var McpServer = class {
26094
26132
  }
26095
26133
  throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`);
26096
26134
  });
26097
- this.setCompletionRequestHandler();
26098
26135
  this._resourceHandlersInitialized = true;
26099
26136
  }
26100
26137
  setPromptRequestHandlers() {
@@ -26142,7 +26179,6 @@ var McpServer = class {
26142
26179
  return await Promise.resolve(cb(extra));
26143
26180
  }
26144
26181
  });
26145
- this.setCompletionRequestHandler();
26146
26182
  this._promptHandlersInitialized = true;
26147
26183
  }
26148
26184
  resource(name, uriOrTemplate, ...rest) {
@@ -26250,6 +26286,11 @@ var McpServer = class {
26250
26286
  }
26251
26287
  };
26252
26288
  this._registeredResourceTemplates[name] = registeredResourceTemplate;
26289
+ const variableNames = template.uriTemplate.variableNames;
26290
+ const hasCompleter = Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v));
26291
+ if (hasCompleter) {
26292
+ this.setCompletionRequestHandler();
26293
+ }
26253
26294
  return registeredResourceTemplate;
26254
26295
  }
26255
26296
  _createRegisteredPrompt(name, title, description, argsSchema, callback) {
@@ -26282,14 +26323,23 @@ var McpServer = class {
26282
26323
  }
26283
26324
  };
26284
26325
  this._registeredPrompts[name] = registeredPrompt;
26326
+ if (argsSchema) {
26327
+ const hasCompletable = Object.values(argsSchema).some((field) => {
26328
+ const inner = field instanceof ZodOptional ? field._def?.innerType : field;
26329
+ return isCompletable(inner);
26330
+ });
26331
+ if (hasCompletable) {
26332
+ this.setCompletionRequestHandler();
26333
+ }
26334
+ }
26285
26335
  return registeredPrompt;
26286
26336
  }
26287
- _createRegisteredTool(name, title, description, inputSchema25, outputSchema, annotations, execution, _meta, handler) {
26337
+ _createRegisteredTool(name, title, description, inputSchema26, outputSchema, annotations, execution, _meta, handler) {
26288
26338
  validateAndWarnToolName(name);
26289
26339
  const registeredTool = {
26290
26340
  title,
26291
26341
  description,
26292
- inputSchema: getZodSchemaObject(inputSchema25),
26342
+ inputSchema: getZodSchemaObject(inputSchema26),
26293
26343
  outputSchema: getZodSchemaObject(outputSchema),
26294
26344
  annotations,
26295
26345
  execution,
@@ -26314,6 +26364,8 @@ var McpServer = class {
26314
26364
  registeredTool.description = updates.description;
26315
26365
  if (typeof updates.paramsSchema !== "undefined")
26316
26366
  registeredTool.inputSchema = objectFromShape(updates.paramsSchema);
26367
+ if (typeof updates.outputSchema !== "undefined")
26368
+ registeredTool.outputSchema = objectFromShape(updates.outputSchema);
26317
26369
  if (typeof updates.callback !== "undefined")
26318
26370
  registeredTool.handler = updates.callback;
26319
26371
  if (typeof updates.annotations !== "undefined")
@@ -26338,7 +26390,7 @@ var McpServer = class {
26338
26390
  throw new Error(`Tool ${name} is already registered`);
26339
26391
  }
26340
26392
  let description;
26341
- let inputSchema25;
26393
+ let inputSchema26;
26342
26394
  let outputSchema;
26343
26395
  let annotations;
26344
26396
  if (typeof rest[0] === "string") {
@@ -26347,7 +26399,7 @@ var McpServer = class {
26347
26399
  if (rest.length > 1) {
26348
26400
  const firstArg = rest[0];
26349
26401
  if (isZodRawShapeCompat(firstArg)) {
26350
- inputSchema25 = rest.shift();
26402
+ inputSchema26 = rest.shift();
26351
26403
  if (rest.length > 1 && typeof rest[0] === "object" && rest[0] !== null && !isZodRawShapeCompat(rest[0])) {
26352
26404
  annotations = rest.shift();
26353
26405
  }
@@ -26356,7 +26408,7 @@ var McpServer = class {
26356
26408
  }
26357
26409
  }
26358
26410
  const callback = rest[0];
26359
- return this._createRegisteredTool(name, void 0, description, inputSchema25, outputSchema, annotations, { taskSupport: "forbidden" }, void 0, callback);
26411
+ return this._createRegisteredTool(name, void 0, description, inputSchema26, outputSchema, annotations, { taskSupport: "forbidden" }, void 0, callback);
26360
26412
  }
26361
26413
  /**
26362
26414
  * Registers a tool with a config object and callback.
@@ -26365,8 +26417,8 @@ var McpServer = class {
26365
26417
  if (this._registeredTools[name]) {
26366
26418
  throw new Error(`Tool ${name} is already registered`);
26367
26419
  }
26368
- const { title, description, inputSchema: inputSchema25, outputSchema, annotations, _meta } = config2;
26369
- return this._createRegisteredTool(name, title, description, inputSchema25, outputSchema, annotations, { taskSupport: "forbidden" }, _meta, cb);
26420
+ const { title, description, inputSchema: inputSchema26, outputSchema, annotations, _meta } = config2;
26421
+ return this._createRegisteredTool(name, title, description, inputSchema26, outputSchema, annotations, { taskSupport: "forbidden" }, _meta, cb);
26370
26422
  }
26371
26423
  prompt(name, ...rest) {
26372
26424
  if (this._registeredPrompts[name]) {
@@ -26488,7 +26540,7 @@ function promptArgumentsFromSchema(schema) {
26488
26540
  }
26489
26541
  function getMethodValue(schema) {
26490
26542
  const shape = getObjectShape(schema);
26491
- const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method;
26543
+ const methodSchema = shape?.method;
26492
26544
  if (!methodSchema) {
26493
26545
  throw new Error("Schema is missing a method literal");
26494
26546
  }
@@ -27393,8 +27445,71 @@ var registerDownloadObjectTool = (server) => {
27393
27445
  );
27394
27446
  };
27395
27447
 
27396
- // src/tools/objects/list_objects.ts
27448
+ // src/tools/objects/download_object_safe.ts
27449
+ import fs from "fs";
27397
27450
  var inputSchema13 = {
27451
+ bucket_name: external_exports.string().describe("The name of the GCS bucket."),
27452
+ object_name: external_exports.string().describe("The name of the object to download."),
27453
+ file_path: external_exports.string().describe("The local path to save the downloaded file to.")
27454
+ };
27455
+ async function downloadObjectSafe(params) {
27456
+ try {
27457
+ if (fs.existsSync(params.file_path)) {
27458
+ return {
27459
+ content: [
27460
+ {
27461
+ type: "text",
27462
+ text: JSON.stringify({
27463
+ success: false,
27464
+ error: `File already exists at path: ${params.file_path}`,
27465
+ error_type: "AlreadyExists"
27466
+ })
27467
+ }
27468
+ ]
27469
+ };
27470
+ }
27471
+ const storage = apiClientFactory.getStorageClient();
27472
+ await storage.bucket(params.bucket_name).file(params.object_name).download({ destination: params.file_path });
27473
+ return {
27474
+ content: [
27475
+ {
27476
+ type: "text",
27477
+ text: JSON.stringify({
27478
+ success: true,
27479
+ message: `Object ${params.object_name} from bucket ${params.bucket_name} downloaded to ${params.file_path}.`
27480
+ })
27481
+ }
27482
+ ]
27483
+ };
27484
+ } catch (e) {
27485
+ const error2 = e;
27486
+ logger.error(error2.message);
27487
+ return {
27488
+ content: [
27489
+ {
27490
+ type: "text",
27491
+ text: JSON.stringify({
27492
+ success: false,
27493
+ error: error2.message
27494
+ })
27495
+ }
27496
+ ]
27497
+ };
27498
+ }
27499
+ }
27500
+ var registerDownloadObjectSafeTool = (server) => {
27501
+ server.registerTool(
27502
+ "download_object_safe",
27503
+ {
27504
+ description: "Downloads an object from GCS to a local file. Fails if the destination file already exists.",
27505
+ inputSchema: inputSchema13
27506
+ },
27507
+ downloadObjectSafe
27508
+ );
27509
+ };
27510
+
27511
+ // src/tools/objects/list_objects.ts
27512
+ var inputSchema14 = {
27398
27513
  bucket_name: external_exports.string().describe("The name of the GCS bucket."),
27399
27514
  prefix: external_exports.string().optional().describe("Filters results to objects whose names begin with this prefix."),
27400
27515
  delimiter: external_exports.string().optional().describe(
@@ -27471,14 +27586,14 @@ var registerListObjectsTool = (server) => {
27471
27586
  "list_objects",
27472
27587
  {
27473
27588
  description: "Lists the names of objects in a Google Cloud Storage (GCS) bucket. Supports filtering by prefix, directory-like listing with a delimiter, pagination, and listing object versions.",
27474
- inputSchema: inputSchema13
27589
+ inputSchema: inputSchema14
27475
27590
  },
27476
27591
  listObjects
27477
27592
  );
27478
27593
  };
27479
27594
 
27480
27595
  // src/tools/objects/move_object.ts
27481
- var inputSchema14 = {
27596
+ var inputSchema15 = {
27482
27597
  source_bucket_name: external_exports.string().describe("The name of the source GCS bucket."),
27483
27598
  source_object_name: external_exports.string().describe("The name of the source object."),
27484
27599
  destination_bucket_name: external_exports.string().describe("The name of the destination GCS bucket."),
@@ -27532,7 +27647,7 @@ var registerMoveObjectTool = (server) => {
27532
27647
  "move_object",
27533
27648
  {
27534
27649
  description: "Moves an object from one bucket to another or renames it within the same bucket by copying and deleting the original.",
27535
- inputSchema: inputSchema14
27650
+ inputSchema: inputSchema15
27536
27651
  },
27537
27652
  moveObject
27538
27653
  );
@@ -27675,7 +27790,7 @@ function detectBufferType(buffer, contentType, fileName) {
27675
27790
 
27676
27791
  // src/tools/objects/read_object_content.ts
27677
27792
  var { decode } = iconv;
27678
- var inputSchema15 = {
27793
+ var inputSchema16 = {
27679
27794
  bucket_name: external_exports.string().describe("The name of the GCS bucket."),
27680
27795
  object_name: external_exports.string().describe("The name of the object.")
27681
27796
  };
@@ -27810,14 +27925,14 @@ var registerReadObjectContentTool = (server) => {
27810
27925
  "read_object_content",
27811
27926
  {
27812
27927
  description: "Reads the content of a specific object.",
27813
- inputSchema: inputSchema15
27928
+ inputSchema: inputSchema16
27814
27929
  },
27815
27930
  readObjectContent
27816
27931
  );
27817
27932
  };
27818
27933
 
27819
27934
  // src/tools/objects/read_object_metadata.ts
27820
- var inputSchema16 = {
27935
+ var inputSchema17 = {
27821
27936
  bucket_name: external_exports.string().describe("The name of the GCS bucket."),
27822
27937
  object_name: external_exports.string().describe("The name of the object.")
27823
27938
  };
@@ -27874,14 +27989,14 @@ var registerReadObjectMetadataTool = (server) => {
27874
27989
  "read_object_metadata",
27875
27990
  {
27876
27991
  description: "Reads metadata for a specific object.",
27877
- inputSchema: inputSchema16
27992
+ inputSchema: inputSchema17
27878
27993
  },
27879
27994
  readObjectMetadata
27880
27995
  );
27881
27996
  };
27882
27997
 
27883
27998
  // src/tools/objects/update_object_metadata.ts
27884
- var inputSchema17 = {
27999
+ var inputSchema18 = {
27885
28000
  bucket_name: external_exports.string().describe("The name of the GCS bucket."),
27886
28001
  object_name: external_exports.string().describe("The name of the object to update."),
27887
28002
  metadata: external_exports.record(external_exports.string()).describe("A dictionary of metadata to set on the object.")
@@ -27935,16 +28050,16 @@ var registerUpdateObjectMetadataTool = (server) => {
27935
28050
  "update_object_metadata",
27936
28051
  {
27937
28052
  description: "Updates the metadata of an existing object.",
27938
- inputSchema: inputSchema17
28053
+ inputSchema: inputSchema18
27939
28054
  },
27940
28055
  updateObjectMetadata
27941
28056
  );
27942
28057
  };
27943
28058
 
27944
28059
  // src/tools/objects/upload_object.ts
27945
- import * as fs from "fs";
28060
+ import * as fs2 from "fs";
27946
28061
  import * as path2 from "path";
27947
- var inputSchema18 = {
28062
+ var inputSchema19 = {
27948
28063
  bucket_name: external_exports.string().describe("The name of the GCS bucket."),
27949
28064
  file_path: external_exports.string().describe("The local path of the file to upload."),
27950
28065
  object_name: external_exports.string().optional().describe(
@@ -27955,7 +28070,7 @@ var inputSchema18 = {
27955
28070
  async function uploadObject(params) {
27956
28071
  try {
27957
28072
  logger.info(`Uploading file: ${params.file_path} to bucket: ${params.bucket_name}`);
27958
- if (!fs.existsSync(params.file_path)) {
28073
+ if (!fs2.existsSync(params.file_path)) {
27959
28074
  return {
27960
28075
  content: [
27961
28076
  {
@@ -28017,15 +28132,15 @@ var registerUploadObjectTool = (server) => {
28017
28132
  "upload_object",
28018
28133
  {
28019
28134
  description: "Uploads a file to a GCS bucket.",
28020
- inputSchema: inputSchema18
28135
+ inputSchema: inputSchema19
28021
28136
  },
28022
28137
  uploadObject
28023
28138
  );
28024
28139
  };
28025
28140
 
28026
28141
  // src/tools/objects/upload_object_safe.ts
28027
- import * as fs2 from "fs";
28028
- var inputSchema19 = {
28142
+ import * as fs3 from "fs";
28143
+ var inputSchema20 = {
28029
28144
  bucket_name: external_exports.string().describe("The name of the GCS bucket."),
28030
28145
  file_path: external_exports.string().describe("The local path of the file to upload."),
28031
28146
  object_name: external_exports.string().optional().describe(
@@ -28036,7 +28151,7 @@ var inputSchema19 = {
28036
28151
  async function uploadObjectSafe(params) {
28037
28152
  try {
28038
28153
  logger.info(`Uploading safe file: ${params.file_path} to bucket: ${params.bucket_name}`);
28039
- if (!fs2.existsSync(params.file_path)) {
28154
+ if (!fs3.existsSync(params.file_path)) {
28040
28155
  const errorMsg = `File not found at path: ${params.file_path}`;
28041
28156
  logger.error(errorMsg);
28042
28157
  return {
@@ -28059,7 +28174,7 @@ async function uploadObjectSafe(params) {
28059
28174
  }
28060
28175
  const file = bucket.file(objectName, { generation: 0 });
28061
28176
  const contentType = params.content_type || getContentType(params.file_path);
28062
- await file.save(fs2.readFileSync(params.file_path), {
28177
+ await file.save(fs3.readFileSync(params.file_path), {
28063
28178
  contentType
28064
28179
  });
28065
28180
  const [metadata] = await file.getMetadata();
@@ -28104,14 +28219,14 @@ var registerUploadObjectSafeTool = (server) => {
28104
28219
  "upload_object_safe",
28105
28220
  {
28106
28221
  description: "Uploads a file to a GCS bucket. Fails if the object already exists.",
28107
- inputSchema: inputSchema19
28222
+ inputSchema: inputSchema20
28108
28223
  },
28109
28224
  uploadObjectSafe
28110
28225
  );
28111
28226
  };
28112
28227
 
28113
28228
  // src/tools/objects/write_object.ts
28114
- var inputSchema20 = {
28229
+ var inputSchema21 = {
28115
28230
  bucket_name: external_exports.string().describe("The name of the GCS bucket."),
28116
28231
  object_name: external_exports.string().describe("The name of the object to write."),
28117
28232
  content: external_exports.string().describe("The content to write to the object, encoded in base64."),
@@ -28183,14 +28298,14 @@ var registerWriteObjectTool = (server) => {
28183
28298
  "write_object",
28184
28299
  {
28185
28300
  description: "Writes a new object to the bucket.",
28186
- inputSchema: inputSchema20
28301
+ inputSchema: inputSchema21
28187
28302
  },
28188
28303
  writeObject
28189
28304
  );
28190
28305
  };
28191
28306
 
28192
28307
  // src/tools/objects/write_object_safe.ts
28193
- var inputSchema21 = {
28308
+ var inputSchema22 = {
28194
28309
  bucket_name: external_exports.string().describe("The name of the GCS bucket."),
28195
28310
  object_name: external_exports.string().describe("The name of the object to write."),
28196
28311
  content: external_exports.string().describe("The content to write to the object, encoded in base64."),
@@ -28269,7 +28384,7 @@ var registerWriteObjectSafeTool = (server) => {
28269
28384
  "write_object_safe",
28270
28385
  {
28271
28386
  description: "Writes a new object to the bucket. Fails if the object already exists.",
28272
- inputSchema: inputSchema21
28387
+ inputSchema: inputSchema22
28273
28388
  },
28274
28389
  writeObjectSafe
28275
28390
  );
@@ -28277,7 +28392,7 @@ var registerWriteObjectSafeTool = (server) => {
28277
28392
 
28278
28393
  // src/tools/insights/get_metadata_table_schema.ts
28279
28394
  var serviceName = "storageinsights.googleapis.com";
28280
- var inputSchema22 = {
28395
+ var inputSchema23 = {
28281
28396
  datasetConfigName: external_exports.string().describe("The name of the dataset configuration."),
28282
28397
  datasetConfigLocation: external_exports.string().describe("The location of the dataset configuration."),
28283
28398
  projectId: external_exports.string().optional().describe("The project ID to check Storage Insights availability for.")
@@ -28511,14 +28626,14 @@ var registerGetMetadataTableSchemaTool = (server) => {
28511
28626
  "get_metadata_table_schema",
28512
28627
  {
28513
28628
  description: "Checks if GCS insights service is enabled and returns the BigQuery table schema for a given insights dataset configuration in JSON format. Also returns hints for each column in the table",
28514
- inputSchema: inputSchema22
28629
+ inputSchema: inputSchema23
28515
28630
  },
28516
28631
  getMetadataTableSchema
28517
28632
  );
28518
28633
  };
28519
28634
 
28520
28635
  // src/tools/insights/execute_insights_query.ts
28521
- var inputSchema23 = {
28636
+ var inputSchema24 = {
28522
28637
  config: external_exports.string().describe(
28523
28638
  "The JSON object of the BigQuery table schema for a given insights dataset configuration."
28524
28639
  ),
@@ -28630,7 +28745,7 @@ var registerExecuteInsightsQueryTool = (server) => {
28630
28745
  "execute_insights_query",
28631
28746
  {
28632
28747
  description: "Executes a BigQuery SQL query against an insights dataset and returns the result.",
28633
- inputSchema: inputSchema23
28748
+ inputSchema: inputSchema24
28634
28749
  },
28635
28750
  executeInsightsQuery
28636
28751
  );
@@ -28638,7 +28753,7 @@ var registerExecuteInsightsQueryTool = (server) => {
28638
28753
 
28639
28754
  // src/tools/insights/list_insights_configs.ts
28640
28755
  var serviceName2 = "storageinsights.googleapis.com";
28641
- var inputSchema24 = {
28756
+ var inputSchema25 = {
28642
28757
  projectId: external_exports.string().optional().describe("The project ID to list Storage Insights dataset configurations for.")
28643
28758
  };
28644
28759
  async function listInsightsConfigs(params) {
@@ -28703,7 +28818,7 @@ var registerListInsightsConfigsTool = (server) => {
28703
28818
  "list_insights_configs",
28704
28819
  {
28705
28820
  description: "Lists the names of all Storage Insights dataset configurations for a given project.",
28706
- inputSchema: inputSchema24
28821
+ inputSchema: inputSchema25
28707
28822
  },
28708
28823
  listInsightsConfigs
28709
28824
  );
@@ -28720,7 +28835,7 @@ var commonSafeTools = [
28720
28835
  registerListObjectsTool,
28721
28836
  registerReadObjectContentTool,
28722
28837
  registerReadObjectMetadataTool,
28723
- registerDownloadObjectTool,
28838
+ registerDownloadObjectSafeTool,
28724
28839
  registerDeleteObjectTool,
28725
28840
  registerGetMetadataTableSchemaTool,
28726
28841
  registerExecuteInsightsQueryTool,
@@ -28740,7 +28855,8 @@ var otherDestructiveTools = [
28740
28855
  registerDeleteBucketTool,
28741
28856
  registerUpdateBucketLabelsTool,
28742
28857
  registerMoveObjectTool,
28743
- registerUpdateObjectMetadataTool
28858
+ registerUpdateObjectMetadataTool,
28859
+ registerDownloadObjectTool
28744
28860
  ];
28745
28861
 
28746
28862
  // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
@@ -28786,8 +28902,7 @@ var StdioServerTransport = class {
28786
28902
  this.processReadBuffer();
28787
28903
  };
28788
28904
  this._onerror = (error2) => {
28789
- var _a2;
28790
- (_a2 = this.onerror) === null || _a2 === void 0 ? void 0 : _a2.call(this, error2);
28905
+ this.onerror?.(error2);
28791
28906
  };
28792
28907
  }
28793
28908
  /**
@@ -28802,21 +28917,19 @@ var StdioServerTransport = class {
28802
28917
  this._stdin.on("error", this._onerror);
28803
28918
  }
28804
28919
  processReadBuffer() {
28805
- var _a2, _b2;
28806
28920
  while (true) {
28807
28921
  try {
28808
28922
  const message = this._readBuffer.readMessage();
28809
28923
  if (message === null) {
28810
28924
  break;
28811
28925
  }
28812
- (_a2 = this.onmessage) === null || _a2 === void 0 ? void 0 : _a2.call(this, message);
28926
+ this.onmessage?.(message);
28813
28927
  } catch (error2) {
28814
- (_b2 = this.onerror) === null || _b2 === void 0 ? void 0 : _b2.call(this, error2);
28928
+ this.onerror?.(error2);
28815
28929
  }
28816
28930
  }
28817
28931
  }
28818
28932
  async close() {
28819
- var _a2;
28820
28933
  this._stdin.off("data", this._ondata);
28821
28934
  this._stdin.off("error", this._onerror);
28822
28935
  const remainingDataListeners = this._stdin.listenerCount("data");
@@ -28824,7 +28937,7 @@ var StdioServerTransport = class {
28824
28937
  this._stdin.pause();
28825
28938
  }
28826
28939
  this._readBuffer.clear();
28827
- (_a2 = this.onclose) === null || _a2 === void 0 ? void 0 : _a2.call(this);
28940
+ this.onclose?.();
28828
28941
  }
28829
28942
  send(message) {
28830
28943
  return new Promise((resolve5) => {
@@ -28841,7 +28954,7 @@ var StdioServerTransport = class {
28841
28954
  // package.json
28842
28955
  var package_default = {
28843
28956
  name: "@google-cloud/storage-mcp",
28844
- version: "0.3.2",
28957
+ version: "0.4.0",
28845
28958
  type: "module",
28846
28959
  main: "dist/bundle.js",
28847
28960
  bin: {
@@ -28891,7 +29004,7 @@ var package_default = {
28891
29004
  eslint: "^9.32.0",
28892
29005
  "eslint-config-prettier": "^10.1.8",
28893
29006
  "eslint-plugin-import": "^2.32.0",
28894
- "eslint-plugin-license-header": "^0.8.0",
29007
+ "eslint-plugin-license-header": "^0.9.0",
28895
29008
  "eslint-plugin-prettier": "^5.5.4",
28896
29009
  prettier: "^3.6.2",
28897
29010
  turbo: "latest",
@@ -28902,13 +29015,13 @@ var package_default = {
28902
29015
  dependencies: {
28903
29016
  "@google-cloud/bigquery": "^8.0.0",
28904
29017
  "@google-cloud/service-usage": "^4.2.0",
28905
- "@google-cloud/storage": "^7.17.1",
29018
+ "@google-cloud/storage": "^7.19.0",
28906
29019
  "@google-cloud/storageinsights": "^2.2.0",
28907
- "@modelcontextprotocol/sdk": "^1.24.0",
29020
+ "@modelcontextprotocol/sdk": "^1.26.0",
28908
29021
  "@types/yargs": "^17.0.33",
28909
29022
  chardet: "^2.1.0",
28910
29023
  "google-auth-library": "^9.11.0",
28911
- googleapis: "^169.0.0",
29024
+ googleapis: "^171.0.0",
28912
29025
  "iconv-lite": "^0.7.0",
28913
29026
  "mime-types": "^2.1.35",
28914
29027
  yargs: "^18.0.0",
@@ -34283,10 +34396,10 @@ For example, you can use the tools to:
34283
34396
  ## GCS Reference Documentation
34284
34397
 
34285
34398
  If additional context or information is needed on GCS, reference documentation can be found at https://cloud.google.com/storage/docs.`;
34286
- var initializeGeminiCLI = async (local = false, enableDestructiveTools = false, fs3 = { mkdir, writeFile: writeFile2 }) => {
34399
+ var initializeGeminiCLI = async (local = false, enableDestructiveTools = false, fs4 = { mkdir, writeFile: writeFile2 }) => {
34287
34400
  try {
34288
34401
  const extensionDir = join2(os.homedir(), ".gemini", "extensions", "storage-mcp");
34289
- await fs3.mkdir(extensionDir, { recursive: true });
34402
+ await fs4.mkdir(extensionDir, { recursive: true });
34290
34403
  const extensionFile = join2(extensionDir, "gemini-extension.json");
34291
34404
  const commandArgs = local ? ["-y", "storage-mcp"] : ["-y", "@google-cloud/storage-mcp"];
34292
34405
  if (enableDestructiveTools) {
@@ -34304,10 +34417,10 @@ var initializeGeminiCLI = async (local = false, enableDestructiveTools = false,
34304
34417
  }
34305
34418
  }
34306
34419
  };
34307
- await fs3.writeFile(extensionFile, JSON.stringify(extensionJson, null, 2));
34420
+ await fs4.writeFile(extensionFile, JSON.stringify(extensionJson, null, 2));
34308
34421
  console.log(`Created: ${extensionFile}`);
34309
34422
  const geminiMdDestPath = join2(extensionDir, "GEMINI.md");
34310
- await fs3.writeFile(geminiMdDestPath, geminiMdContent);
34423
+ await fs4.writeFile(geminiMdDestPath, geminiMdContent);
34311
34424
  console.log(`Created: ${geminiMdDestPath}`);
34312
34425
  console.log(`\u{1F331} storage-mcp Gemini CLI extension initialized.`);
34313
34426
  } catch (err) {