@fre4x/grok 1.0.51 → 1.0.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +2820 -628
  2. package/package.json +5 -6
package/dist/index.js CHANGED
@@ -3229,8 +3229,8 @@ var require_utils = __commonJS({
3229
3229
  }
3230
3230
  return ind;
3231
3231
  }
3232
- function removeDotSegments(path2) {
3233
- let input = path2;
3232
+ function removeDotSegments(path3) {
3233
+ let input = path3;
3234
3234
  const output = [];
3235
3235
  let nextSlash = -1;
3236
3236
  let len = 0;
@@ -3429,8 +3429,8 @@ var require_schemes = __commonJS({
3429
3429
  wsComponent.secure = void 0;
3430
3430
  }
3431
3431
  if (wsComponent.resourceName) {
3432
- const [path2, query] = wsComponent.resourceName.split("?");
3433
- wsComponent.path = path2 && path2 !== "/" ? path2 : void 0;
3432
+ const [path3, query] = wsComponent.resourceName.split("?");
3433
+ wsComponent.path = path3 && path3 !== "/" ? path3 : void 0;
3434
3434
  wsComponent.query = query;
3435
3435
  wsComponent.resourceName = void 0;
3436
3436
  }
@@ -6792,12 +6792,12 @@ var require_dist = __commonJS({
6792
6792
  throw new Error(`Unknown format "${name}"`);
6793
6793
  return f;
6794
6794
  };
6795
- function addFormats(ajv, list, fs2, exportName) {
6795
+ function addFormats(ajv, list, fs3, exportName) {
6796
6796
  var _a2;
6797
6797
  var _b;
6798
6798
  (_a2 = (_b = ajv.opts.code).formats) !== null && _a2 !== void 0 ? _a2 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
6799
6799
  for (const f of list)
6800
- ajv.addFormat(f, fs2[f]);
6800
+ ajv.addFormat(f, fs3[f]);
6801
6801
  }
6802
6802
  module.exports = exports = formatsPlugin;
6803
6803
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -15652,11 +15652,11 @@ var require_mime_types = __commonJS({
15652
15652
  }
15653
15653
  return exts[0];
15654
15654
  }
15655
- function lookup(path2) {
15656
- if (!path2 || typeof path2 !== "string") {
15655
+ function lookup(path3) {
15656
+ if (!path3 || typeof path3 !== "string") {
15657
15657
  return false;
15658
15658
  }
15659
- var extension2 = extname("x." + path2).toLowerCase().substr(1);
15659
+ var extension2 = extname("x." + path3).toLowerCase().substr(1);
15660
15660
  if (!extension2) {
15661
15661
  return false;
15662
15662
  }
@@ -16084,7 +16084,7 @@ var require_shams = __commonJS({
16084
16084
  return true;
16085
16085
  }
16086
16086
  var obj = {};
16087
- var sym = Symbol("test");
16087
+ var sym = /* @__PURE__ */ Symbol("test");
16088
16088
  var symObj = Object(sym);
16089
16089
  if (typeof sym === "string") {
16090
16090
  return false;
@@ -16143,7 +16143,7 @@ var require_has_symbols = __commonJS({
16143
16143
  if (typeof origSymbol("foo") !== "symbol") {
16144
16144
  return false;
16145
16145
  }
16146
- if (typeof Symbol("bar") !== "symbol") {
16146
+ if (typeof /* @__PURE__ */ Symbol("bar") !== "symbol") {
16147
16147
  return false;
16148
16148
  }
16149
16149
  return hasSymbolSham();
@@ -16761,11 +16761,11 @@ var require_form_data = __commonJS({
16761
16761
  "use strict";
16762
16762
  var CombinedStream = require_combined_stream();
16763
16763
  var util4 = __require("util");
16764
- var path2 = __require("path");
16764
+ var path3 = __require("path");
16765
16765
  var http3 = __require("http");
16766
16766
  var https2 = __require("https");
16767
16767
  var parseUrl = __require("url").parse;
16768
- var fs2 = __require("fs");
16768
+ var fs3 = __require("fs");
16769
16769
  var Stream = __require("stream").Stream;
16770
16770
  var crypto2 = __require("crypto");
16771
16771
  var mime = require_mime_types();
@@ -16832,7 +16832,7 @@ var require_form_data = __commonJS({
16832
16832
  if (value.end != void 0 && value.end != Infinity && value.start != void 0) {
16833
16833
  callback(null, value.end + 1 - (value.start ? value.start : 0));
16834
16834
  } else {
16835
- fs2.stat(value.path, function(err, stat) {
16835
+ fs3.stat(value.path, function(err, stat) {
16836
16836
  if (err) {
16837
16837
  callback(err);
16838
16838
  return;
@@ -16889,11 +16889,11 @@ var require_form_data = __commonJS({
16889
16889
  FormData3.prototype._getContentDisposition = function(value, options) {
16890
16890
  var filename;
16891
16891
  if (typeof options.filepath === "string") {
16892
- filename = path2.normalize(options.filepath).replace(/\\/g, "/");
16892
+ filename = path3.normalize(options.filepath).replace(/\\/g, "/");
16893
16893
  } else if (options.filename || value && (value.name || value.path)) {
16894
- filename = path2.basename(options.filename || value && (value.name || value.path));
16894
+ filename = path3.basename(options.filename || value && (value.name || value.path));
16895
16895
  } else if (value && value.readable && hasOwn(value, "httpVersion")) {
16896
- filename = path2.basename(value.client._httpMessage.path || "");
16896
+ filename = path3.basename(value.client._httpMessage.path || "");
16897
16897
  }
16898
16898
  if (filename) {
16899
16899
  return 'filename="' + filename + '"';
@@ -17624,7 +17624,7 @@ var require_has_flag = __commonJS({
17624
17624
  var require_supports_color = __commonJS({
17625
17625
  "../node_modules/supports-color/index.js"(exports, module) {
17626
17626
  "use strict";
17627
- var os = __require("os");
17627
+ var os2 = __require("os");
17628
17628
  var tty = __require("tty");
17629
17629
  var hasFlag = require_has_flag();
17630
17630
  var { env } = process;
@@ -17681,7 +17681,7 @@ var require_supports_color = __commonJS({
17681
17681
  return min;
17682
17682
  }
17683
17683
  if (process.platform === "win32") {
17684
- const osRelease = os.release().split(".");
17684
+ const osRelease = os2.release().split(".");
17685
17685
  if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
17686
17686
  return Number(osRelease[2]) >= 14931 ? 3 : 2;
17687
17687
  }
@@ -18437,8 +18437,8 @@ var require_follow_redirects = __commonJS({
18437
18437
 
18438
18438
  // src/index.ts
18439
18439
  import { realpathSync } from "node:fs";
18440
- import * as fs from "node:fs/promises";
18441
- import * as path from "node:path";
18440
+ import * as fs2 from "node:fs/promises";
18441
+ import * as path2 from "node:path";
18442
18442
  import { fileURLToPath } from "node:url";
18443
18443
 
18444
18444
  // ../packages/shared/dist/errors.js
@@ -19344,7 +19344,7 @@ function $constructor(name, initializer3, params) {
19344
19344
  Object.defineProperty(_, "name", { value: name });
19345
19345
  return _;
19346
19346
  }
19347
- var $brand = Symbol("zod_brand");
19347
+ var $brand = /* @__PURE__ */ Symbol("zod_brand");
19348
19348
  var $ZodAsyncError = class extends Error {
19349
19349
  constructor() {
19350
19350
  super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
@@ -19491,7 +19491,7 @@ function floatSafeRemainder(val, step) {
19491
19491
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
19492
19492
  return valInt % stepInt / 10 ** decCount;
19493
19493
  }
19494
- var EVALUATING = Symbol("evaluating");
19494
+ var EVALUATING = /* @__PURE__ */ Symbol("evaluating");
19495
19495
  function defineLazy(object3, key, getter) {
19496
19496
  let value = void 0;
19497
19497
  Object.defineProperty(object3, key, {
@@ -19536,10 +19536,10 @@ function mergeDefs(...defs) {
19536
19536
  function cloneDef(schema) {
19537
19537
  return mergeDefs(schema._zod.def);
19538
19538
  }
19539
- function getElementAtPath(obj, path2) {
19540
- if (!path2)
19539
+ function getElementAtPath(obj, path3) {
19540
+ if (!path3)
19541
19541
  return obj;
19542
- return path2.reduce((acc, key) => acc?.[key], obj);
19542
+ return path3.reduce((acc, key) => acc?.[key], obj);
19543
19543
  }
19544
19544
  function promiseAllObject(promisesObj) {
19545
19545
  const keys = Object.keys(promisesObj);
@@ -19922,11 +19922,11 @@ function aborted(x, startIndex = 0) {
19922
19922
  }
19923
19923
  return false;
19924
19924
  }
19925
- function prefixIssues(path2, issues) {
19925
+ function prefixIssues(path3, issues) {
19926
19926
  return issues.map((iss) => {
19927
19927
  var _a2;
19928
19928
  (_a2 = iss).path ?? (_a2.path = []);
19929
- iss.path.unshift(path2);
19929
+ iss.path.unshift(path3);
19930
19930
  return iss;
19931
19931
  });
19932
19932
  }
@@ -20109,7 +20109,7 @@ function formatError(error48, mapper = (issue2) => issue2.message) {
20109
20109
  }
20110
20110
  function treeifyError(error48, mapper = (issue2) => issue2.message) {
20111
20111
  const result = { errors: [] };
20112
- const processError = (error49, path2 = []) => {
20112
+ const processError = (error49, path3 = []) => {
20113
20113
  var _a2, _b;
20114
20114
  for (const issue2 of error49.issues) {
20115
20115
  if (issue2.code === "invalid_union" && issue2.errors.length) {
@@ -20119,7 +20119,7 @@ function treeifyError(error48, mapper = (issue2) => issue2.message) {
20119
20119
  } else if (issue2.code === "invalid_element") {
20120
20120
  processError({ issues: issue2.issues }, issue2.path);
20121
20121
  } else {
20122
- const fullpath = [...path2, ...issue2.path];
20122
+ const fullpath = [...path3, ...issue2.path];
20123
20123
  if (fullpath.length === 0) {
20124
20124
  result.errors.push(mapper(issue2));
20125
20125
  continue;
@@ -20151,8 +20151,8 @@ function treeifyError(error48, mapper = (issue2) => issue2.message) {
20151
20151
  }
20152
20152
  function toDotPath(_path) {
20153
20153
  const segs = [];
20154
- const path2 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
20155
- for (const seg of path2) {
20154
+ const path3 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
20155
+ for (const seg of path3) {
20156
20156
  if (typeof seg === "number")
20157
20157
  segs.push(`[${seg}]`);
20158
20158
  else if (typeof seg === "symbol")
@@ -28564,8 +28564,8 @@ function yo_default() {
28564
28564
 
28565
28565
  // ../node_modules/zod/v4/core/registries.js
28566
28566
  var _a;
28567
- var $output = Symbol("ZodOutput");
28568
- var $input = Symbol("ZodInput");
28567
+ var $output = /* @__PURE__ */ Symbol("ZodOutput");
28568
+ var $input = /* @__PURE__ */ Symbol("ZodInput");
28569
28569
  var $ZodRegistry = class {
28570
28570
  constructor() {
28571
28571
  this._map = /* @__PURE__ */ new WeakMap();
@@ -32129,13 +32129,13 @@ function resolveRef(ref, ctx) {
32129
32129
  if (!ref.startsWith("#")) {
32130
32130
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
32131
32131
  }
32132
- const path2 = ref.slice(1).split("/").filter(Boolean);
32133
- if (path2.length === 0) {
32132
+ const path3 = ref.slice(1).split("/").filter(Boolean);
32133
+ if (path3.length === 0) {
32134
32134
  return ctx.rootSchema;
32135
32135
  }
32136
32136
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
32137
- if (path2[0] === defsKey) {
32138
- const key = path2[1];
32137
+ if (path3[0] === defsKey) {
32138
+ const key = path3[1];
32139
32139
  if (!key || !ctx.defs[key]) {
32140
32140
  throw new Error(`Reference not found: ${ref}`);
32141
32141
  }
@@ -32547,6 +32547,87 @@ var paginationSchema = z2.object({
32547
32547
  offset: z2.number().int().min(0).default(0).describe("Number of results to skip for pagination (default 0)")
32548
32548
  });
32549
32549
 
32550
+ // ../packages/shared/dist/cache.js
32551
+ import * as fs from "node:fs/promises";
32552
+ import * as path from "node:path";
32553
+ import * as os from "node:os";
32554
+ var PersistentCache = class {
32555
+ cacheDir;
32556
+ memoryCache = /* @__PURE__ */ new Map();
32557
+ constructor(namespace) {
32558
+ const baseDir = process.env.FRE4X_CACHE_DIR || path.join(os.homedir(), ".fre4x-cache");
32559
+ this.cacheDir = path.join(baseDir, namespace);
32560
+ }
32561
+ async ensureDir() {
32562
+ await fs.mkdir(this.cacheDir, { recursive: true });
32563
+ }
32564
+ getFilePath(key) {
32565
+ const safeKey = Buffer.from(key).toString("hex").slice(0, 64);
32566
+ return path.join(this.cacheDir, `${safeKey}.json`);
32567
+ }
32568
+ async get(key) {
32569
+ const now = Date.now();
32570
+ const memEntry = this.memoryCache.get(key);
32571
+ if (memEntry) {
32572
+ if (now - memEntry.timestamp < memEntry.ttlMs) {
32573
+ return memEntry.data;
32574
+ }
32575
+ this.memoryCache.delete(key);
32576
+ }
32577
+ const fpath = this.getFilePath(key);
32578
+ try {
32579
+ const raw = await fs.readFile(fpath, "utf8");
32580
+ const entry = JSON.parse(raw);
32581
+ if (now - entry.timestamp < entry.ttlMs) {
32582
+ this.memoryCache.set(key, entry);
32583
+ return entry.data;
32584
+ }
32585
+ await fs.unlink(fpath).catch(() => {
32586
+ });
32587
+ } catch {
32588
+ }
32589
+ return null;
32590
+ }
32591
+ async set(key, data, ttlMs) {
32592
+ const entry = {
32593
+ data,
32594
+ timestamp: Date.now(),
32595
+ ttlMs
32596
+ };
32597
+ this.memoryCache.set(key, entry);
32598
+ try {
32599
+ await this.ensureDir();
32600
+ const fpath = this.getFilePath(key);
32601
+ await fs.writeFile(fpath, JSON.stringify(entry), "utf8");
32602
+ } catch (error48) {
32603
+ console.error(`[Cache] Failed to save to disk: ${error48}`);
32604
+ }
32605
+ }
32606
+ async wrap(key, ttlMs, fetchFn) {
32607
+ const cached2 = await this.get(key);
32608
+ if (cached2 !== null)
32609
+ return cached2;
32610
+ const data = await fetchFn();
32611
+ await this.set(key, data, ttlMs);
32612
+ return data;
32613
+ }
32614
+ async clear() {
32615
+ this.memoryCache.clear();
32616
+ try {
32617
+ await fs.rm(this.cacheDir, { recursive: true, force: true });
32618
+ } catch {
32619
+ }
32620
+ }
32621
+ };
32622
+
32623
+ // ../packages/shared/dist/package.js
32624
+ import { createRequire as createJsonRequire } from "node:module";
32625
+ function getPackageVersion(moduleUrl) {
32626
+ const require2 = createJsonRequire(moduleUrl);
32627
+ const packageJson = require2("../package.json");
32628
+ return packageJson.version ?? "0.0.0";
32629
+ }
32630
+
32550
32631
  // ../node_modules/zod/v3/helpers/util.js
32551
32632
  var util;
32552
32633
  (function(util4) {
@@ -32906,8 +32987,8 @@ function getErrorMap2() {
32906
32987
 
32907
32988
  // ../node_modules/zod/v3/helpers/parseUtil.js
32908
32989
  var makeIssue = (params) => {
32909
- const { data, path: path2, errorMaps, issueData } = params;
32910
- const fullPath = [...path2, ...issueData.path || []];
32990
+ const { data, path: path3, errorMaps, issueData } = params;
32991
+ const fullPath = [...path3, ...issueData.path || []];
32911
32992
  const fullIssue = {
32912
32993
  ...issueData,
32913
32994
  path: fullPath
@@ -33022,11 +33103,11 @@ var errorUtil;
33022
33103
 
33023
33104
  // ../node_modules/zod/v3/types.js
33024
33105
  var ParseInputLazyPath = class {
33025
- constructor(parent, value, path2, key) {
33106
+ constructor(parent, value, path3, key) {
33026
33107
  this._cachedPath = [];
33027
33108
  this.parent = parent;
33028
33109
  this.data = value;
33029
- this._path = path2;
33110
+ this._path = path3;
33030
33111
  this._key = key;
33031
33112
  }
33032
33113
  get path() {
@@ -36255,7 +36336,6 @@ ZodNaN2.create = (params) => {
36255
36336
  ...processCreateParams(params)
36256
36337
  });
36257
36338
  };
36258
- var BRAND = Symbol("zod_brand");
36259
36339
  var ZodBranded = class extends ZodType2 {
36260
36340
  _parse(input) {
36261
36341
  const { ctx } = this._processInputParams(input);
@@ -36424,11 +36504,67 @@ var nullableType = ZodNullable2.create;
36424
36504
  var preprocessType = ZodEffects.createWithPreprocess;
36425
36505
  var pipelineType = ZodPipeline.create;
36426
36506
 
36507
+ // ../node_modules/zod/v4/mini/schemas.js
36508
+ var ZodMiniType = /* @__PURE__ */ $constructor("ZodMiniType", (inst, def) => {
36509
+ if (!inst._zod)
36510
+ throw new Error("Uninitialized schema in ZodMiniType.");
36511
+ $ZodType.init(inst, def);
36512
+ inst.def = def;
36513
+ inst.type = def.type;
36514
+ inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
36515
+ inst.safeParse = (data, params) => safeParse(inst, data, params);
36516
+ inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
36517
+ inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
36518
+ inst.check = (...checks) => {
36519
+ return inst.clone({
36520
+ ...def,
36521
+ checks: [
36522
+ ...def.checks ?? [],
36523
+ ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
36524
+ ]
36525
+ }, { parent: true });
36526
+ };
36527
+ inst.with = inst.check;
36528
+ inst.clone = (_def, params) => clone(inst, _def, params);
36529
+ inst.brand = () => inst;
36530
+ inst.register = ((reg, meta3) => {
36531
+ reg.add(inst, meta3);
36532
+ return inst;
36533
+ });
36534
+ inst.apply = (fn) => fn(inst);
36535
+ });
36536
+ var ZodMiniObject = /* @__PURE__ */ $constructor("ZodMiniObject", (inst, def) => {
36537
+ $ZodObject.init(inst, def);
36538
+ ZodMiniType.init(inst, def);
36539
+ defineLazy(inst, "shape", () => def.shape);
36540
+ });
36541
+ // @__NO_SIDE_EFFECTS__
36542
+ function object2(shape, params) {
36543
+ const def = {
36544
+ type: "object",
36545
+ shape: shape ?? {},
36546
+ ...normalizeParams(params)
36547
+ };
36548
+ return new ZodMiniObject(def);
36549
+ }
36550
+
36427
36551
  // ../node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
36428
36552
  function isZ4Schema(s) {
36429
36553
  const schema = s;
36430
36554
  return !!schema._zod;
36431
36555
  }
36556
+ function objectFromShape(shape) {
36557
+ const values = Object.values(shape);
36558
+ if (values.length === 0)
36559
+ return object2({});
36560
+ const allV4 = values.every(isZ4Schema);
36561
+ const allV3 = values.every((s) => !isZ4Schema(s));
36562
+ if (allV4)
36563
+ return object2(shape);
36564
+ if (allV3)
36565
+ return objectType(shape);
36566
+ throw new Error("Mixed Zod versions detected in object shape.");
36567
+ }
36432
36568
  function safeParse3(schema, data) {
36433
36569
  if (isZ4Schema(schema)) {
36434
36570
  const result2 = safeParse(schema, data);
@@ -36438,6 +36574,15 @@ function safeParse3(schema, data) {
36438
36574
  const result = v3Schema.safeParse(data);
36439
36575
  return result;
36440
36576
  }
36577
+ async function safeParseAsync3(schema, data) {
36578
+ if (isZ4Schema(schema)) {
36579
+ const result2 = await safeParseAsync(schema, data);
36580
+ return result2;
36581
+ }
36582
+ const v3Schema = schema;
36583
+ const result = await v3Schema.safeParseAsync(data);
36584
+ return result;
36585
+ }
36441
36586
  function getObjectShape(schema) {
36442
36587
  if (!schema)
36443
36588
  return void 0;
@@ -36460,6 +36605,66 @@ function getObjectShape(schema) {
36460
36605
  }
36461
36606
  return rawShape;
36462
36607
  }
36608
+ function normalizeObjectSchema(schema) {
36609
+ if (!schema)
36610
+ return void 0;
36611
+ if (typeof schema === "object") {
36612
+ const asV3 = schema;
36613
+ const asV4 = schema;
36614
+ if (!asV3._def && !asV4._zod) {
36615
+ const values = Object.values(schema);
36616
+ if (values.length > 0 && values.every((v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function"))) {
36617
+ return objectFromShape(schema);
36618
+ }
36619
+ }
36620
+ }
36621
+ if (isZ4Schema(schema)) {
36622
+ const v4Schema = schema;
36623
+ const def = v4Schema._zod?.def;
36624
+ if (def && (def.type === "object" || def.shape !== void 0)) {
36625
+ return schema;
36626
+ }
36627
+ } else {
36628
+ const v3Schema = schema;
36629
+ if (v3Schema.shape !== void 0) {
36630
+ return schema;
36631
+ }
36632
+ }
36633
+ return void 0;
36634
+ }
36635
+ function getParseErrorMessage(error48) {
36636
+ if (error48 && typeof error48 === "object") {
36637
+ if ("message" in error48 && typeof error48.message === "string") {
36638
+ return error48.message;
36639
+ }
36640
+ if ("issues" in error48 && Array.isArray(error48.issues) && error48.issues.length > 0) {
36641
+ const firstIssue = error48.issues[0];
36642
+ if (firstIssue && typeof firstIssue === "object" && "message" in firstIssue) {
36643
+ return String(firstIssue.message);
36644
+ }
36645
+ }
36646
+ try {
36647
+ return JSON.stringify(error48);
36648
+ } catch {
36649
+ return String(error48);
36650
+ }
36651
+ }
36652
+ return String(error48);
36653
+ }
36654
+ function getSchemaDescription(schema) {
36655
+ return schema.description;
36656
+ }
36657
+ function isSchemaOptional(schema) {
36658
+ if (isZ4Schema(schema)) {
36659
+ const v4Schema = schema;
36660
+ return v4Schema._zod?.def?.type === "optional";
36661
+ }
36662
+ const v3Schema = schema;
36663
+ if (typeof schema.isOptional === "function") {
36664
+ return schema.isOptional();
36665
+ }
36666
+ return v3Schema._def?.typeName === "ZodOptional";
36667
+ }
36463
36668
  function getLiteralValue(schema) {
36464
36669
  if (isZ4Schema(schema)) {
36465
36670
  const v4Schema = schema;
@@ -37848,6 +38053,18 @@ var CompleteRequestSchema = RequestSchema.extend({
37848
38053
  method: literal("completion/complete"),
37849
38054
  params: CompleteRequestParamsSchema
37850
38055
  });
38056
+ function assertCompleteRequestPrompt(request) {
38057
+ if (request.params.ref.type !== "ref/prompt") {
38058
+ throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);
38059
+ }
38060
+ void request;
38061
+ }
38062
+ function assertCompleteRequestResourceTemplate(request) {
38063
+ if (request.params.ref.type !== "ref/resource") {
38064
+ throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);
38065
+ }
38066
+ void request;
38067
+ }
37851
38068
  var CompleteResultSchema = ResultSchema.extend({
37852
38069
  completion: looseObject({
37853
38070
  /**
@@ -37999,12 +38216,1311 @@ function isTerminal(status) {
37999
38216
  }
38000
38217
 
38001
38218
  // ../node_modules/zod-to-json-schema/dist/esm/Options.js
38002
- var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
38219
+ var ignoreOverride = /* @__PURE__ */ Symbol("Let zodToJsonSchema decide on which parser to use");
38220
+ var defaultOptions = {
38221
+ name: void 0,
38222
+ $refStrategy: "root",
38223
+ basePath: ["#"],
38224
+ effectStrategy: "input",
38225
+ pipeStrategy: "all",
38226
+ dateStrategy: "format:date-time",
38227
+ mapStrategy: "entries",
38228
+ removeAdditionalStrategy: "passthrough",
38229
+ allowedAdditionalProperties: true,
38230
+ rejectedAdditionalProperties: false,
38231
+ definitionPath: "definitions",
38232
+ target: "jsonSchema7",
38233
+ strictUnions: false,
38234
+ definitions: {},
38235
+ errorMessages: false,
38236
+ markdownDescription: false,
38237
+ patternStrategy: "escape",
38238
+ applyRegexFlags: false,
38239
+ emailStrategy: "format:email",
38240
+ base64Strategy: "contentEncoding:base64",
38241
+ nameStrategy: "ref",
38242
+ openAiAnyTypeName: "OpenAiAnyType"
38243
+ };
38244
+ var getDefaultOptions = (options) => typeof options === "string" ? {
38245
+ ...defaultOptions,
38246
+ name: options
38247
+ } : {
38248
+ ...defaultOptions,
38249
+ ...options
38250
+ };
38251
+
38252
+ // ../node_modules/zod-to-json-schema/dist/esm/Refs.js
38253
+ var getRefs = (options) => {
38254
+ const _options = getDefaultOptions(options);
38255
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
38256
+ return {
38257
+ ..._options,
38258
+ flags: { hasReferencedOpenAiAnyType: false },
38259
+ currentPath,
38260
+ propertyPath: void 0,
38261
+ seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
38262
+ def._def,
38263
+ {
38264
+ def: def._def,
38265
+ path: [..._options.basePath, _options.definitionPath, name],
38266
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
38267
+ jsonSchema: void 0
38268
+ }
38269
+ ]))
38270
+ };
38271
+ };
38272
+
38273
+ // ../node_modules/zod-to-json-schema/dist/esm/errorMessages.js
38274
+ function addErrorMessage(res, key, errorMessage, refs) {
38275
+ if (!refs?.errorMessages)
38276
+ return;
38277
+ if (errorMessage) {
38278
+ res.errorMessage = {
38279
+ ...res.errorMessage,
38280
+ [key]: errorMessage
38281
+ };
38282
+ }
38283
+ }
38284
+ function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
38285
+ res[key] = value;
38286
+ addErrorMessage(res, key, errorMessage, refs);
38287
+ }
38288
+
38289
+ // ../node_modules/zod-to-json-schema/dist/esm/getRelativePath.js
38290
+ var getRelativePath = (pathA, pathB) => {
38291
+ let i = 0;
38292
+ for (; i < pathA.length && i < pathB.length; i++) {
38293
+ if (pathA[i] !== pathB[i])
38294
+ break;
38295
+ }
38296
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
38297
+ };
38298
+
38299
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/any.js
38300
+ function parseAnyDef(refs) {
38301
+ if (refs.target !== "openAi") {
38302
+ return {};
38303
+ }
38304
+ const anyDefinitionPath = [
38305
+ ...refs.basePath,
38306
+ refs.definitionPath,
38307
+ refs.openAiAnyTypeName
38308
+ ];
38309
+ refs.flags.hasReferencedOpenAiAnyType = true;
38310
+ return {
38311
+ $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/")
38312
+ };
38313
+ }
38314
+
38315
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/array.js
38316
+ function parseArrayDef(def, refs) {
38317
+ const res = {
38318
+ type: "array"
38319
+ };
38320
+ if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind2.ZodAny) {
38321
+ res.items = parseDef(def.type._def, {
38322
+ ...refs,
38323
+ currentPath: [...refs.currentPath, "items"]
38324
+ });
38325
+ }
38326
+ if (def.minLength) {
38327
+ setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
38328
+ }
38329
+ if (def.maxLength) {
38330
+ setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
38331
+ }
38332
+ if (def.exactLength) {
38333
+ setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
38334
+ setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
38335
+ }
38336
+ return res;
38337
+ }
38338
+
38339
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
38340
+ function parseBigintDef(def, refs) {
38341
+ const res = {
38342
+ type: "integer",
38343
+ format: "int64"
38344
+ };
38345
+ if (!def.checks)
38346
+ return res;
38347
+ for (const check2 of def.checks) {
38348
+ switch (check2.kind) {
38349
+ case "min":
38350
+ if (refs.target === "jsonSchema7") {
38351
+ if (check2.inclusive) {
38352
+ setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);
38353
+ } else {
38354
+ setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs);
38355
+ }
38356
+ } else {
38357
+ if (!check2.inclusive) {
38358
+ res.exclusiveMinimum = true;
38359
+ }
38360
+ setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);
38361
+ }
38362
+ break;
38363
+ case "max":
38364
+ if (refs.target === "jsonSchema7") {
38365
+ if (check2.inclusive) {
38366
+ setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);
38367
+ } else {
38368
+ setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs);
38369
+ }
38370
+ } else {
38371
+ if (!check2.inclusive) {
38372
+ res.exclusiveMaximum = true;
38373
+ }
38374
+ setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);
38375
+ }
38376
+ break;
38377
+ case "multipleOf":
38378
+ setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs);
38379
+ break;
38380
+ }
38381
+ }
38382
+ return res;
38383
+ }
38384
+
38385
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
38386
+ function parseBooleanDef() {
38387
+ return {
38388
+ type: "boolean"
38389
+ };
38390
+ }
38391
+
38392
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
38393
+ function parseBrandedDef(_def, refs) {
38394
+ return parseDef(_def.type._def, refs);
38395
+ }
38396
+
38397
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
38398
+ var parseCatchDef = (def, refs) => {
38399
+ return parseDef(def.innerType._def, refs);
38400
+ };
38401
+
38402
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/date.js
38403
+ function parseDateDef(def, refs, overrideDateStrategy) {
38404
+ const strategy = overrideDateStrategy ?? refs.dateStrategy;
38405
+ if (Array.isArray(strategy)) {
38406
+ return {
38407
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
38408
+ };
38409
+ }
38410
+ switch (strategy) {
38411
+ case "string":
38412
+ case "format:date-time":
38413
+ return {
38414
+ type: "string",
38415
+ format: "date-time"
38416
+ };
38417
+ case "format:date":
38418
+ return {
38419
+ type: "string",
38420
+ format: "date"
38421
+ };
38422
+ case "integer":
38423
+ return integerDateParser(def, refs);
38424
+ }
38425
+ }
38426
+ var integerDateParser = (def, refs) => {
38427
+ const res = {
38428
+ type: "integer",
38429
+ format: "unix-time"
38430
+ };
38431
+ if (refs.target === "openApi3") {
38432
+ return res;
38433
+ }
38434
+ for (const check2 of def.checks) {
38435
+ switch (check2.kind) {
38436
+ case "min":
38437
+ setResponseValueAndErrors(
38438
+ res,
38439
+ "minimum",
38440
+ check2.value,
38441
+ // This is in milliseconds
38442
+ check2.message,
38443
+ refs
38444
+ );
38445
+ break;
38446
+ case "max":
38447
+ setResponseValueAndErrors(
38448
+ res,
38449
+ "maximum",
38450
+ check2.value,
38451
+ // This is in milliseconds
38452
+ check2.message,
38453
+ refs
38454
+ );
38455
+ break;
38456
+ }
38457
+ }
38458
+ return res;
38459
+ };
38460
+
38461
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/default.js
38462
+ function parseDefaultDef(_def, refs) {
38463
+ return {
38464
+ ...parseDef(_def.innerType._def, refs),
38465
+ default: _def.defaultValue()
38466
+ };
38467
+ }
38468
+
38469
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
38470
+ function parseEffectsDef(_def, refs) {
38471
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs);
38472
+ }
38473
+
38474
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
38475
+ function parseEnumDef(def) {
38476
+ return {
38477
+ type: "string",
38478
+ enum: Array.from(def.values)
38479
+ };
38480
+ }
38481
+
38482
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
38483
+ var isJsonSchema7AllOfType = (type) => {
38484
+ if ("type" in type && type.type === "string")
38485
+ return false;
38486
+ return "allOf" in type;
38487
+ };
38488
+ function parseIntersectionDef(def, refs) {
38489
+ const allOf = [
38490
+ parseDef(def.left._def, {
38491
+ ...refs,
38492
+ currentPath: [...refs.currentPath, "allOf", "0"]
38493
+ }),
38494
+ parseDef(def.right._def, {
38495
+ ...refs,
38496
+ currentPath: [...refs.currentPath, "allOf", "1"]
38497
+ })
38498
+ ].filter((x) => !!x);
38499
+ let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
38500
+ const mergedAllOf = [];
38501
+ allOf.forEach((schema) => {
38502
+ if (isJsonSchema7AllOfType(schema)) {
38503
+ mergedAllOf.push(...schema.allOf);
38504
+ if (schema.unevaluatedProperties === void 0) {
38505
+ unevaluatedProperties = void 0;
38506
+ }
38507
+ } else {
38508
+ let nestedSchema = schema;
38509
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
38510
+ const { additionalProperties, ...rest } = schema;
38511
+ nestedSchema = rest;
38512
+ } else {
38513
+ unevaluatedProperties = void 0;
38514
+ }
38515
+ mergedAllOf.push(nestedSchema);
38516
+ }
38517
+ });
38518
+ return mergedAllOf.length ? {
38519
+ allOf: mergedAllOf,
38520
+ ...unevaluatedProperties
38521
+ } : void 0;
38522
+ }
38523
+
38524
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
38525
+ function parseLiteralDef(def, refs) {
38526
+ const parsedType2 = typeof def.value;
38527
+ if (parsedType2 !== "bigint" && parsedType2 !== "number" && parsedType2 !== "boolean" && parsedType2 !== "string") {
38528
+ return {
38529
+ type: Array.isArray(def.value) ? "array" : "object"
38530
+ };
38531
+ }
38532
+ if (refs.target === "openApi3") {
38533
+ return {
38534
+ type: parsedType2 === "bigint" ? "integer" : parsedType2,
38535
+ enum: [def.value]
38536
+ };
38537
+ }
38538
+ return {
38539
+ type: parsedType2 === "bigint" ? "integer" : parsedType2,
38540
+ const: def.value
38541
+ };
38542
+ }
38003
38543
 
38004
38544
  // ../node_modules/zod-to-json-schema/dist/esm/parsers/string.js
38545
+ var emojiRegex2 = void 0;
38546
+ var zodPatterns = {
38547
+ /**
38548
+ * `c` was changed to `[cC]` to replicate /i flag
38549
+ */
38550
+ cuid: /^[cC][^\s-]{8,}$/,
38551
+ cuid2: /^[0-9a-z]+$/,
38552
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
38553
+ /**
38554
+ * `a-z` was added to replicate /i flag
38555
+ */
38556
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
38557
+ /**
38558
+ * Constructed a valid Unicode RegExp
38559
+ *
38560
+ * Lazily instantiate since this type of regex isn't supported
38561
+ * in all envs (e.g. React Native).
38562
+ *
38563
+ * See:
38564
+ * https://github.com/colinhacks/zod/issues/2433
38565
+ * Fix in Zod:
38566
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
38567
+ */
38568
+ emoji: () => {
38569
+ if (emojiRegex2 === void 0) {
38570
+ emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
38571
+ }
38572
+ return emojiRegex2;
38573
+ },
38574
+ /**
38575
+ * Unused
38576
+ */
38577
+ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
38578
+ /**
38579
+ * Unused
38580
+ */
38581
+ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
38582
+ ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
38583
+ /**
38584
+ * Unused
38585
+ */
38586
+ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
38587
+ ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
38588
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
38589
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
38590
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
38591
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
38592
+ };
38593
+ function parseStringDef(def, refs) {
38594
+ const res = {
38595
+ type: "string"
38596
+ };
38597
+ if (def.checks) {
38598
+ for (const check2 of def.checks) {
38599
+ switch (check2.kind) {
38600
+ case "min":
38601
+ setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs);
38602
+ break;
38603
+ case "max":
38604
+ setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs);
38605
+ break;
38606
+ case "email":
38607
+ switch (refs.emailStrategy) {
38608
+ case "format:email":
38609
+ addFormat(res, "email", check2.message, refs);
38610
+ break;
38611
+ case "format:idn-email":
38612
+ addFormat(res, "idn-email", check2.message, refs);
38613
+ break;
38614
+ case "pattern:zod":
38615
+ addPattern(res, zodPatterns.email, check2.message, refs);
38616
+ break;
38617
+ }
38618
+ break;
38619
+ case "url":
38620
+ addFormat(res, "uri", check2.message, refs);
38621
+ break;
38622
+ case "uuid":
38623
+ addFormat(res, "uuid", check2.message, refs);
38624
+ break;
38625
+ case "regex":
38626
+ addPattern(res, check2.regex, check2.message, refs);
38627
+ break;
38628
+ case "cuid":
38629
+ addPattern(res, zodPatterns.cuid, check2.message, refs);
38630
+ break;
38631
+ case "cuid2":
38632
+ addPattern(res, zodPatterns.cuid2, check2.message, refs);
38633
+ break;
38634
+ case "startsWith":
38635
+ addPattern(res, RegExp(`^${escapeLiteralCheckValue(check2.value, refs)}`), check2.message, refs);
38636
+ break;
38637
+ case "endsWith":
38638
+ addPattern(res, RegExp(`${escapeLiteralCheckValue(check2.value, refs)}$`), check2.message, refs);
38639
+ break;
38640
+ case "datetime":
38641
+ addFormat(res, "date-time", check2.message, refs);
38642
+ break;
38643
+ case "date":
38644
+ addFormat(res, "date", check2.message, refs);
38645
+ break;
38646
+ case "time":
38647
+ addFormat(res, "time", check2.message, refs);
38648
+ break;
38649
+ case "duration":
38650
+ addFormat(res, "duration", check2.message, refs);
38651
+ break;
38652
+ case "length":
38653
+ setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs);
38654
+ setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs);
38655
+ break;
38656
+ case "includes": {
38657
+ addPattern(res, RegExp(escapeLiteralCheckValue(check2.value, refs)), check2.message, refs);
38658
+ break;
38659
+ }
38660
+ case "ip": {
38661
+ if (check2.version !== "v6") {
38662
+ addFormat(res, "ipv4", check2.message, refs);
38663
+ }
38664
+ if (check2.version !== "v4") {
38665
+ addFormat(res, "ipv6", check2.message, refs);
38666
+ }
38667
+ break;
38668
+ }
38669
+ case "base64url":
38670
+ addPattern(res, zodPatterns.base64url, check2.message, refs);
38671
+ break;
38672
+ case "jwt":
38673
+ addPattern(res, zodPatterns.jwt, check2.message, refs);
38674
+ break;
38675
+ case "cidr": {
38676
+ if (check2.version !== "v6") {
38677
+ addPattern(res, zodPatterns.ipv4Cidr, check2.message, refs);
38678
+ }
38679
+ if (check2.version !== "v4") {
38680
+ addPattern(res, zodPatterns.ipv6Cidr, check2.message, refs);
38681
+ }
38682
+ break;
38683
+ }
38684
+ case "emoji":
38685
+ addPattern(res, zodPatterns.emoji(), check2.message, refs);
38686
+ break;
38687
+ case "ulid": {
38688
+ addPattern(res, zodPatterns.ulid, check2.message, refs);
38689
+ break;
38690
+ }
38691
+ case "base64": {
38692
+ switch (refs.base64Strategy) {
38693
+ case "format:binary": {
38694
+ addFormat(res, "binary", check2.message, refs);
38695
+ break;
38696
+ }
38697
+ case "contentEncoding:base64": {
38698
+ setResponseValueAndErrors(res, "contentEncoding", "base64", check2.message, refs);
38699
+ break;
38700
+ }
38701
+ case "pattern:zod": {
38702
+ addPattern(res, zodPatterns.base64, check2.message, refs);
38703
+ break;
38704
+ }
38705
+ }
38706
+ break;
38707
+ }
38708
+ case "nanoid": {
38709
+ addPattern(res, zodPatterns.nanoid, check2.message, refs);
38710
+ }
38711
+ case "toLowerCase":
38712
+ case "toUpperCase":
38713
+ case "trim":
38714
+ break;
38715
+ default:
38716
+ /* @__PURE__ */ ((_) => {
38717
+ })(check2);
38718
+ }
38719
+ }
38720
+ }
38721
+ return res;
38722
+ }
38723
+ function escapeLiteralCheckValue(literal2, refs) {
38724
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal2) : literal2;
38725
+ }
38005
38726
  var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
38727
+ function escapeNonAlphaNumeric(source) {
38728
+ let result = "";
38729
+ for (let i = 0; i < source.length; i++) {
38730
+ if (!ALPHA_NUMERIC.has(source[i])) {
38731
+ result += "\\";
38732
+ }
38733
+ result += source[i];
38734
+ }
38735
+ return result;
38736
+ }
38737
+ function addFormat(schema, value, message, refs) {
38738
+ if (schema.format || schema.anyOf?.some((x) => x.format)) {
38739
+ if (!schema.anyOf) {
38740
+ schema.anyOf = [];
38741
+ }
38742
+ if (schema.format) {
38743
+ schema.anyOf.push({
38744
+ format: schema.format,
38745
+ ...schema.errorMessage && refs.errorMessages && {
38746
+ errorMessage: { format: schema.errorMessage.format }
38747
+ }
38748
+ });
38749
+ delete schema.format;
38750
+ if (schema.errorMessage) {
38751
+ delete schema.errorMessage.format;
38752
+ if (Object.keys(schema.errorMessage).length === 0) {
38753
+ delete schema.errorMessage;
38754
+ }
38755
+ }
38756
+ }
38757
+ schema.anyOf.push({
38758
+ format: value,
38759
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
38760
+ });
38761
+ } else {
38762
+ setResponseValueAndErrors(schema, "format", value, message, refs);
38763
+ }
38764
+ }
38765
+ function addPattern(schema, regex, message, refs) {
38766
+ if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
38767
+ if (!schema.allOf) {
38768
+ schema.allOf = [];
38769
+ }
38770
+ if (schema.pattern) {
38771
+ schema.allOf.push({
38772
+ pattern: schema.pattern,
38773
+ ...schema.errorMessage && refs.errorMessages && {
38774
+ errorMessage: { pattern: schema.errorMessage.pattern }
38775
+ }
38776
+ });
38777
+ delete schema.pattern;
38778
+ if (schema.errorMessage) {
38779
+ delete schema.errorMessage.pattern;
38780
+ if (Object.keys(schema.errorMessage).length === 0) {
38781
+ delete schema.errorMessage;
38782
+ }
38783
+ }
38784
+ }
38785
+ schema.allOf.push({
38786
+ pattern: stringifyRegExpWithFlags(regex, refs),
38787
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
38788
+ });
38789
+ } else {
38790
+ setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
38791
+ }
38792
+ }
38793
+ function stringifyRegExpWithFlags(regex, refs) {
38794
+ if (!refs.applyRegexFlags || !regex.flags) {
38795
+ return regex.source;
38796
+ }
38797
+ const flags = {
38798
+ i: regex.flags.includes("i"),
38799
+ m: regex.flags.includes("m"),
38800
+ s: regex.flags.includes("s")
38801
+ // `.` matches newlines
38802
+ };
38803
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
38804
+ let pattern = "";
38805
+ let isEscaped = false;
38806
+ let inCharGroup = false;
38807
+ let inCharRange = false;
38808
+ for (let i = 0; i < source.length; i++) {
38809
+ if (isEscaped) {
38810
+ pattern += source[i];
38811
+ isEscaped = false;
38812
+ continue;
38813
+ }
38814
+ if (flags.i) {
38815
+ if (inCharGroup) {
38816
+ if (source[i].match(/[a-z]/)) {
38817
+ if (inCharRange) {
38818
+ pattern += source[i];
38819
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
38820
+ inCharRange = false;
38821
+ } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {
38822
+ pattern += source[i];
38823
+ inCharRange = true;
38824
+ } else {
38825
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
38826
+ }
38827
+ continue;
38828
+ }
38829
+ } else if (source[i].match(/[a-z]/)) {
38830
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
38831
+ continue;
38832
+ }
38833
+ }
38834
+ if (flags.m) {
38835
+ if (source[i] === "^") {
38836
+ pattern += `(^|(?<=[\r
38837
+ ]))`;
38838
+ continue;
38839
+ } else if (source[i] === "$") {
38840
+ pattern += `($|(?=[\r
38841
+ ]))`;
38842
+ continue;
38843
+ }
38844
+ }
38845
+ if (flags.s && source[i] === ".") {
38846
+ pattern += inCharGroup ? `${source[i]}\r
38847
+ ` : `[${source[i]}\r
38848
+ ]`;
38849
+ continue;
38850
+ }
38851
+ pattern += source[i];
38852
+ if (source[i] === "\\") {
38853
+ isEscaped = true;
38854
+ } else if (inCharGroup && source[i] === "]") {
38855
+ inCharGroup = false;
38856
+ } else if (!inCharGroup && source[i] === "[") {
38857
+ inCharGroup = true;
38858
+ }
38859
+ }
38860
+ try {
38861
+ new RegExp(pattern);
38862
+ } catch {
38863
+ console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
38864
+ return regex.source;
38865
+ }
38866
+ return pattern;
38867
+ }
38868
+
38869
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/record.js
38870
+ function parseRecordDef(def, refs) {
38871
+ if (refs.target === "openAi") {
38872
+ console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
38873
+ }
38874
+ if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodEnum) {
38875
+ return {
38876
+ type: "object",
38877
+ required: def.keyType._def.values,
38878
+ properties: def.keyType._def.values.reduce((acc, key) => ({
38879
+ ...acc,
38880
+ [key]: parseDef(def.valueType._def, {
38881
+ ...refs,
38882
+ currentPath: [...refs.currentPath, "properties", key]
38883
+ }) ?? parseAnyDef(refs)
38884
+ }), {}),
38885
+ additionalProperties: refs.rejectedAdditionalProperties
38886
+ };
38887
+ }
38888
+ const schema = {
38889
+ type: "object",
38890
+ additionalProperties: parseDef(def.valueType._def, {
38891
+ ...refs,
38892
+ currentPath: [...refs.currentPath, "additionalProperties"]
38893
+ }) ?? refs.allowedAdditionalProperties
38894
+ };
38895
+ if (refs.target === "openApi3") {
38896
+ return schema;
38897
+ }
38898
+ if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.checks?.length) {
38899
+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
38900
+ return {
38901
+ ...schema,
38902
+ propertyNames: keyType
38903
+ };
38904
+ } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodEnum) {
38905
+ return {
38906
+ ...schema,
38907
+ propertyNames: {
38908
+ enum: def.keyType._def.values
38909
+ }
38910
+ };
38911
+ } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.type._def.checks?.length) {
38912
+ const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
38913
+ return {
38914
+ ...schema,
38915
+ propertyNames: keyType
38916
+ };
38917
+ }
38918
+ return schema;
38919
+ }
38920
+
38921
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/map.js
38922
+ function parseMapDef(def, refs) {
38923
+ if (refs.mapStrategy === "record") {
38924
+ return parseRecordDef(def, refs);
38925
+ }
38926
+ const keys = parseDef(def.keyType._def, {
38927
+ ...refs,
38928
+ currentPath: [...refs.currentPath, "items", "items", "0"]
38929
+ }) || parseAnyDef(refs);
38930
+ const values = parseDef(def.valueType._def, {
38931
+ ...refs,
38932
+ currentPath: [...refs.currentPath, "items", "items", "1"]
38933
+ }) || parseAnyDef(refs);
38934
+ return {
38935
+ type: "array",
38936
+ maxItems: 125,
38937
+ items: {
38938
+ type: "array",
38939
+ items: [keys, values],
38940
+ minItems: 2,
38941
+ maxItems: 2
38942
+ }
38943
+ };
38944
+ }
38945
+
38946
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
38947
+ function parseNativeEnumDef(def) {
38948
+ const object3 = def.values;
38949
+ const actualKeys = Object.keys(def.values).filter((key) => {
38950
+ return typeof object3[object3[key]] !== "number";
38951
+ });
38952
+ const actualValues = actualKeys.map((key) => object3[key]);
38953
+ const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
38954
+ return {
38955
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
38956
+ enum: actualValues
38957
+ };
38958
+ }
38959
+
38960
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/never.js
38961
+ function parseNeverDef(refs) {
38962
+ return refs.target === "openAi" ? void 0 : {
38963
+ not: parseAnyDef({
38964
+ ...refs,
38965
+ currentPath: [...refs.currentPath, "not"]
38966
+ })
38967
+ };
38968
+ }
38969
+
38970
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/null.js
38971
+ function parseNullDef(refs) {
38972
+ return refs.target === "openApi3" ? {
38973
+ enum: ["null"],
38974
+ nullable: true
38975
+ } : {
38976
+ type: "null"
38977
+ };
38978
+ }
38979
+
38980
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/union.js
38981
+ var primitiveMappings = {
38982
+ ZodString: "string",
38983
+ ZodNumber: "number",
38984
+ ZodBigInt: "integer",
38985
+ ZodBoolean: "boolean",
38986
+ ZodNull: "null"
38987
+ };
38988
+ function parseUnionDef(def, refs) {
38989
+ if (refs.target === "openApi3")
38990
+ return asAnyOf(def, refs);
38991
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
38992
+ if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {
38993
+ const types = options.reduce((types2, x) => {
38994
+ const type = primitiveMappings[x._def.typeName];
38995
+ return type && !types2.includes(type) ? [...types2, type] : types2;
38996
+ }, []);
38997
+ return {
38998
+ type: types.length > 1 ? types : types[0]
38999
+ };
39000
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
39001
+ const types = options.reduce((acc, x) => {
39002
+ const type = typeof x._def.value;
39003
+ switch (type) {
39004
+ case "string":
39005
+ case "number":
39006
+ case "boolean":
39007
+ return [...acc, type];
39008
+ case "bigint":
39009
+ return [...acc, "integer"];
39010
+ case "object":
39011
+ if (x._def.value === null)
39012
+ return [...acc, "null"];
39013
+ case "symbol":
39014
+ case "undefined":
39015
+ case "function":
39016
+ default:
39017
+ return acc;
39018
+ }
39019
+ }, []);
39020
+ if (types.length === options.length) {
39021
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
39022
+ return {
39023
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
39024
+ enum: options.reduce((acc, x) => {
39025
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
39026
+ }, [])
39027
+ };
39028
+ }
39029
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
39030
+ return {
39031
+ type: "string",
39032
+ enum: options.reduce((acc, x) => [
39033
+ ...acc,
39034
+ ...x._def.values.filter((x2) => !acc.includes(x2))
39035
+ ], [])
39036
+ };
39037
+ }
39038
+ return asAnyOf(def, refs);
39039
+ }
39040
+ var asAnyOf = (def, refs) => {
39041
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {
39042
+ ...refs,
39043
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
39044
+ })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
39045
+ return anyOf.length ? { anyOf } : void 0;
39046
+ };
39047
+
39048
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
39049
+ function parseNullableDef(def, refs) {
39050
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
39051
+ if (refs.target === "openApi3") {
39052
+ return {
39053
+ type: primitiveMappings[def.innerType._def.typeName],
39054
+ nullable: true
39055
+ };
39056
+ }
39057
+ return {
39058
+ type: [
39059
+ primitiveMappings[def.innerType._def.typeName],
39060
+ "null"
39061
+ ]
39062
+ };
39063
+ }
39064
+ if (refs.target === "openApi3") {
39065
+ const base2 = parseDef(def.innerType._def, {
39066
+ ...refs,
39067
+ currentPath: [...refs.currentPath]
39068
+ });
39069
+ if (base2 && "$ref" in base2)
39070
+ return { allOf: [base2], nullable: true };
39071
+ return base2 && { ...base2, nullable: true };
39072
+ }
39073
+ const base = parseDef(def.innerType._def, {
39074
+ ...refs,
39075
+ currentPath: [...refs.currentPath, "anyOf", "0"]
39076
+ });
39077
+ return base && { anyOf: [base, { type: "null" }] };
39078
+ }
39079
+
39080
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/number.js
39081
+ function parseNumberDef(def, refs) {
39082
+ const res = {
39083
+ type: "number"
39084
+ };
39085
+ if (!def.checks)
39086
+ return res;
39087
+ for (const check2 of def.checks) {
39088
+ switch (check2.kind) {
39089
+ case "int":
39090
+ res.type = "integer";
39091
+ addErrorMessage(res, "type", check2.message, refs);
39092
+ break;
39093
+ case "min":
39094
+ if (refs.target === "jsonSchema7") {
39095
+ if (check2.inclusive) {
39096
+ setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);
39097
+ } else {
39098
+ setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs);
39099
+ }
39100
+ } else {
39101
+ if (!check2.inclusive) {
39102
+ res.exclusiveMinimum = true;
39103
+ }
39104
+ setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);
39105
+ }
39106
+ break;
39107
+ case "max":
39108
+ if (refs.target === "jsonSchema7") {
39109
+ if (check2.inclusive) {
39110
+ setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);
39111
+ } else {
39112
+ setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs);
39113
+ }
39114
+ } else {
39115
+ if (!check2.inclusive) {
39116
+ res.exclusiveMaximum = true;
39117
+ }
39118
+ setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);
39119
+ }
39120
+ break;
39121
+ case "multipleOf":
39122
+ setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs);
39123
+ break;
39124
+ }
39125
+ }
39126
+ return res;
39127
+ }
39128
+
39129
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/object.js
39130
+ function parseObjectDef(def, refs) {
39131
+ const forceOptionalIntoNullable = refs.target === "openAi";
39132
+ const result = {
39133
+ type: "object",
39134
+ properties: {}
39135
+ };
39136
+ const required2 = [];
39137
+ const shape = def.shape();
39138
+ for (const propName in shape) {
39139
+ let propDef = shape[propName];
39140
+ if (propDef === void 0 || propDef._def === void 0) {
39141
+ continue;
39142
+ }
39143
+ let propOptional = safeIsOptional(propDef);
39144
+ if (propOptional && forceOptionalIntoNullable) {
39145
+ if (propDef._def.typeName === "ZodOptional") {
39146
+ propDef = propDef._def.innerType;
39147
+ }
39148
+ if (!propDef.isNullable()) {
39149
+ propDef = propDef.nullable();
39150
+ }
39151
+ propOptional = false;
39152
+ }
39153
+ const parsedDef = parseDef(propDef._def, {
39154
+ ...refs,
39155
+ currentPath: [...refs.currentPath, "properties", propName],
39156
+ propertyPath: [...refs.currentPath, "properties", propName]
39157
+ });
39158
+ if (parsedDef === void 0) {
39159
+ continue;
39160
+ }
39161
+ result.properties[propName] = parsedDef;
39162
+ if (!propOptional) {
39163
+ required2.push(propName);
39164
+ }
39165
+ }
39166
+ if (required2.length) {
39167
+ result.required = required2;
39168
+ }
39169
+ const additionalProperties = decideAdditionalProperties(def, refs);
39170
+ if (additionalProperties !== void 0) {
39171
+ result.additionalProperties = additionalProperties;
39172
+ }
39173
+ return result;
39174
+ }
39175
+ function decideAdditionalProperties(def, refs) {
39176
+ if (def.catchall._def.typeName !== "ZodNever") {
39177
+ return parseDef(def.catchall._def, {
39178
+ ...refs,
39179
+ currentPath: [...refs.currentPath, "additionalProperties"]
39180
+ });
39181
+ }
39182
+ switch (def.unknownKeys) {
39183
+ case "passthrough":
39184
+ return refs.allowedAdditionalProperties;
39185
+ case "strict":
39186
+ return refs.rejectedAdditionalProperties;
39187
+ case "strip":
39188
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
39189
+ }
39190
+ }
39191
+ function safeIsOptional(schema) {
39192
+ try {
39193
+ return schema.isOptional();
39194
+ } catch {
39195
+ return true;
39196
+ }
39197
+ }
39198
+
39199
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
39200
+ var parseOptionalDef = (def, refs) => {
39201
+ if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
39202
+ return parseDef(def.innerType._def, refs);
39203
+ }
39204
+ const innerSchema = parseDef(def.innerType._def, {
39205
+ ...refs,
39206
+ currentPath: [...refs.currentPath, "anyOf", "1"]
39207
+ });
39208
+ return innerSchema ? {
39209
+ anyOf: [
39210
+ {
39211
+ not: parseAnyDef(refs)
39212
+ },
39213
+ innerSchema
39214
+ ]
39215
+ } : parseAnyDef(refs);
39216
+ };
39217
+
39218
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
39219
+ var parsePipelineDef = (def, refs) => {
39220
+ if (refs.pipeStrategy === "input") {
39221
+ return parseDef(def.in._def, refs);
39222
+ } else if (refs.pipeStrategy === "output") {
39223
+ return parseDef(def.out._def, refs);
39224
+ }
39225
+ const a = parseDef(def.in._def, {
39226
+ ...refs,
39227
+ currentPath: [...refs.currentPath, "allOf", "0"]
39228
+ });
39229
+ const b = parseDef(def.out._def, {
39230
+ ...refs,
39231
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
39232
+ });
39233
+ return {
39234
+ allOf: [a, b].filter((x) => x !== void 0)
39235
+ };
39236
+ };
39237
+
39238
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
39239
+ function parsePromiseDef(def, refs) {
39240
+ return parseDef(def.type._def, refs);
39241
+ }
39242
+
39243
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/set.js
39244
+ function parseSetDef(def, refs) {
39245
+ const items = parseDef(def.valueType._def, {
39246
+ ...refs,
39247
+ currentPath: [...refs.currentPath, "items"]
39248
+ });
39249
+ const schema = {
39250
+ type: "array",
39251
+ uniqueItems: true,
39252
+ items
39253
+ };
39254
+ if (def.minSize) {
39255
+ setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
39256
+ }
39257
+ if (def.maxSize) {
39258
+ setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
39259
+ }
39260
+ return schema;
39261
+ }
39262
+
39263
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
39264
+ function parseTupleDef(def, refs) {
39265
+ if (def.rest) {
39266
+ return {
39267
+ type: "array",
39268
+ minItems: def.items.length,
39269
+ items: def.items.map((x, i) => parseDef(x._def, {
39270
+ ...refs,
39271
+ currentPath: [...refs.currentPath, "items", `${i}`]
39272
+ })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),
39273
+ additionalItems: parseDef(def.rest._def, {
39274
+ ...refs,
39275
+ currentPath: [...refs.currentPath, "additionalItems"]
39276
+ })
39277
+ };
39278
+ } else {
39279
+ return {
39280
+ type: "array",
39281
+ minItems: def.items.length,
39282
+ maxItems: def.items.length,
39283
+ items: def.items.map((x, i) => parseDef(x._def, {
39284
+ ...refs,
39285
+ currentPath: [...refs.currentPath, "items", `${i}`]
39286
+ })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])
39287
+ };
39288
+ }
39289
+ }
39290
+
39291
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
39292
+ function parseUndefinedDef(refs) {
39293
+ return {
39294
+ not: parseAnyDef(refs)
39295
+ };
39296
+ }
39297
+
39298
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
39299
+ function parseUnknownDef(refs) {
39300
+ return parseAnyDef(refs);
39301
+ }
39302
+
39303
+ // ../node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
39304
+ var parseReadonlyDef = (def, refs) => {
39305
+ return parseDef(def.innerType._def, refs);
39306
+ };
39307
+
39308
+ // ../node_modules/zod-to-json-schema/dist/esm/selectParser.js
39309
+ var selectParser = (def, typeName, refs) => {
39310
+ switch (typeName) {
39311
+ case ZodFirstPartyTypeKind2.ZodString:
39312
+ return parseStringDef(def, refs);
39313
+ case ZodFirstPartyTypeKind2.ZodNumber:
39314
+ return parseNumberDef(def, refs);
39315
+ case ZodFirstPartyTypeKind2.ZodObject:
39316
+ return parseObjectDef(def, refs);
39317
+ case ZodFirstPartyTypeKind2.ZodBigInt:
39318
+ return parseBigintDef(def, refs);
39319
+ case ZodFirstPartyTypeKind2.ZodBoolean:
39320
+ return parseBooleanDef();
39321
+ case ZodFirstPartyTypeKind2.ZodDate:
39322
+ return parseDateDef(def, refs);
39323
+ case ZodFirstPartyTypeKind2.ZodUndefined:
39324
+ return parseUndefinedDef(refs);
39325
+ case ZodFirstPartyTypeKind2.ZodNull:
39326
+ return parseNullDef(refs);
39327
+ case ZodFirstPartyTypeKind2.ZodArray:
39328
+ return parseArrayDef(def, refs);
39329
+ case ZodFirstPartyTypeKind2.ZodUnion:
39330
+ case ZodFirstPartyTypeKind2.ZodDiscriminatedUnion:
39331
+ return parseUnionDef(def, refs);
39332
+ case ZodFirstPartyTypeKind2.ZodIntersection:
39333
+ return parseIntersectionDef(def, refs);
39334
+ case ZodFirstPartyTypeKind2.ZodTuple:
39335
+ return parseTupleDef(def, refs);
39336
+ case ZodFirstPartyTypeKind2.ZodRecord:
39337
+ return parseRecordDef(def, refs);
39338
+ case ZodFirstPartyTypeKind2.ZodLiteral:
39339
+ return parseLiteralDef(def, refs);
39340
+ case ZodFirstPartyTypeKind2.ZodEnum:
39341
+ return parseEnumDef(def);
39342
+ case ZodFirstPartyTypeKind2.ZodNativeEnum:
39343
+ return parseNativeEnumDef(def);
39344
+ case ZodFirstPartyTypeKind2.ZodNullable:
39345
+ return parseNullableDef(def, refs);
39346
+ case ZodFirstPartyTypeKind2.ZodOptional:
39347
+ return parseOptionalDef(def, refs);
39348
+ case ZodFirstPartyTypeKind2.ZodMap:
39349
+ return parseMapDef(def, refs);
39350
+ case ZodFirstPartyTypeKind2.ZodSet:
39351
+ return parseSetDef(def, refs);
39352
+ case ZodFirstPartyTypeKind2.ZodLazy:
39353
+ return () => def.getter()._def;
39354
+ case ZodFirstPartyTypeKind2.ZodPromise:
39355
+ return parsePromiseDef(def, refs);
39356
+ case ZodFirstPartyTypeKind2.ZodNaN:
39357
+ case ZodFirstPartyTypeKind2.ZodNever:
39358
+ return parseNeverDef(refs);
39359
+ case ZodFirstPartyTypeKind2.ZodEffects:
39360
+ return parseEffectsDef(def, refs);
39361
+ case ZodFirstPartyTypeKind2.ZodAny:
39362
+ return parseAnyDef(refs);
39363
+ case ZodFirstPartyTypeKind2.ZodUnknown:
39364
+ return parseUnknownDef(refs);
39365
+ case ZodFirstPartyTypeKind2.ZodDefault:
39366
+ return parseDefaultDef(def, refs);
39367
+ case ZodFirstPartyTypeKind2.ZodBranded:
39368
+ return parseBrandedDef(def, refs);
39369
+ case ZodFirstPartyTypeKind2.ZodReadonly:
39370
+ return parseReadonlyDef(def, refs);
39371
+ case ZodFirstPartyTypeKind2.ZodCatch:
39372
+ return parseCatchDef(def, refs);
39373
+ case ZodFirstPartyTypeKind2.ZodPipeline:
39374
+ return parsePipelineDef(def, refs);
39375
+ case ZodFirstPartyTypeKind2.ZodFunction:
39376
+ case ZodFirstPartyTypeKind2.ZodVoid:
39377
+ case ZodFirstPartyTypeKind2.ZodSymbol:
39378
+ return void 0;
39379
+ default:
39380
+ return /* @__PURE__ */ ((_) => void 0)(typeName);
39381
+ }
39382
+ };
39383
+
39384
+ // ../node_modules/zod-to-json-schema/dist/esm/parseDef.js
39385
+ function parseDef(def, refs, forceResolution = false) {
39386
+ const seenItem = refs.seen.get(def);
39387
+ if (refs.override) {
39388
+ const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
39389
+ if (overrideResult !== ignoreOverride) {
39390
+ return overrideResult;
39391
+ }
39392
+ }
39393
+ if (seenItem && !forceResolution) {
39394
+ const seenSchema = get$ref(seenItem, refs);
39395
+ if (seenSchema !== void 0) {
39396
+ return seenSchema;
39397
+ }
39398
+ }
39399
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
39400
+ refs.seen.set(def, newItem);
39401
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
39402
+ const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
39403
+ if (jsonSchema) {
39404
+ addMeta(def, refs, jsonSchema);
39405
+ }
39406
+ if (refs.postProcess) {
39407
+ const postProcessResult = refs.postProcess(jsonSchema, def, refs);
39408
+ newItem.jsonSchema = jsonSchema;
39409
+ return postProcessResult;
39410
+ }
39411
+ newItem.jsonSchema = jsonSchema;
39412
+ return jsonSchema;
39413
+ }
39414
+ var get$ref = (item, refs) => {
39415
+ switch (refs.$refStrategy) {
39416
+ case "root":
39417
+ return { $ref: item.path.join("/") };
39418
+ case "relative":
39419
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
39420
+ case "none":
39421
+ case "seen": {
39422
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
39423
+ console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
39424
+ return parseAnyDef(refs);
39425
+ }
39426
+ return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0;
39427
+ }
39428
+ }
39429
+ };
39430
+ var addMeta = (def, refs, jsonSchema) => {
39431
+ if (def.description) {
39432
+ jsonSchema.description = def.description;
39433
+ if (refs.markdownDescription) {
39434
+ jsonSchema.markdownDescription = def.description;
39435
+ }
39436
+ }
39437
+ return jsonSchema;
39438
+ };
39439
+
39440
+ // ../node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
39441
+ var zodToJsonSchema = (schema, options) => {
39442
+ const refs = getRefs(options);
39443
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({
39444
+ ...acc,
39445
+ [name2]: parseDef(schema2._def, {
39446
+ ...refs,
39447
+ currentPath: [...refs.basePath, refs.definitionPath, name2]
39448
+ }, true) ?? parseAnyDef(refs)
39449
+ }), {}) : void 0;
39450
+ const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
39451
+ const main = parseDef(schema._def, name === void 0 ? refs : {
39452
+ ...refs,
39453
+ currentPath: [...refs.basePath, refs.definitionPath, name]
39454
+ }, false) ?? parseAnyDef(refs);
39455
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
39456
+ if (title !== void 0) {
39457
+ main.title = title;
39458
+ }
39459
+ if (refs.flags.hasReferencedOpenAiAnyType) {
39460
+ if (!definitions) {
39461
+ definitions = {};
39462
+ }
39463
+ if (!definitions[refs.openAiAnyTypeName]) {
39464
+ definitions[refs.openAiAnyTypeName] = {
39465
+ // Skipping "object" as no properties can be defined and additionalProperties must be "false"
39466
+ type: ["string", "number", "integer", "boolean", "array", "null"],
39467
+ items: {
39468
+ $ref: refs.$refStrategy === "relative" ? "1" : [
39469
+ ...refs.basePath,
39470
+ refs.definitionPath,
39471
+ refs.openAiAnyTypeName
39472
+ ].join("/")
39473
+ }
39474
+ };
39475
+ }
39476
+ }
39477
+ const combined = name === void 0 ? definitions ? {
39478
+ ...main,
39479
+ [refs.definitionPath]: definitions
39480
+ } : main : {
39481
+ $ref: [
39482
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
39483
+ refs.definitionPath,
39484
+ name
39485
+ ].join("/"),
39486
+ [refs.definitionPath]: {
39487
+ ...definitions,
39488
+ [name]: main
39489
+ }
39490
+ };
39491
+ if (refs.target === "jsonSchema7") {
39492
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
39493
+ } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
39494
+ combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
39495
+ }
39496
+ if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) {
39497
+ console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
39498
+ }
39499
+ return combined;
39500
+ };
38006
39501
 
38007
39502
  // ../node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
39503
+ function mapMiniTarget(t) {
39504
+ if (!t)
39505
+ return "draft-7";
39506
+ if (t === "jsonSchema7" || t === "draft-7")
39507
+ return "draft-7";
39508
+ if (t === "jsonSchema2019-09" || t === "draft-2020-12")
39509
+ return "draft-2020-12";
39510
+ return "draft-7";
39511
+ }
39512
+ function toJsonSchemaCompat(schema, opts) {
39513
+ if (isZ4Schema(schema)) {
39514
+ return toJSONSchema(schema, {
39515
+ target: mapMiniTarget(opts?.target),
39516
+ io: opts?.pipeStrategy ?? "input"
39517
+ });
39518
+ }
39519
+ return zodToJsonSchema(schema, {
39520
+ strictUnions: opts?.strictUnions ?? true,
39521
+ pipeStrategy: opts?.pipeStrategy ?? "input"
39522
+ });
39523
+ }
38008
39524
  function getMethodLiteral(schema) {
38009
39525
  const shape = getObjectShape(schema);
38010
39526
  const methodSchema = shape?.method;
@@ -39669,6 +41185,879 @@ var Server = class extends Protocol {
39669
41185
  }
39670
41186
  };
39671
41187
 
41188
+ // ../node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js
41189
+ var COMPLETABLE_SYMBOL = /* @__PURE__ */ Symbol.for("mcp.completable");
41190
+ function isCompletable(schema) {
41191
+ return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema;
41192
+ }
41193
+ function getCompleter(schema) {
41194
+ const meta3 = schema[COMPLETABLE_SYMBOL];
41195
+ return meta3?.complete;
41196
+ }
41197
+ var McpZodTypeKind;
41198
+ (function(McpZodTypeKind2) {
41199
+ McpZodTypeKind2["Completable"] = "McpCompletable";
41200
+ })(McpZodTypeKind || (McpZodTypeKind = {}));
41201
+
41202
+ // ../node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js
41203
+ var TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/;
41204
+ function validateToolName(name) {
41205
+ const warnings = [];
41206
+ if (name.length === 0) {
41207
+ return {
41208
+ isValid: false,
41209
+ warnings: ["Tool name cannot be empty"]
41210
+ };
41211
+ }
41212
+ if (name.length > 128) {
41213
+ return {
41214
+ isValid: false,
41215
+ warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]
41216
+ };
41217
+ }
41218
+ if (name.includes(" ")) {
41219
+ warnings.push("Tool name contains spaces, which may cause parsing issues");
41220
+ }
41221
+ if (name.includes(",")) {
41222
+ warnings.push("Tool name contains commas, which may cause parsing issues");
41223
+ }
41224
+ if (name.startsWith("-") || name.endsWith("-")) {
41225
+ warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");
41226
+ }
41227
+ if (name.startsWith(".") || name.endsWith(".")) {
41228
+ warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");
41229
+ }
41230
+ if (!TOOL_NAME_REGEX.test(name)) {
41231
+ const invalidChars = name.split("").filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index);
41232
+ warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)");
41233
+ return {
41234
+ isValid: false,
41235
+ warnings
41236
+ };
41237
+ }
41238
+ return {
41239
+ isValid: true,
41240
+ warnings
41241
+ };
41242
+ }
41243
+ function issueToolNameWarning(name, warnings) {
41244
+ if (warnings.length > 0) {
41245
+ console.warn(`Tool name validation warning for "${name}":`);
41246
+ for (const warning of warnings) {
41247
+ console.warn(` - ${warning}`);
41248
+ }
41249
+ console.warn("Tool registration will proceed, but this may cause compatibility issues.");
41250
+ console.warn("Consider updating the tool name to conform to the MCP tool naming standard.");
41251
+ console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.");
41252
+ }
41253
+ }
41254
+ function validateAndWarnToolName(name) {
41255
+ const result = validateToolName(name);
41256
+ issueToolNameWarning(name, result.warnings);
41257
+ return result.isValid;
41258
+ }
41259
+
41260
+ // ../node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js
41261
+ var ExperimentalMcpServerTasks = class {
41262
+ constructor(_mcpServer) {
41263
+ this._mcpServer = _mcpServer;
41264
+ }
41265
+ registerToolTask(name, config2, handler) {
41266
+ const execution = { taskSupport: "required", ...config2.execution };
41267
+ if (execution.taskSupport === "forbidden") {
41268
+ throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`);
41269
+ }
41270
+ const mcpServerInternal = this._mcpServer;
41271
+ return mcpServerInternal._createRegisteredTool(name, config2.title, config2.description, config2.inputSchema, config2.outputSchema, config2.annotations, execution, config2._meta, handler);
41272
+ }
41273
+ };
41274
+
41275
+ // ../node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js
41276
+ var McpServer = class {
41277
+ constructor(serverInfo, options) {
41278
+ this._registeredResources = {};
41279
+ this._registeredResourceTemplates = {};
41280
+ this._registeredTools = {};
41281
+ this._registeredPrompts = {};
41282
+ this._toolHandlersInitialized = false;
41283
+ this._completionHandlerInitialized = false;
41284
+ this._resourceHandlersInitialized = false;
41285
+ this._promptHandlersInitialized = false;
41286
+ this.server = new Server(serverInfo, options);
41287
+ }
41288
+ /**
41289
+ * Access experimental features.
41290
+ *
41291
+ * WARNING: These APIs are experimental and may change without notice.
41292
+ *
41293
+ * @experimental
41294
+ */
41295
+ get experimental() {
41296
+ if (!this._experimental) {
41297
+ this._experimental = {
41298
+ tasks: new ExperimentalMcpServerTasks(this)
41299
+ };
41300
+ }
41301
+ return this._experimental;
41302
+ }
41303
+ /**
41304
+ * Attaches to the given transport, starts it, and starts listening for messages.
41305
+ *
41306
+ * The `server` 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.
41307
+ */
41308
+ async connect(transport) {
41309
+ return await this.server.connect(transport);
41310
+ }
41311
+ /**
41312
+ * Closes the connection.
41313
+ */
41314
+ async close() {
41315
+ await this.server.close();
41316
+ }
41317
+ setToolRequestHandlers() {
41318
+ if (this._toolHandlersInitialized) {
41319
+ return;
41320
+ }
41321
+ this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema));
41322
+ this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema));
41323
+ this.server.registerCapabilities({
41324
+ tools: {
41325
+ listChanged: true
41326
+ }
41327
+ });
41328
+ this.server.setRequestHandler(ListToolsRequestSchema, () => ({
41329
+ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => {
41330
+ const toolDefinition = {
41331
+ name,
41332
+ title: tool.title,
41333
+ description: tool.description,
41334
+ inputSchema: (() => {
41335
+ const obj = normalizeObjectSchema(tool.inputSchema);
41336
+ return obj ? toJsonSchemaCompat(obj, {
41337
+ strictUnions: true,
41338
+ pipeStrategy: "input"
41339
+ }) : EMPTY_OBJECT_JSON_SCHEMA;
41340
+ })(),
41341
+ annotations: tool.annotations,
41342
+ execution: tool.execution,
41343
+ _meta: tool._meta
41344
+ };
41345
+ if (tool.outputSchema) {
41346
+ const obj = normalizeObjectSchema(tool.outputSchema);
41347
+ if (obj) {
41348
+ toolDefinition.outputSchema = toJsonSchemaCompat(obj, {
41349
+ strictUnions: true,
41350
+ pipeStrategy: "output"
41351
+ });
41352
+ }
41353
+ }
41354
+ return toolDefinition;
41355
+ })
41356
+ }));
41357
+ this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
41358
+ try {
41359
+ const tool = this._registeredTools[request.params.name];
41360
+ if (!tool) {
41361
+ throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`);
41362
+ }
41363
+ if (!tool.enabled) {
41364
+ throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);
41365
+ }
41366
+ const isTaskRequest = !!request.params.task;
41367
+ const taskSupport = tool.execution?.taskSupport;
41368
+ const isTaskHandler = "createTask" in tool.handler;
41369
+ if ((taskSupport === "required" || taskSupport === "optional") && !isTaskHandler) {
41370
+ throw new McpError(ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`);
41371
+ }
41372
+ if (taskSupport === "required" && !isTaskRequest) {
41373
+ throw new McpError(ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`);
41374
+ }
41375
+ if (taskSupport === "optional" && !isTaskRequest && isTaskHandler) {
41376
+ return await this.handleAutomaticTaskPolling(tool, request, extra);
41377
+ }
41378
+ const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
41379
+ const result = await this.executeToolHandler(tool, args, extra);
41380
+ if (isTaskRequest) {
41381
+ return result;
41382
+ }
41383
+ await this.validateToolOutput(tool, result, request.params.name);
41384
+ return result;
41385
+ } catch (error48) {
41386
+ if (error48 instanceof McpError) {
41387
+ if (error48.code === ErrorCode.UrlElicitationRequired) {
41388
+ throw error48;
41389
+ }
41390
+ }
41391
+ return this.createToolError(error48 instanceof Error ? error48.message : String(error48));
41392
+ }
41393
+ });
41394
+ this._toolHandlersInitialized = true;
41395
+ }
41396
+ /**
41397
+ * Creates a tool error result.
41398
+ *
41399
+ * @param errorMessage - The error message.
41400
+ * @returns The tool error result.
41401
+ */
41402
+ createToolError(errorMessage) {
41403
+ return {
41404
+ content: [
41405
+ {
41406
+ type: "text",
41407
+ text: errorMessage
41408
+ }
41409
+ ],
41410
+ isError: true
41411
+ };
41412
+ }
41413
+ /**
41414
+ * Validates tool input arguments against the tool's input schema.
41415
+ */
41416
+ async validateToolInput(tool, args, toolName) {
41417
+ if (!tool.inputSchema) {
41418
+ return void 0;
41419
+ }
41420
+ const inputObj = normalizeObjectSchema(tool.inputSchema);
41421
+ const schemaToParse = inputObj ?? tool.inputSchema;
41422
+ const parseResult = await safeParseAsync3(schemaToParse, args);
41423
+ if (!parseResult.success) {
41424
+ const error48 = "error" in parseResult ? parseResult.error : "Unknown error";
41425
+ const errorMessage = getParseErrorMessage(error48);
41426
+ throw new McpError(ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`);
41427
+ }
41428
+ return parseResult.data;
41429
+ }
41430
+ /**
41431
+ * Validates tool output against the tool's output schema.
41432
+ */
41433
+ async validateToolOutput(tool, result, toolName) {
41434
+ if (!tool.outputSchema) {
41435
+ return;
41436
+ }
41437
+ if (!("content" in result)) {
41438
+ return;
41439
+ }
41440
+ if (result.isError) {
41441
+ return;
41442
+ }
41443
+ if (!result.structuredContent) {
41444
+ throw new McpError(ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);
41445
+ }
41446
+ const outputObj = normalizeObjectSchema(tool.outputSchema);
41447
+ const parseResult = await safeParseAsync3(outputObj, result.structuredContent);
41448
+ if (!parseResult.success) {
41449
+ const error48 = "error" in parseResult ? parseResult.error : "Unknown error";
41450
+ const errorMessage = getParseErrorMessage(error48);
41451
+ throw new McpError(ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`);
41452
+ }
41453
+ }
41454
+ /**
41455
+ * Executes a tool handler (either regular or task-based).
41456
+ */
41457
+ async executeToolHandler(tool, args, extra) {
41458
+ const handler = tool.handler;
41459
+ const isTaskHandler = "createTask" in handler;
41460
+ if (isTaskHandler) {
41461
+ if (!extra.taskStore) {
41462
+ throw new Error("No task store provided.");
41463
+ }
41464
+ const taskExtra = { ...extra, taskStore: extra.taskStore };
41465
+ if (tool.inputSchema) {
41466
+ const typedHandler = handler;
41467
+ return await Promise.resolve(typedHandler.createTask(args, taskExtra));
41468
+ } else {
41469
+ const typedHandler = handler;
41470
+ return await Promise.resolve(typedHandler.createTask(taskExtra));
41471
+ }
41472
+ }
41473
+ if (tool.inputSchema) {
41474
+ const typedHandler = handler;
41475
+ return await Promise.resolve(typedHandler(args, extra));
41476
+ } else {
41477
+ const typedHandler = handler;
41478
+ return await Promise.resolve(typedHandler(extra));
41479
+ }
41480
+ }
41481
+ /**
41482
+ * Handles automatic task polling for tools with taskSupport 'optional'.
41483
+ */
41484
+ async handleAutomaticTaskPolling(tool, request, extra) {
41485
+ if (!extra.taskStore) {
41486
+ throw new Error("No task store provided for task-capable tool.");
41487
+ }
41488
+ const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
41489
+ const handler = tool.handler;
41490
+ const taskExtra = { ...extra, taskStore: extra.taskStore };
41491
+ const createTaskResult = args ? await Promise.resolve(handler.createTask(args, taskExtra)) : (
41492
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
41493
+ await Promise.resolve(handler.createTask(taskExtra))
41494
+ );
41495
+ const taskId = createTaskResult.task.taskId;
41496
+ let task = createTaskResult.task;
41497
+ const pollInterval = task.pollInterval ?? 5e3;
41498
+ while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {
41499
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
41500
+ const updatedTask = await extra.taskStore.getTask(taskId);
41501
+ if (!updatedTask) {
41502
+ throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);
41503
+ }
41504
+ task = updatedTask;
41505
+ }
41506
+ return await extra.taskStore.getTaskResult(taskId);
41507
+ }
41508
+ setCompletionRequestHandler() {
41509
+ if (this._completionHandlerInitialized) {
41510
+ return;
41511
+ }
41512
+ this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema));
41513
+ this.server.registerCapabilities({
41514
+ completions: {}
41515
+ });
41516
+ this.server.setRequestHandler(CompleteRequestSchema, async (request) => {
41517
+ switch (request.params.ref.type) {
41518
+ case "ref/prompt":
41519
+ assertCompleteRequestPrompt(request);
41520
+ return this.handlePromptCompletion(request, request.params.ref);
41521
+ case "ref/resource":
41522
+ assertCompleteRequestResourceTemplate(request);
41523
+ return this.handleResourceCompletion(request, request.params.ref);
41524
+ default:
41525
+ throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`);
41526
+ }
41527
+ });
41528
+ this._completionHandlerInitialized = true;
41529
+ }
41530
+ async handlePromptCompletion(request, ref) {
41531
+ const prompt = this._registeredPrompts[ref.name];
41532
+ if (!prompt) {
41533
+ throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`);
41534
+ }
41535
+ if (!prompt.enabled) {
41536
+ throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`);
41537
+ }
41538
+ if (!prompt.argsSchema) {
41539
+ return EMPTY_COMPLETION_RESULT;
41540
+ }
41541
+ const promptShape = getObjectShape(prompt.argsSchema);
41542
+ const field = promptShape?.[request.params.argument.name];
41543
+ if (!isCompletable(field)) {
41544
+ return EMPTY_COMPLETION_RESULT;
41545
+ }
41546
+ const completer = getCompleter(field);
41547
+ if (!completer) {
41548
+ return EMPTY_COMPLETION_RESULT;
41549
+ }
41550
+ const suggestions = await completer(request.params.argument.value, request.params.context);
41551
+ return createCompletionResult(suggestions);
41552
+ }
41553
+ async handleResourceCompletion(request, ref) {
41554
+ const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri);
41555
+ if (!template) {
41556
+ if (this._registeredResources[ref.uri]) {
41557
+ return EMPTY_COMPLETION_RESULT;
41558
+ }
41559
+ throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`);
41560
+ }
41561
+ const completer = template.resourceTemplate.completeCallback(request.params.argument.name);
41562
+ if (!completer) {
41563
+ return EMPTY_COMPLETION_RESULT;
41564
+ }
41565
+ const suggestions = await completer(request.params.argument.value, request.params.context);
41566
+ return createCompletionResult(suggestions);
41567
+ }
41568
+ setResourceRequestHandlers() {
41569
+ if (this._resourceHandlersInitialized) {
41570
+ return;
41571
+ }
41572
+ this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema));
41573
+ this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema));
41574
+ this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema));
41575
+ this.server.registerCapabilities({
41576
+ resources: {
41577
+ listChanged: true
41578
+ }
41579
+ });
41580
+ this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => {
41581
+ const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({
41582
+ uri,
41583
+ name: resource.name,
41584
+ ...resource.metadata
41585
+ }));
41586
+ const templateResources = [];
41587
+ for (const template of Object.values(this._registeredResourceTemplates)) {
41588
+ if (!template.resourceTemplate.listCallback) {
41589
+ continue;
41590
+ }
41591
+ const result = await template.resourceTemplate.listCallback(extra);
41592
+ for (const resource of result.resources) {
41593
+ templateResources.push({
41594
+ ...template.metadata,
41595
+ // the defined resource metadata should override the template metadata if present
41596
+ ...resource
41597
+ });
41598
+ }
41599
+ }
41600
+ return { resources: [...resources, ...templateResources] };
41601
+ });
41602
+ this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {
41603
+ const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({
41604
+ name,
41605
+ uriTemplate: template.resourceTemplate.uriTemplate.toString(),
41606
+ ...template.metadata
41607
+ }));
41608
+ return { resourceTemplates };
41609
+ });
41610
+ this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {
41611
+ const uri = new URL(request.params.uri);
41612
+ const resource = this._registeredResources[uri.toString()];
41613
+ if (resource) {
41614
+ if (!resource.enabled) {
41615
+ throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`);
41616
+ }
41617
+ return resource.readCallback(uri, extra);
41618
+ }
41619
+ for (const template of Object.values(this._registeredResourceTemplates)) {
41620
+ const variables = template.resourceTemplate.uriTemplate.match(uri.toString());
41621
+ if (variables) {
41622
+ return template.readCallback(uri, variables, extra);
41623
+ }
41624
+ }
41625
+ throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`);
41626
+ });
41627
+ this._resourceHandlersInitialized = true;
41628
+ }
41629
+ setPromptRequestHandlers() {
41630
+ if (this._promptHandlersInitialized) {
41631
+ return;
41632
+ }
41633
+ this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema));
41634
+ this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema));
41635
+ this.server.registerCapabilities({
41636
+ prompts: {
41637
+ listChanged: true
41638
+ }
41639
+ });
41640
+ this.server.setRequestHandler(ListPromptsRequestSchema, () => ({
41641
+ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => {
41642
+ return {
41643
+ name,
41644
+ title: prompt.title,
41645
+ description: prompt.description,
41646
+ arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : void 0
41647
+ };
41648
+ })
41649
+ }));
41650
+ this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => {
41651
+ const prompt = this._registeredPrompts[request.params.name];
41652
+ if (!prompt) {
41653
+ throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`);
41654
+ }
41655
+ if (!prompt.enabled) {
41656
+ throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`);
41657
+ }
41658
+ if (prompt.argsSchema) {
41659
+ const argsObj = normalizeObjectSchema(prompt.argsSchema);
41660
+ const parseResult = await safeParseAsync3(argsObj, request.params.arguments);
41661
+ if (!parseResult.success) {
41662
+ const error48 = "error" in parseResult ? parseResult.error : "Unknown error";
41663
+ const errorMessage = getParseErrorMessage(error48);
41664
+ throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage}`);
41665
+ }
41666
+ const args = parseResult.data;
41667
+ const cb = prompt.callback;
41668
+ return await Promise.resolve(cb(args, extra));
41669
+ } else {
41670
+ const cb = prompt.callback;
41671
+ return await Promise.resolve(cb(extra));
41672
+ }
41673
+ });
41674
+ this._promptHandlersInitialized = true;
41675
+ }
41676
+ resource(name, uriOrTemplate, ...rest) {
41677
+ let metadata;
41678
+ if (typeof rest[0] === "object") {
41679
+ metadata = rest.shift();
41680
+ }
41681
+ const readCallback = rest[0];
41682
+ if (typeof uriOrTemplate === "string") {
41683
+ if (this._registeredResources[uriOrTemplate]) {
41684
+ throw new Error(`Resource ${uriOrTemplate} is already registered`);
41685
+ }
41686
+ const registeredResource = this._createRegisteredResource(name, void 0, uriOrTemplate, metadata, readCallback);
41687
+ this.setResourceRequestHandlers();
41688
+ this.sendResourceListChanged();
41689
+ return registeredResource;
41690
+ } else {
41691
+ if (this._registeredResourceTemplates[name]) {
41692
+ throw new Error(`Resource template ${name} is already registered`);
41693
+ }
41694
+ const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, void 0, uriOrTemplate, metadata, readCallback);
41695
+ this.setResourceRequestHandlers();
41696
+ this.sendResourceListChanged();
41697
+ return registeredResourceTemplate;
41698
+ }
41699
+ }
41700
+ registerResource(name, uriOrTemplate, config2, readCallback) {
41701
+ if (typeof uriOrTemplate === "string") {
41702
+ if (this._registeredResources[uriOrTemplate]) {
41703
+ throw new Error(`Resource ${uriOrTemplate} is already registered`);
41704
+ }
41705
+ const registeredResource = this._createRegisteredResource(name, config2.title, uriOrTemplate, config2, readCallback);
41706
+ this.setResourceRequestHandlers();
41707
+ this.sendResourceListChanged();
41708
+ return registeredResource;
41709
+ } else {
41710
+ if (this._registeredResourceTemplates[name]) {
41711
+ throw new Error(`Resource template ${name} is already registered`);
41712
+ }
41713
+ const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config2.title, uriOrTemplate, config2, readCallback);
41714
+ this.setResourceRequestHandlers();
41715
+ this.sendResourceListChanged();
41716
+ return registeredResourceTemplate;
41717
+ }
41718
+ }
41719
+ _createRegisteredResource(name, title, uri, metadata, readCallback) {
41720
+ const registeredResource = {
41721
+ name,
41722
+ title,
41723
+ metadata,
41724
+ readCallback,
41725
+ enabled: true,
41726
+ disable: () => registeredResource.update({ enabled: false }),
41727
+ enable: () => registeredResource.update({ enabled: true }),
41728
+ remove: () => registeredResource.update({ uri: null }),
41729
+ update: (updates) => {
41730
+ if (typeof updates.uri !== "undefined" && updates.uri !== uri) {
41731
+ delete this._registeredResources[uri];
41732
+ if (updates.uri)
41733
+ this._registeredResources[updates.uri] = registeredResource;
41734
+ }
41735
+ if (typeof updates.name !== "undefined")
41736
+ registeredResource.name = updates.name;
41737
+ if (typeof updates.title !== "undefined")
41738
+ registeredResource.title = updates.title;
41739
+ if (typeof updates.metadata !== "undefined")
41740
+ registeredResource.metadata = updates.metadata;
41741
+ if (typeof updates.callback !== "undefined")
41742
+ registeredResource.readCallback = updates.callback;
41743
+ if (typeof updates.enabled !== "undefined")
41744
+ registeredResource.enabled = updates.enabled;
41745
+ this.sendResourceListChanged();
41746
+ }
41747
+ };
41748
+ this._registeredResources[uri] = registeredResource;
41749
+ return registeredResource;
41750
+ }
41751
+ _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) {
41752
+ const registeredResourceTemplate = {
41753
+ resourceTemplate: template,
41754
+ title,
41755
+ metadata,
41756
+ readCallback,
41757
+ enabled: true,
41758
+ disable: () => registeredResourceTemplate.update({ enabled: false }),
41759
+ enable: () => registeredResourceTemplate.update({ enabled: true }),
41760
+ remove: () => registeredResourceTemplate.update({ name: null }),
41761
+ update: (updates) => {
41762
+ if (typeof updates.name !== "undefined" && updates.name !== name) {
41763
+ delete this._registeredResourceTemplates[name];
41764
+ if (updates.name)
41765
+ this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;
41766
+ }
41767
+ if (typeof updates.title !== "undefined")
41768
+ registeredResourceTemplate.title = updates.title;
41769
+ if (typeof updates.template !== "undefined")
41770
+ registeredResourceTemplate.resourceTemplate = updates.template;
41771
+ if (typeof updates.metadata !== "undefined")
41772
+ registeredResourceTemplate.metadata = updates.metadata;
41773
+ if (typeof updates.callback !== "undefined")
41774
+ registeredResourceTemplate.readCallback = updates.callback;
41775
+ if (typeof updates.enabled !== "undefined")
41776
+ registeredResourceTemplate.enabled = updates.enabled;
41777
+ this.sendResourceListChanged();
41778
+ }
41779
+ };
41780
+ this._registeredResourceTemplates[name] = registeredResourceTemplate;
41781
+ const variableNames = template.uriTemplate.variableNames;
41782
+ const hasCompleter = Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v));
41783
+ if (hasCompleter) {
41784
+ this.setCompletionRequestHandler();
41785
+ }
41786
+ return registeredResourceTemplate;
41787
+ }
41788
+ _createRegisteredPrompt(name, title, description, argsSchema, callback) {
41789
+ const registeredPrompt = {
41790
+ title,
41791
+ description,
41792
+ argsSchema: argsSchema === void 0 ? void 0 : objectFromShape(argsSchema),
41793
+ callback,
41794
+ enabled: true,
41795
+ disable: () => registeredPrompt.update({ enabled: false }),
41796
+ enable: () => registeredPrompt.update({ enabled: true }),
41797
+ remove: () => registeredPrompt.update({ name: null }),
41798
+ update: (updates) => {
41799
+ if (typeof updates.name !== "undefined" && updates.name !== name) {
41800
+ delete this._registeredPrompts[name];
41801
+ if (updates.name)
41802
+ this._registeredPrompts[updates.name] = registeredPrompt;
41803
+ }
41804
+ if (typeof updates.title !== "undefined")
41805
+ registeredPrompt.title = updates.title;
41806
+ if (typeof updates.description !== "undefined")
41807
+ registeredPrompt.description = updates.description;
41808
+ if (typeof updates.argsSchema !== "undefined")
41809
+ registeredPrompt.argsSchema = objectFromShape(updates.argsSchema);
41810
+ if (typeof updates.callback !== "undefined")
41811
+ registeredPrompt.callback = updates.callback;
41812
+ if (typeof updates.enabled !== "undefined")
41813
+ registeredPrompt.enabled = updates.enabled;
41814
+ this.sendPromptListChanged();
41815
+ }
41816
+ };
41817
+ this._registeredPrompts[name] = registeredPrompt;
41818
+ if (argsSchema) {
41819
+ const hasCompletable = Object.values(argsSchema).some((field) => {
41820
+ const inner = field instanceof ZodOptional ? field._def?.innerType : field;
41821
+ return isCompletable(inner);
41822
+ });
41823
+ if (hasCompletable) {
41824
+ this.setCompletionRequestHandler();
41825
+ }
41826
+ }
41827
+ return registeredPrompt;
41828
+ }
41829
+ _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) {
41830
+ validateAndWarnToolName(name);
41831
+ const registeredTool = {
41832
+ title,
41833
+ description,
41834
+ inputSchema: getZodSchemaObject(inputSchema),
41835
+ outputSchema: getZodSchemaObject(outputSchema),
41836
+ annotations,
41837
+ execution,
41838
+ _meta,
41839
+ handler,
41840
+ enabled: true,
41841
+ disable: () => registeredTool.update({ enabled: false }),
41842
+ enable: () => registeredTool.update({ enabled: true }),
41843
+ remove: () => registeredTool.update({ name: null }),
41844
+ update: (updates) => {
41845
+ if (typeof updates.name !== "undefined" && updates.name !== name) {
41846
+ if (typeof updates.name === "string") {
41847
+ validateAndWarnToolName(updates.name);
41848
+ }
41849
+ delete this._registeredTools[name];
41850
+ if (updates.name)
41851
+ this._registeredTools[updates.name] = registeredTool;
41852
+ }
41853
+ if (typeof updates.title !== "undefined")
41854
+ registeredTool.title = updates.title;
41855
+ if (typeof updates.description !== "undefined")
41856
+ registeredTool.description = updates.description;
41857
+ if (typeof updates.paramsSchema !== "undefined")
41858
+ registeredTool.inputSchema = objectFromShape(updates.paramsSchema);
41859
+ if (typeof updates.outputSchema !== "undefined")
41860
+ registeredTool.outputSchema = objectFromShape(updates.outputSchema);
41861
+ if (typeof updates.callback !== "undefined")
41862
+ registeredTool.handler = updates.callback;
41863
+ if (typeof updates.annotations !== "undefined")
41864
+ registeredTool.annotations = updates.annotations;
41865
+ if (typeof updates._meta !== "undefined")
41866
+ registeredTool._meta = updates._meta;
41867
+ if (typeof updates.enabled !== "undefined")
41868
+ registeredTool.enabled = updates.enabled;
41869
+ this.sendToolListChanged();
41870
+ }
41871
+ };
41872
+ this._registeredTools[name] = registeredTool;
41873
+ this.setToolRequestHandlers();
41874
+ this.sendToolListChanged();
41875
+ return registeredTool;
41876
+ }
41877
+ /**
41878
+ * tool() implementation. Parses arguments passed to overrides defined above.
41879
+ */
41880
+ tool(name, ...rest) {
41881
+ if (this._registeredTools[name]) {
41882
+ throw new Error(`Tool ${name} is already registered`);
41883
+ }
41884
+ let description;
41885
+ let inputSchema;
41886
+ let outputSchema;
41887
+ let annotations;
41888
+ if (typeof rest[0] === "string") {
41889
+ description = rest.shift();
41890
+ }
41891
+ if (rest.length > 1) {
41892
+ const firstArg = rest[0];
41893
+ if (isZodRawShapeCompat(firstArg)) {
41894
+ inputSchema = rest.shift();
41895
+ if (rest.length > 1 && typeof rest[0] === "object" && rest[0] !== null && !isZodRawShapeCompat(rest[0])) {
41896
+ annotations = rest.shift();
41897
+ }
41898
+ } else if (typeof firstArg === "object" && firstArg !== null) {
41899
+ annotations = rest.shift();
41900
+ }
41901
+ }
41902
+ const callback = rest[0];
41903
+ return this._createRegisteredTool(name, void 0, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, void 0, callback);
41904
+ }
41905
+ /**
41906
+ * Registers a tool with a config object and callback.
41907
+ */
41908
+ registerTool(name, config2, cb) {
41909
+ if (this._registeredTools[name]) {
41910
+ throw new Error(`Tool ${name} is already registered`);
41911
+ }
41912
+ const { title, description, inputSchema, outputSchema, annotations, _meta } = config2;
41913
+ return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, _meta, cb);
41914
+ }
41915
+ prompt(name, ...rest) {
41916
+ if (this._registeredPrompts[name]) {
41917
+ throw new Error(`Prompt ${name} is already registered`);
41918
+ }
41919
+ let description;
41920
+ if (typeof rest[0] === "string") {
41921
+ description = rest.shift();
41922
+ }
41923
+ let argsSchema;
41924
+ if (rest.length > 1) {
41925
+ argsSchema = rest.shift();
41926
+ }
41927
+ const cb = rest[0];
41928
+ const registeredPrompt = this._createRegisteredPrompt(name, void 0, description, argsSchema, cb);
41929
+ this.setPromptRequestHandlers();
41930
+ this.sendPromptListChanged();
41931
+ return registeredPrompt;
41932
+ }
41933
+ /**
41934
+ * Registers a prompt with a config object and callback.
41935
+ */
41936
+ registerPrompt(name, config2, cb) {
41937
+ if (this._registeredPrompts[name]) {
41938
+ throw new Error(`Prompt ${name} is already registered`);
41939
+ }
41940
+ const { title, description, argsSchema } = config2;
41941
+ const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb);
41942
+ this.setPromptRequestHandlers();
41943
+ this.sendPromptListChanged();
41944
+ return registeredPrompt;
41945
+ }
41946
+ /**
41947
+ * Checks if the server is connected to a transport.
41948
+ * @returns True if the server is connected
41949
+ */
41950
+ isConnected() {
41951
+ return this.server.transport !== void 0;
41952
+ }
41953
+ /**
41954
+ * Sends a logging message to the client, if connected.
41955
+ * Note: You only need to send the parameters object, not the entire JSON RPC message
41956
+ * @see LoggingMessageNotification
41957
+ * @param params
41958
+ * @param sessionId optional for stateless and backward compatibility
41959
+ */
41960
+ async sendLoggingMessage(params, sessionId) {
41961
+ return this.server.sendLoggingMessage(params, sessionId);
41962
+ }
41963
+ /**
41964
+ * Sends a resource list changed event to the client, if connected.
41965
+ */
41966
+ sendResourceListChanged() {
41967
+ if (this.isConnected()) {
41968
+ this.server.sendResourceListChanged();
41969
+ }
41970
+ }
41971
+ /**
41972
+ * Sends a tool list changed event to the client, if connected.
41973
+ */
41974
+ sendToolListChanged() {
41975
+ if (this.isConnected()) {
41976
+ this.server.sendToolListChanged();
41977
+ }
41978
+ }
41979
+ /**
41980
+ * Sends a prompt list changed event to the client, if connected.
41981
+ */
41982
+ sendPromptListChanged() {
41983
+ if (this.isConnected()) {
41984
+ this.server.sendPromptListChanged();
41985
+ }
41986
+ }
41987
+ };
41988
+ var EMPTY_OBJECT_JSON_SCHEMA = {
41989
+ type: "object",
41990
+ properties: {}
41991
+ };
41992
+ function isZodTypeLike(value) {
41993
+ return value !== null && typeof value === "object" && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
41994
+ }
41995
+ function isZodSchemaInstance(obj) {
41996
+ return "_def" in obj || "_zod" in obj || isZodTypeLike(obj);
41997
+ }
41998
+ function isZodRawShapeCompat(obj) {
41999
+ if (typeof obj !== "object" || obj === null) {
42000
+ return false;
42001
+ }
42002
+ if (isZodSchemaInstance(obj)) {
42003
+ return false;
42004
+ }
42005
+ if (Object.keys(obj).length === 0) {
42006
+ return true;
42007
+ }
42008
+ return Object.values(obj).some(isZodTypeLike);
42009
+ }
42010
+ function getZodSchemaObject(schema) {
42011
+ if (!schema) {
42012
+ return void 0;
42013
+ }
42014
+ if (isZodRawShapeCompat(schema)) {
42015
+ return objectFromShape(schema);
42016
+ }
42017
+ return schema;
42018
+ }
42019
+ function promptArgumentsFromSchema(schema) {
42020
+ const shape = getObjectShape(schema);
42021
+ if (!shape)
42022
+ return [];
42023
+ return Object.entries(shape).map(([name, field]) => {
42024
+ const description = getSchemaDescription(field);
42025
+ const isOptional = isSchemaOptional(field);
42026
+ return {
42027
+ name,
42028
+ description,
42029
+ required: !isOptional
42030
+ };
42031
+ });
42032
+ }
42033
+ function getMethodValue(schema) {
42034
+ const shape = getObjectShape(schema);
42035
+ const methodSchema = shape?.method;
42036
+ if (!methodSchema) {
42037
+ throw new Error("Schema is missing a method literal");
42038
+ }
42039
+ const value = getLiteralValue(methodSchema);
42040
+ if (typeof value === "string") {
42041
+ return value;
42042
+ }
42043
+ throw new Error("Schema method literal must be a string");
42044
+ }
42045
+ function createCompletionResult(suggestions) {
42046
+ return {
42047
+ completion: {
42048
+ values: suggestions.slice(0, 100),
42049
+ total: suggestions.length,
42050
+ hasMore: suggestions.length > 100
42051
+ }
42052
+ };
42053
+ }
42054
+ var EMPTY_COMPLETION_RESULT = {
42055
+ completion: {
42056
+ values: [],
42057
+ hasMore: false
42058
+ }
42059
+ };
42060
+
39672
42061
  // ../node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
39673
42062
  import process3 from "node:process";
39674
42063
 
@@ -39772,9 +42161,9 @@ function bind(fn, thisArg) {
39772
42161
  var { toString } = Object.prototype;
39773
42162
  var { getPrototypeOf } = Object;
39774
42163
  var { iterator, toStringTag } = Symbol;
39775
- var kindOf = /* @__PURE__ */ ((cache) => (thing) => {
42164
+ var kindOf = /* @__PURE__ */ ((cache2) => (thing) => {
39776
42165
  const str = toString.call(thing);
39777
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
42166
+ return cache2[str] || (cache2[str] = str.slice(8, -1).toLowerCase());
39778
42167
  })(/* @__PURE__ */ Object.create(null));
39779
42168
  var kindOfTest = (type) => {
39780
42169
  type = type.toLowerCase();
@@ -40281,9 +42670,9 @@ function isVisitable(thing) {
40281
42670
  function removeBrackets(key) {
40282
42671
  return utils_default.endsWith(key, "[]") ? key.slice(0, -2) : key;
40283
42672
  }
40284
- function renderKey(path2, key, dots) {
40285
- if (!path2) return key;
40286
- return path2.concat(key).map(function each(token, i) {
42673
+ function renderKey(path3, key, dots) {
42674
+ if (!path3) return key;
42675
+ return path3.concat(key).map(function each(token, i) {
40287
42676
  token = removeBrackets(token);
40288
42677
  return !dots && i ? "[" + token + "]" : token;
40289
42678
  }).join(dots ? "." : "");
@@ -40336,13 +42725,13 @@ function toFormData(obj, formData, options) {
40336
42725
  }
40337
42726
  return value;
40338
42727
  }
40339
- function defaultVisitor(value, key, path2) {
42728
+ function defaultVisitor(value, key, path3) {
40340
42729
  let arr = value;
40341
42730
  if (utils_default.isReactNative(formData) && utils_default.isReactNativeBlob(value)) {
40342
- formData.append(renderKey(path2, key, dots), convertValue(value));
42731
+ formData.append(renderKey(path3, key, dots), convertValue(value));
40343
42732
  return false;
40344
42733
  }
40345
- if (value && !path2 && typeof value === "object") {
42734
+ if (value && !path3 && typeof value === "object") {
40346
42735
  if (utils_default.endsWith(key, "{}")) {
40347
42736
  key = metaTokens ? key : key.slice(0, -2);
40348
42737
  value = JSON.stringify(value);
@@ -40361,7 +42750,7 @@ function toFormData(obj, formData, options) {
40361
42750
  if (isVisitable(value)) {
40362
42751
  return true;
40363
42752
  }
40364
- formData.append(renderKey(path2, key, dots), convertValue(value));
42753
+ formData.append(renderKey(path3, key, dots), convertValue(value));
40365
42754
  return false;
40366
42755
  }
40367
42756
  const stack = [];
@@ -40370,16 +42759,16 @@ function toFormData(obj, formData, options) {
40370
42759
  convertValue,
40371
42760
  isVisitable
40372
42761
  });
40373
- function build(value, path2) {
42762
+ function build(value, path3) {
40374
42763
  if (utils_default.isUndefined(value)) return;
40375
42764
  if (stack.indexOf(value) !== -1) {
40376
- throw Error("Circular reference detected in " + path2.join("."));
42765
+ throw Error("Circular reference detected in " + path3.join("."));
40377
42766
  }
40378
42767
  stack.push(value);
40379
42768
  utils_default.forEach(value, function each(el, key) {
40380
- const result = !(utils_default.isUndefined(el) || el === null) && visitor.call(formData, el, utils_default.isString(key) ? key.trim() : key, path2, exposedHelpers);
42769
+ const result = !(utils_default.isUndefined(el) || el === null) && visitor.call(formData, el, utils_default.isString(key) ? key.trim() : key, path3, exposedHelpers);
40381
42770
  if (result === true) {
40382
- build(el, path2 ? path2.concat(key) : [key]);
42771
+ build(el, path3 ? path3.concat(key) : [key]);
40383
42772
  }
40384
42773
  });
40385
42774
  stack.pop();
@@ -40591,7 +42980,7 @@ var platform_default = {
40591
42980
  // ../node_modules/axios/lib/helpers/toURLEncodedForm.js
40592
42981
  function toURLEncodedForm(data, options) {
40593
42982
  return toFormData_default(data, new platform_default.classes.URLSearchParams(), {
40594
- visitor: function(value, key, path2, helpers) {
42983
+ visitor: function(value, key, path3, helpers) {
40595
42984
  if (platform_default.isNode && utils_default.isBuffer(value)) {
40596
42985
  this.append(key, value.toString("base64"));
40597
42986
  return false;
@@ -40621,11 +43010,11 @@ function arrayToObject(arr) {
40621
43010
  return obj;
40622
43011
  }
40623
43012
  function formDataToJSON(formData) {
40624
- function buildPath(path2, value, target, index) {
40625
- let name = path2[index++];
43013
+ function buildPath(path3, value, target, index) {
43014
+ let name = path3[index++];
40626
43015
  if (name === "__proto__") return true;
40627
43016
  const isNumericKey = Number.isFinite(+name);
40628
- const isLast = index >= path2.length;
43017
+ const isLast = index >= path3.length;
40629
43018
  name = !name && utils_default.isArray(target) ? target.length : name;
40630
43019
  if (isLast) {
40631
43020
  if (utils_default.hasOwnProp(target, name)) {
@@ -40638,7 +43027,7 @@ function formDataToJSON(formData) {
40638
43027
  if (!target[name] || !utils_default.isObject(target[name])) {
40639
43028
  target[name] = [];
40640
43029
  }
40641
- const result = buildPath(path2, value, target[name], index);
43030
+ const result = buildPath(path3, value, target[name], index);
40642
43031
  if (result && utils_default.isArray(target[name])) {
40643
43032
  target[name] = arrayToObject(target[name]);
40644
43033
  }
@@ -40814,7 +43203,7 @@ var parseHeaders_default = (rawHeaders) => {
40814
43203
  };
40815
43204
 
40816
43205
  // ../node_modules/axios/lib/core/AxiosHeaders.js
40817
- var $internals = Symbol("internals");
43206
+ var $internals = /* @__PURE__ */ Symbol("internals");
40818
43207
  function normalizeHeader(header) {
40819
43208
  return header && String(header).trim().toLowerCase();
40820
43209
  }
@@ -41178,7 +43567,7 @@ import stream3 from "stream";
41178
43567
 
41179
43568
  // ../node_modules/axios/lib/helpers/AxiosTransformStream.js
41180
43569
  import stream from "stream";
41181
- var kInternals = Symbol("internals");
43570
+ var kInternals = /* @__PURE__ */ Symbol("internals");
41182
43571
  var AxiosTransformStream = class extends stream.Transform {
41183
43572
  constructor(options) {
41184
43573
  options = utils_default.toFlatObject(
@@ -42019,9 +44408,9 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config2) {
42019
44408
  auth = urlUsername + ":" + urlPassword;
42020
44409
  }
42021
44410
  auth && headers.delete("authorization");
42022
- let path2;
44411
+ let path3;
42023
44412
  try {
42024
- path2 = buildURL(
44413
+ path3 = buildURL(
42025
44414
  parsed.pathname + parsed.search,
42026
44415
  config2.params,
42027
44416
  config2.paramsSerializer
@@ -42039,7 +44428,7 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config2) {
42039
44428
  false
42040
44429
  );
42041
44430
  const options = {
42042
- path: path2,
44431
+ path: path3,
42043
44432
  method,
42044
44433
  headers: headers.toJSON(),
42045
44434
  agents: { http: config2.httpAgent, https: config2.httpsAgent },
@@ -42288,14 +44677,14 @@ var isURLSameOrigin_default = platform_default.hasStandardBrowserEnv ? /* @__PUR
42288
44677
  var cookies_default = platform_default.hasStandardBrowserEnv ? (
42289
44678
  // Standard browser envs support document.cookie
42290
44679
  {
42291
- write(name, value, expires, path2, domain2, secure, sameSite) {
44680
+ write(name, value, expires, path3, domain2, secure, sameSite) {
42292
44681
  if (typeof document === "undefined") return;
42293
44682
  const cookie = [`${name}=${encodeURIComponent(value)}`];
42294
44683
  if (utils_default.isNumber(expires)) {
42295
44684
  cookie.push(`expires=${new Date(expires).toUTCString()}`);
42296
44685
  }
42297
- if (utils_default.isString(path2)) {
42298
- cookie.push(`path=${path2}`);
44686
+ if (utils_default.isString(path3)) {
44687
+ cookie.push(`path=${path3}`);
42299
44688
  }
42300
44689
  if (utils_default.isString(domain2)) {
42301
44690
  cookie.push(`domain=${domain2}`);
@@ -43635,8 +46024,11 @@ var MOCK_FIXTURES = {
43635
46024
  // src/index.ts
43636
46025
  var z3 = external_exports || zod_default || zod_exports;
43637
46026
  var XAI_API_KEY = process.env.XAI_API_KEY;
46027
+ var PACKAGE_VERSION = getPackageVersion(import.meta.url);
46028
+ var GROK_SEARCH_MODEL = process.env.GROK_SEARCH_MODEL || "grok-4-1-fast-reasoning";
46029
+ var GROK_IMAGE_MODEL = process.env.GROK_IMAGE_MODEL || "grok-imagine-image";
46030
+ var GROK_VIDEO_MODEL = process.env.GROK_VIDEO_MODEL || "grok-imagine-video";
43638
46031
  var aspectRatioValues = ["1:1", "16:9", "9:16"];
43639
- var MAX_SEARCH_RESULTS = 100;
43640
46032
  var MAX_EMBEDDED_MEDIA_BYTES = Number.parseInt(
43641
46033
  process.env.GROK_MAX_EMBEDDED_MEDIA_BYTES || "5242880",
43642
46034
  10
@@ -43673,314 +46065,6 @@ var videoStatusSchema = z3.object({
43673
46065
  request_id: z3.string().min(1).max(200),
43674
46066
  output_dir: z3.string().optional()
43675
46067
  }).strict();
43676
- var TOOL_DEFINITIONS = [
43677
- {
43678
- name: "grok_search_x",
43679
- description: "Search X posts and threads via Grok.",
43680
- inputSchema: {
43681
- type: "object",
43682
- additionalProperties: false,
43683
- properties: {
43684
- query: {
43685
- type: "string",
43686
- minLength: 1,
43687
- maxLength: 500,
43688
- description: "Search query for X content"
43689
- },
43690
- allowed_handles: {
43691
- type: "array",
43692
- items: { type: "string", minLength: 1, maxLength: 50 },
43693
- maxItems: 10,
43694
- description: "Optional X handles to search"
43695
- },
43696
- from_date: {
43697
- type: "string",
43698
- format: "date-time",
43699
- description: "Optional inclusive start time"
43700
- },
43701
- to_date: {
43702
- type: "string",
43703
- format: "date-time",
43704
- description: "Optional inclusive end time"
43705
- },
43706
- limit: {
43707
- type: "integer",
43708
- minimum: 1,
43709
- maximum: MAX_SEARCH_RESULTS,
43710
- default: 20,
43711
- description: "Maximum results to return"
43712
- },
43713
- offset: {
43714
- type: "integer",
43715
- minimum: 0,
43716
- default: 0,
43717
- description: "Results to skip first"
43718
- },
43719
- output_dir: {
43720
- type: "string",
43721
- description: "Optional directory to save search results"
43722
- }
43723
- },
43724
- required: ["query"]
43725
- },
43726
- outputSchema: {
43727
- type: "object",
43728
- additionalProperties: false,
43729
- properties: {
43730
- query: { type: "string" },
43731
- summary: { type: "string" },
43732
- results: {
43733
- type: "array",
43734
- items: {
43735
- type: "object",
43736
- additionalProperties: false,
43737
- properties: {
43738
- id: { type: "string" },
43739
- text: { type: "string" },
43740
- author: { type: "string" },
43741
- created_at: { type: "string" },
43742
- url: { type: "string" }
43743
- },
43744
- required: ["text"]
43745
- }
43746
- },
43747
- citations: {
43748
- type: "array",
43749
- items: {
43750
- type: "object",
43751
- additionalProperties: false,
43752
- properties: {
43753
- url: { type: "string" },
43754
- title: { type: "string" }
43755
- },
43756
- required: ["url"]
43757
- }
43758
- },
43759
- total: { type: "integer" },
43760
- offset: { type: "integer" },
43761
- limit: { type: "integer" },
43762
- has_more: { type: "boolean" }
43763
- },
43764
- required: [
43765
- "query",
43766
- "summary",
43767
- "results",
43768
- "citations",
43769
- "total",
43770
- "offset",
43771
- "limit",
43772
- "has_more"
43773
- ]
43774
- }
43775
- },
43776
- {
43777
- name: "grok_search_web",
43778
- description: "Search the public web via Grok.",
43779
- inputSchema: {
43780
- type: "object",
43781
- additionalProperties: false,
43782
- properties: {
43783
- query: {
43784
- type: "string",
43785
- minLength: 1,
43786
- maxLength: 500,
43787
- description: "Search query for web search"
43788
- },
43789
- allowed_domains: {
43790
- type: "array",
43791
- items: { type: "string", minLength: 1, maxLength: 255 },
43792
- maxItems: 20,
43793
- description: "Optional domains to allow"
43794
- },
43795
- limit: {
43796
- type: "integer",
43797
- minimum: 1,
43798
- maximum: MAX_SEARCH_RESULTS,
43799
- default: 20,
43800
- description: "Maximum results to return"
43801
- },
43802
- offset: {
43803
- type: "integer",
43804
- minimum: 0,
43805
- default: 0,
43806
- description: "Results to skip first"
43807
- },
43808
- output_dir: {
43809
- type: "string",
43810
- description: "Optional directory to save search results"
43811
- }
43812
- },
43813
- required: ["query"]
43814
- },
43815
- outputSchema: {
43816
- type: "object",
43817
- additionalProperties: false,
43818
- properties: {
43819
- query: { type: "string" },
43820
- summary: { type: "string" },
43821
- results: {
43822
- type: "array",
43823
- items: {
43824
- type: "object",
43825
- additionalProperties: false,
43826
- properties: {
43827
- title: { type: "string" },
43828
- url: { type: "string" },
43829
- snippet: { type: "string" }
43830
- },
43831
- required: ["title", "url"]
43832
- }
43833
- },
43834
- citations: {
43835
- type: "array",
43836
- items: {
43837
- type: "object",
43838
- additionalProperties: false,
43839
- properties: {
43840
- url: { type: "string" },
43841
- title: { type: "string" }
43842
- },
43843
- required: ["url"]
43844
- }
43845
- },
43846
- total: { type: "integer" },
43847
- offset: { type: "integer" },
43848
- limit: { type: "integer" },
43849
- has_more: { type: "boolean" }
43850
- },
43851
- required: [
43852
- "query",
43853
- "summary",
43854
- "results",
43855
- "citations",
43856
- "total",
43857
- "offset",
43858
- "limit",
43859
- "has_more"
43860
- ]
43861
- }
43862
- },
43863
- {
43864
- name: "grok_imagine",
43865
- description: "Generate images from a text prompt.",
43866
- inputSchema: {
43867
- type: "object",
43868
- additionalProperties: false,
43869
- properties: {
43870
- prompt: {
43871
- type: "string",
43872
- minLength: 1,
43873
- maxLength: 2e3,
43874
- description: "Prompt for image generation"
43875
- },
43876
- aspect_ratio: {
43877
- type: "string",
43878
- enum: [...aspectRatioValues],
43879
- default: "1:1",
43880
- description: "Image aspect ratio"
43881
- },
43882
- output_dir: {
43883
- type: "string",
43884
- description: "Optional directory to save generated images"
43885
- }
43886
- },
43887
- required: ["prompt"]
43888
- },
43889
- outputSchema: {
43890
- type: "object",
43891
- additionalProperties: false,
43892
- properties: {
43893
- prompt: { type: "string" },
43894
- aspect_ratio: { type: "string" },
43895
- images: {
43896
- type: "array",
43897
- items: {
43898
- type: "object",
43899
- additionalProperties: false,
43900
- properties: {
43901
- url: { type: "string" },
43902
- revised_prompt: { type: "string" }
43903
- },
43904
- required: ["url"]
43905
- }
43906
- }
43907
- },
43908
- required: ["prompt", "aspect_ratio", "images"]
43909
- }
43910
- },
43911
- {
43912
- name: "grok_animate",
43913
- description: "Start a Grok video generation task.",
43914
- inputSchema: {
43915
- type: "object",
43916
- additionalProperties: false,
43917
- properties: {
43918
- prompt: {
43919
- type: "string",
43920
- minLength: 1,
43921
- maxLength: 2e3,
43922
- description: "Prompt for video generation"
43923
- },
43924
- image_url: {
43925
- type: "string",
43926
- format: "uri",
43927
- description: "Optional source image URL"
43928
- },
43929
- aspect_ratio: {
43930
- type: "string",
43931
- enum: [...aspectRatioValues],
43932
- default: "16:9",
43933
- description: "Video aspect ratio"
43934
- }
43935
- },
43936
- required: ["prompt"]
43937
- },
43938
- outputSchema: {
43939
- type: "object",
43940
- additionalProperties: false,
43941
- properties: {
43942
- prompt: { type: "string" },
43943
- aspect_ratio: { type: "string" },
43944
- request_id: { type: "string" },
43945
- status: { type: "string" },
43946
- image_url: { type: "string" },
43947
- video_url: { type: "string" }
43948
- },
43949
- required: ["prompt", "aspect_ratio", "request_id", "status"]
43950
- }
43951
- },
43952
- {
43953
- name: "grok_check_video_status",
43954
- description: "Check a Grok video task status.",
43955
- inputSchema: {
43956
- type: "object",
43957
- additionalProperties: false,
43958
- properties: {
43959
- request_id: {
43960
- type: "string",
43961
- minLength: 1,
43962
- maxLength: 200,
43963
- description: "Video request identifier"
43964
- },
43965
- output_dir: {
43966
- type: "string",
43967
- description: "Optional directory to save the generated video"
43968
- }
43969
- },
43970
- required: ["request_id"]
43971
- },
43972
- outputSchema: {
43973
- type: "object",
43974
- additionalProperties: false,
43975
- properties: {
43976
- request_id: { type: "string" },
43977
- status: { type: "string" },
43978
- video_url: { type: "string" }
43979
- },
43980
- required: ["request_id", "status"]
43981
- }
43982
- }
43983
- ];
43984
46068
  if (!XAI_API_KEY && !IS_MOCK) {
43985
46069
  console.error(
43986
46070
  "XAI_API_KEY environment variable is required. Set MOCK=true to run without a key."
@@ -43990,6 +46074,8 @@ if (!XAI_API_KEY && !IS_MOCK) {
43990
46074
  if (IS_MOCK) {
43991
46075
  console.error("[grok] Running in MOCK mode \u2014 no real API calls.");
43992
46076
  }
46077
+ var cache = new PersistentCache("grok");
46078
+ var SEARCH_CACHE_TTL = 30 * 60 * 1e3;
43993
46079
  var xaiClient = axios_default.create({
43994
46080
  baseURL: "https://api.x.ai/v1",
43995
46081
  headers: {
@@ -43997,16 +46083,358 @@ var xaiClient = axios_default.create({
43997
46083
  "Content-Type": "application/json"
43998
46084
  }
43999
46085
  });
44000
- var server = new Server(
44001
- {
44002
- name: "grok-mcp-server",
44003
- version: "1.0.0"
44004
- },
44005
- {
44006
- capabilities: {
44007
- tools: {}
46086
+ var server = new McpServer({
46087
+ name: "grok-mcp-server",
46088
+ version: PACKAGE_VERSION
46089
+ });
46090
+ var TOOL_DEFINITIONS = [
46091
+ { name: "grok_search_x" },
46092
+ { name: "grok_search_web" },
46093
+ { name: "grok_imagine" },
46094
+ { name: "grok_animate" },
46095
+ { name: "grok_check_video_status" }
46096
+ ];
46097
+ function getValidationResult(error48) {
46098
+ const issue2 = error48.issues[0];
46099
+ const field = issue2?.path.join(".") || "input";
46100
+ return createValidationError(field, issue2?.message || "invalid input");
46101
+ }
46102
+ async function handleGrokSearchX(params, client = xaiClient) {
46103
+ const {
46104
+ query,
46105
+ allowed_handles,
46106
+ from_date,
46107
+ to_date,
46108
+ limit,
46109
+ offset,
46110
+ output_dir
46111
+ } = params;
46112
+ try {
46113
+ if (from_date && to_date && from_date > to_date) {
46114
+ return createValidationError(
46115
+ "from_date",
46116
+ "must be earlier than or equal to to_date"
46117
+ );
46118
+ }
46119
+ const cacheKey = JSON.stringify({
46120
+ tool: "grok_search_x",
46121
+ query,
46122
+ allowed_handles,
46123
+ from_date,
46124
+ to_date
46125
+ });
46126
+ const rawResponse = await cache.wrap(
46127
+ cacheKey,
46128
+ SEARCH_CACHE_TTL,
46129
+ async () => {
46130
+ if (IS_MOCK) return MOCK_FIXTURES.grok_search_x;
46131
+ const { data } = await client.post("/responses", {
46132
+ model: GROK_SEARCH_MODEL,
46133
+ input: [{ role: "user", content: query }],
46134
+ tools: [
46135
+ {
46136
+ type: "x_search",
46137
+ x_search: {
46138
+ allowed_x_handles: allowed_handles,
46139
+ from_date,
46140
+ to_date
46141
+ }
46142
+ }
46143
+ ]
46144
+ });
46145
+ return data;
46146
+ }
46147
+ );
46148
+ const output = normalizeSearchResponse(
46149
+ rawResponse,
46150
+ query,
46151
+ limit,
46152
+ offset,
46153
+ normalizeXResults
46154
+ );
46155
+ let extraText = "";
46156
+ if (output_dir) {
46157
+ try {
46158
+ const fname = `grok-x-search-${Date.now()}.json`;
46159
+ const fpath = await saveFile(
46160
+ output_dir,
46161
+ fname,
46162
+ JSON.stringify(output, null, 2)
46163
+ );
46164
+ extraText = `
46165
+
46166
+ \u2705 Results saved to: ${fpath}`;
46167
+ } catch (error48) {
46168
+ extraText = `
46169
+
46170
+ \u26A0\uFE0F Failed to save results: ${error48.message}`;
46171
+ }
46172
+ }
46173
+ return toolResult(renderXSearch(output) + extraText, output);
46174
+ } catch (error48) {
46175
+ if (axios_default.isAxiosError(error48)) {
46176
+ return createApiError(
46177
+ isRecord(error48.response?.data) && isRecord(error48.response?.data.error) && asString(error48.response?.data.error.message) || error48.message,
46178
+ error48.response?.status
46179
+ );
46180
+ }
46181
+ return createInternalError(error48);
46182
+ }
46183
+ }
46184
+ async function handleGrokSearchWeb(params, client = xaiClient) {
46185
+ const { query, allowed_domains, limit, offset, output_dir } = params;
46186
+ try {
46187
+ const cacheKey = JSON.stringify({
46188
+ tool: "grok_search_web",
46189
+ query,
46190
+ allowed_domains
46191
+ });
46192
+ const rawResponse = await cache.wrap(
46193
+ cacheKey,
46194
+ SEARCH_CACHE_TTL,
46195
+ async () => {
46196
+ if (IS_MOCK) return MOCK_FIXTURES.grok_search_web;
46197
+ const { data } = await client.post("/responses", {
46198
+ model: GROK_SEARCH_MODEL,
46199
+ input: [
46200
+ {
46201
+ role: "user",
46202
+ content: `Search the web for: ${query}. Use the web_search tool.`
46203
+ }
46204
+ ],
46205
+ tools: [
46206
+ {
46207
+ type: "web_search",
46208
+ web_search: { allowed_domains }
46209
+ }
46210
+ ]
46211
+ });
46212
+ return data;
46213
+ }
46214
+ );
46215
+ const output = normalizeSearchResponse(
46216
+ rawResponse,
46217
+ query,
46218
+ limit,
46219
+ offset,
46220
+ normalizeWebResults
46221
+ );
46222
+ let extraText = "";
46223
+ if (output_dir) {
46224
+ try {
46225
+ const fname = `grok-web-search-${Date.now()}.json`;
46226
+ const fpath = await saveFile(
46227
+ output_dir,
46228
+ fname,
46229
+ JSON.stringify(output, null, 2)
46230
+ );
46231
+ extraText = `
46232
+
46233
+ \u2705 Results saved to: ${fpath}`;
46234
+ } catch (error48) {
46235
+ extraText = `
46236
+
46237
+ \u26A0\uFE0F Failed to save results: ${error48.message}`;
46238
+ }
46239
+ }
46240
+ return toolResult(renderWebSearch(output) + extraText, output);
46241
+ } catch (error48) {
46242
+ if (axios_default.isAxiosError(error48)) {
46243
+ return createApiError(
46244
+ isRecord(error48.response?.data) && isRecord(error48.response?.data.error) && asString(error48.response?.data.error.message) || error48.message,
46245
+ error48.response?.status
46246
+ );
46247
+ }
46248
+ return createInternalError(error48);
46249
+ }
46250
+ }
46251
+ async function handleGrokImagine(params, client = xaiClient) {
46252
+ const { prompt, aspect_ratio, output_dir } = params;
46253
+ try {
46254
+ const rawResponse = IS_MOCK ? MOCK_FIXTURES.grok_imagine : (await client.post("/images/generations", {
46255
+ model: GROK_IMAGE_MODEL,
46256
+ prompt,
46257
+ aspect_ratio,
46258
+ response_format: "url"
46259
+ })).data;
46260
+ const output = normalizeImagineResponse(
46261
+ rawResponse,
46262
+ prompt,
46263
+ aspect_ratio
46264
+ );
46265
+ const mediaResults = IS_MOCK ? [buildMockImageContent()] : (await Promise.all(
46266
+ output.images.map(
46267
+ (image) => buildImageContent(image.url, client)
46268
+ )
46269
+ )).filter(
46270
+ (item) => item !== void 0
46271
+ );
46272
+ const mediaContent = mediaResults.map((r) => r.content);
46273
+ let extraText = "";
46274
+ if (output_dir && mediaResults.length > 0) {
46275
+ try {
46276
+ const savedPaths = await Promise.all(
46277
+ mediaResults.map(
46278
+ (res, i) => saveFile(
46279
+ output_dir,
46280
+ `imagine-${Date.now()}-${i + 1}.png`,
46281
+ res.buffer
46282
+ )
46283
+ )
46284
+ );
46285
+ extraText = `
46286
+
46287
+ \u2705 Images saved to:
46288
+ ${savedPaths.join("\n")}`;
46289
+ } catch (error48) {
46290
+ extraText = `
46291
+
46292
+ \u26A0\uFE0F Failed to save images: ${error48.message}`;
46293
+ }
46294
+ }
46295
+ return toolResult(
46296
+ renderImagine(output) + extraText,
46297
+ output,
46298
+ mediaContent
46299
+ );
46300
+ } catch (error48) {
46301
+ if (axios_default.isAxiosError(error48)) {
46302
+ return createApiError(
46303
+ isRecord(error48.response?.data) && isRecord(error48.response?.data.error) && asString(error48.response?.data.error.message) || error48.message,
46304
+ error48.response?.status
46305
+ );
46306
+ }
46307
+ return createInternalError(error48);
46308
+ }
46309
+ }
46310
+ async function handleGrokAnimate(params, client = xaiClient) {
46311
+ const { prompt, image_url, aspect_ratio } = params;
46312
+ try {
46313
+ const rawResponse = IS_MOCK ? MOCK_FIXTURES.grok_animate : (await client.post("/videos/generations", {
46314
+ model: GROK_VIDEO_MODEL,
46315
+ prompt,
46316
+ image_url,
46317
+ aspect_ratio
46318
+ })).data;
46319
+ const output = normalizeVideoGenerationResponse(
46320
+ rawResponse,
46321
+ prompt,
46322
+ aspect_ratio,
46323
+ image_url
46324
+ );
46325
+ return toolResult(renderVideoGeneration(output), output);
46326
+ } catch (error48) {
46327
+ if (axios_default.isAxiosError(error48)) {
46328
+ return createApiError(
46329
+ isRecord(error48.response?.data) && isRecord(error48.response?.data.error) && asString(error48.response?.data.error.message) || error48.message,
46330
+ error48.response?.status
46331
+ );
46332
+ }
46333
+ return createInternalError(error48);
46334
+ }
46335
+ }
46336
+ async function handleGrokVideoStatus(params, client = xaiClient) {
46337
+ const { request_id, output_dir } = params;
46338
+ try {
46339
+ const rawResponse = IS_MOCK ? MOCK_FIXTURES.grok_check_video_status : (await client.get(`/videos/${request_id}`)).data;
46340
+ const output = normalizeVideoStatusResponse(rawResponse, request_id);
46341
+ let mediaContent = [];
46342
+ let extraText = "";
46343
+ if (output.video_url !== void 0) {
46344
+ const mediaRes = IS_MOCK ? buildMockVideoContent(output.video_url) : await buildVideoContent(
46345
+ output.video_url,
46346
+ client
46347
+ );
46348
+ if (mediaRes) {
46349
+ mediaContent = [mediaRes.content];
46350
+ if (output_dir) {
46351
+ try {
46352
+ const fpath = await saveFile(
46353
+ output_dir,
46354
+ `video-${Date.now()}.mp4`,
46355
+ mediaRes.buffer
46356
+ );
46357
+ extraText = `
46358
+
46359
+ \u2705 Video saved to: ${fpath}`;
46360
+ } catch (error48) {
46361
+ extraText = `
46362
+
46363
+ \u26A0\uFE0F Failed to save video: ${error48.message}`;
46364
+ }
46365
+ }
46366
+ }
46367
+ }
46368
+ return toolResult(
46369
+ renderVideoStatus(output) + extraText,
46370
+ output,
46371
+ mediaContent
46372
+ );
46373
+ } catch (error48) {
46374
+ if (axios_default.isAxiosError(error48)) {
46375
+ return createApiError(
46376
+ isRecord(error48.response?.data) && isRecord(error48.response?.data.error) && asString(error48.response?.data.error.message) || error48.message,
46377
+ error48.response?.status
46378
+ );
46379
+ }
46380
+ return createInternalError(error48);
46381
+ }
46382
+ }
46383
+ async function handleToolCall(name, args, client = xaiClient) {
46384
+ switch (name) {
46385
+ case "grok_search_x": {
46386
+ const parsed = xSearchSchema.safeParse(args);
46387
+ return parsed.success ? handleGrokSearchX(parsed.data, client) : getValidationResult(parsed.error);
46388
+ }
46389
+ case "grok_search_web": {
46390
+ const parsed = webSearchSchema.safeParse(args);
46391
+ return parsed.success ? handleGrokSearchWeb(parsed.data, client) : getValidationResult(parsed.error);
46392
+ }
46393
+ case "grok_imagine": {
46394
+ const parsed = imagineSchema.safeParse(args);
46395
+ return parsed.success ? handleGrokImagine(parsed.data, client) : getValidationResult(parsed.error);
46396
+ }
46397
+ case "grok_animate": {
46398
+ const parsed = animateSchema.safeParse(args);
46399
+ return parsed.success ? handleGrokAnimate(parsed.data, client) : getValidationResult(parsed.error);
46400
+ }
46401
+ case "grok_check_video_status": {
46402
+ const parsed = videoStatusSchema.safeParse(args);
46403
+ return parsed.success ? handleGrokVideoStatus(parsed.data, client) : getValidationResult(parsed.error);
44008
46404
  }
46405
+ default:
46406
+ throw { code: -32601, message: `Unknown tool: ${name}` };
44009
46407
  }
46408
+ }
46409
+ server.tool(
46410
+ "grok_search_x",
46411
+ "Search X posts and threads via Grok.",
46412
+ xSearchSchema.shape,
46413
+ async (args) => handleGrokSearchX(args)
46414
+ );
46415
+ server.tool(
46416
+ "grok_search_web",
46417
+ "Search the public web via Grok.",
46418
+ webSearchSchema.shape,
46419
+ async (args) => handleGrokSearchWeb(args)
46420
+ );
46421
+ server.tool(
46422
+ "grok_imagine",
46423
+ "Generate images from a text prompt.",
46424
+ imagineSchema.shape,
46425
+ async (args) => handleGrokImagine(args)
46426
+ );
46427
+ server.tool(
46428
+ "grok_animate",
46429
+ "Start a Grok video generation task.",
46430
+ animateSchema.shape,
46431
+ async (args) => handleGrokAnimate(args)
46432
+ );
46433
+ server.tool(
46434
+ "grok_check_video_status",
46435
+ "Check a Grok video task status.",
46436
+ videoStatusSchema.shape,
46437
+ async (args) => handleGrokVideoStatus(args)
44010
46438
  );
44011
46439
  function isRecord(value) {
44012
46440
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -44331,28 +46759,6 @@ function renderVideoStatus(output) {
44331
46759
  ]);
44332
46760
  return truncateToLimit(formatMarkdownSection("Grok Video Status", body));
44333
46761
  }
44334
- function parseArguments(toolName, schema, args) {
44335
- const parsed = schema.safeParse(args ?? {});
44336
- if (!parsed.success) {
44337
- const issue2 = parsed.error.issues[0];
44338
- const field = issue2?.path.length ? issue2.path.join(".") : toolName;
44339
- return {
44340
- error: createValidationError(
44341
- field,
44342
- issue2?.message || parsed.error.message
44343
- )
44344
- };
44345
- }
44346
- if (isRecord(parsed.data) && typeof parsed.data.from_date === "string" && typeof parsed.data.to_date === "string" && parsed.data.from_date > parsed.data.to_date) {
44347
- return {
44348
- error: createValidationError(
44349
- "from_date",
44350
- "must be earlier than or equal to to_date"
44351
- )
44352
- };
44353
- }
44354
- return { data: parsed.data };
44355
- }
44356
46762
  function toolResult(text, structuredContent, extraContent = []) {
44357
46763
  return {
44358
46764
  content: [
@@ -44363,9 +46769,9 @@ function toolResult(text, structuredContent, extraContent = []) {
44363
46769
  };
44364
46770
  }
44365
46771
  async function saveFile(outputDir, filename, data) {
44366
- await fs.mkdir(outputDir, { recursive: true });
44367
- const fpath = path.join(outputDir, filename);
44368
- await fs.writeFile(fpath, data);
46772
+ await fs2.mkdir(outputDir, { recursive: true });
46773
+ const fpath = path2.join(outputDir, filename);
46774
+ await fs2.writeFile(fpath, data);
44369
46775
  return fpath;
44370
46776
  }
44371
46777
  function normalizeSearchResponse(raw, query, limit, offset, normalizer) {
@@ -44440,221 +46846,6 @@ function normalizeVideoStatusResponse(raw, requestId) {
44440
46846
  video_url: extractVideoUrl(raw)
44441
46847
  };
44442
46848
  }
44443
- async function handleToolCall(name, args, client = xaiClient) {
44444
- try {
44445
- switch (name) {
44446
- case "grok_search_x": {
44447
- const parsed = parseArguments(name, xSearchSchema, args);
44448
- if ("error" in parsed) {
44449
- return parsed.error;
44450
- }
44451
- const {
44452
- query,
44453
- allowed_handles,
44454
- from_date,
44455
- to_date,
44456
- limit,
44457
- offset,
44458
- output_dir
44459
- } = parsed.data;
44460
- const rawResponse = IS_MOCK ? MOCK_FIXTURES.grok_search_x : (await client.post("/responses", {
44461
- model: "grok-4-1-fast-reasoning",
44462
- input: [{ role: "user", content: query }],
44463
- tools: [
44464
- {
44465
- type: "x_search",
44466
- x_search: {
44467
- allowed_x_handles: allowed_handles,
44468
- from_date,
44469
- to_date
44470
- }
44471
- }
44472
- ]
44473
- })).data;
44474
- const output = normalizeSearchResponse(
44475
- rawResponse,
44476
- query,
44477
- limit,
44478
- offset,
44479
- normalizeXResults
44480
- );
44481
- let extraText = "";
44482
- if (output_dir) {
44483
- const fname = `grok-x-search-${Date.now()}.json`;
44484
- const fpath = await saveFile(
44485
- output_dir,
44486
- fname,
44487
- JSON.stringify(output, null, 2)
44488
- );
44489
- extraText = `
44490
-
44491
- \u2705 Results saved to: ${fpath}`;
44492
- }
44493
- return toolResult(renderXSearch(output) + extraText, output);
44494
- }
44495
- case "grok_search_web": {
44496
- const parsed = parseArguments(name, webSearchSchema, args);
44497
- if ("error" in parsed) {
44498
- return parsed.error;
44499
- }
44500
- const { query, allowed_domains, limit, offset, output_dir } = parsed.data;
44501
- const rawResponse = IS_MOCK ? MOCK_FIXTURES.grok_search_web : (await client.post("/responses", {
44502
- model: "grok-4-1-fast-reasoning",
44503
- input: [{ role: "user", content: query }],
44504
- tools: [
44505
- {
44506
- type: "web_search",
44507
- web_search: { allowed_domains }
44508
- }
44509
- ]
44510
- })).data;
44511
- const output = normalizeSearchResponse(
44512
- rawResponse,
44513
- query,
44514
- limit,
44515
- offset,
44516
- normalizeWebResults
44517
- );
44518
- let extraText = "";
44519
- if (output_dir) {
44520
- const fname = `grok-web-search-${Date.now()}.json`;
44521
- const fpath = await saveFile(
44522
- output_dir,
44523
- fname,
44524
- JSON.stringify(output, null, 2)
44525
- );
44526
- extraText = `
44527
-
44528
- \u2705 Results saved to: ${fpath}`;
44529
- }
44530
- return toolResult(renderWebSearch(output) + extraText, output);
44531
- }
44532
- case "grok_imagine": {
44533
- const parsed = parseArguments(name, imagineSchema, args);
44534
- if ("error" in parsed) {
44535
- return parsed.error;
44536
- }
44537
- const { prompt, aspect_ratio, output_dir } = parsed.data;
44538
- const rawResponse = IS_MOCK ? MOCK_FIXTURES.grok_imagine : (await client.post("/images/generations", {
44539
- model: "grok-imagine-image",
44540
- prompt,
44541
- aspect_ratio,
44542
- response_format: "url"
44543
- })).data;
44544
- const output = normalizeImagineResponse(
44545
- rawResponse,
44546
- prompt,
44547
- aspect_ratio
44548
- );
44549
- const mediaResults = IS_MOCK ? [buildMockImageContent()] : (await Promise.all(
44550
- output.images.map(
44551
- (image) => buildImageContent(image.url, client)
44552
- )
44553
- )).filter(
44554
- (item) => item !== void 0
44555
- );
44556
- const mediaContent = mediaResults.map((r) => r.content);
44557
- let extraText = "";
44558
- if (output_dir && mediaResults.length > 0) {
44559
- const savedPaths = await Promise.all(
44560
- mediaResults.map(
44561
- (res, i) => saveFile(
44562
- output_dir,
44563
- `imagine-${Date.now()}-${i + 1}.png`,
44564
- res.buffer
44565
- )
44566
- )
44567
- );
44568
- extraText = `
44569
-
44570
- \u2705 Images saved to:
44571
- ${savedPaths.join("\n")}`;
44572
- }
44573
- return toolResult(
44574
- renderImagine(output) + extraText,
44575
- output,
44576
- mediaContent
44577
- );
44578
- }
44579
- case "grok_animate": {
44580
- const parsed = parseArguments(name, animateSchema, args);
44581
- if ("error" in parsed) {
44582
- return parsed.error;
44583
- }
44584
- const { prompt, image_url, aspect_ratio } = parsed.data;
44585
- const rawResponse = IS_MOCK ? MOCK_FIXTURES.grok_animate : (await client.post("/videos/generations", {
44586
- model: "grok-imagine-video",
44587
- prompt,
44588
- image_url,
44589
- aspect_ratio
44590
- })).data;
44591
- const output = normalizeVideoGenerationResponse(
44592
- rawResponse,
44593
- prompt,
44594
- aspect_ratio,
44595
- image_url
44596
- );
44597
- return toolResult(renderVideoGeneration(output), output);
44598
- }
44599
- case "grok_check_video_status": {
44600
- const parsed = parseArguments(name, videoStatusSchema, args);
44601
- if ("error" in parsed) {
44602
- return parsed.error;
44603
- }
44604
- const { request_id, output_dir } = parsed.data;
44605
- const rawResponse = IS_MOCK ? MOCK_FIXTURES.grok_check_video_status : (await client.get(`/videos/${request_id}`)).data;
44606
- const output = normalizeVideoStatusResponse(
44607
- rawResponse,
44608
- request_id
44609
- );
44610
- let mediaContent = [];
44611
- let extraText = "";
44612
- if (output.video_url !== void 0) {
44613
- const mediaRes = IS_MOCK ? buildMockVideoContent(output.video_url) : await buildVideoContent(output.video_url, client);
44614
- if (mediaRes) {
44615
- mediaContent = [mediaRes.content];
44616
- if (output_dir) {
44617
- const fpath = await saveFile(
44618
- output_dir,
44619
- `video-${Date.now()}.mp4`,
44620
- mediaRes.buffer
44621
- );
44622
- extraText = `
44623
-
44624
- \u2705 Video saved to: ${fpath}`;
44625
- }
44626
- }
44627
- }
44628
- return toolResult(
44629
- renderVideoStatus(output) + extraText,
44630
- output,
44631
- mediaContent
44632
- );
44633
- }
44634
- default:
44635
- throw new McpError(
44636
- ErrorCode.MethodNotFound,
44637
- `Unknown tool: ${name}`
44638
- );
44639
- }
44640
- } catch (error48) {
44641
- if (error48 instanceof McpError) {
44642
- throw error48;
44643
- }
44644
- if (axios_default.isAxiosError(error48)) {
44645
- const message = isRecord(error48.response?.data) && isRecord(error48.response?.data.error) && asString(error48.response?.data.error.message) || error48.message;
44646
- return createApiError(message, error48.response?.status);
44647
- }
44648
- return createInternalError(error48);
44649
- }
44650
- }
44651
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
44652
- tools: [...TOOL_DEFINITIONS]
44653
- }));
44654
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
44655
- const { name, arguments: args } = request.params;
44656
- return handleToolCall(name, args);
44657
- });
44658
46849
  async function runServer() {
44659
46850
  const transport = new StdioServerTransport();
44660
46851
  await server.connect(transport);
@@ -44680,7 +46871,8 @@ if (isMainModule(import.meta.url)) {
44680
46871
  export {
44681
46872
  TOOL_DEFINITIONS,
44682
46873
  handleToolCall,
44683
- runServer
46874
+ runServer,
46875
+ server
44684
46876
  };
44685
46877
  /*! Bundled license information:
44686
46878