@mastra/mcp 2.5.0 → 2.6.0-alpha.1

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 (40) hide show
  1. package/dist/cli/generate-D0K0N5WQ.js +218 -0
  2. package/dist/cli/generate-D0K0N5WQ.js.map +1 -0
  3. package/dist/cli/generate.d.ts +18 -0
  4. package/dist/cli/generate.d.ts.map +1 -0
  5. package/dist/cli/index.d.ts +3 -0
  6. package/dist/cli/index.d.ts.map +1 -0
  7. package/dist/cli/index.js +32 -0
  8. package/dist/cli/index.js.map +1 -0
  9. package/dist/cli/json-schema-dialect-CdIOPBiC.js +132 -0
  10. package/dist/cli/json-schema-dialect-CdIOPBiC.js.map +1 -0
  11. package/dist/cli/typegen-B5dH_z0t.js +363 -0
  12. package/dist/cli/typegen-B5dH_z0t.js.map +1 -0
  13. package/dist/cli/typegen.d.ts +14 -0
  14. package/dist/cli/typegen.d.ts.map +1 -0
  15. package/dist/client/client.d.ts +2 -1
  16. package/dist/client/client.d.ts.map +1 -1
  17. package/dist/client/configuration.d.ts +30 -10
  18. package/dist/client/configuration.d.ts.map +1 -1
  19. package/dist/client/index.d.ts +1 -1
  20. package/dist/client/index.d.ts.map +1 -1
  21. package/dist/client/types.d.ts +38 -1
  22. package/dist/client/types.d.ts.map +1 -1
  23. package/dist/docs/SKILL.md +2 -3
  24. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  25. package/dist/docs/references/docs-connections-mcp.md +159 -50
  26. package/dist/docs/references/docs-connections-overview.md +1 -1
  27. package/dist/docs/references/docs-guides-mcp-authentication-authorization.md +2 -2
  28. package/dist/docs/references/reference-migrations-mcp-v2.md +1 -1
  29. package/dist/docs/references/reference-tools-mcp-client.md +207 -16
  30. package/dist/docs/references/reference-tools-mcp-server.md +9 -7
  31. package/dist/index.cjs +270 -257
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.js +269 -255
  34. package/dist/index.js.map +1 -1
  35. package/dist/server/server.d.ts +13 -1
  36. package/dist/server/server.d.ts.map +1 -1
  37. package/dist/shared/json-schema-dialect.d.ts +34 -0
  38. package/dist/shared/json-schema-dialect.d.ts.map +1 -1
  39. package/package.json +25 -20
  40. package/dist/docs/references/docs-guides-mcp-events.md +0 -306
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region \0rolldown/runtime.js
2
+ // \0rolldown/runtime.js
3
3
  var __create$2 = Object.create;
4
4
  var __defProp$3 = Object.defineProperty;
5
5
  var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
@@ -20,7 +20,6 @@ var __toESM$2 = (mod, isNodeMode, target) => (target = mod != null ? __create$2(
20
20
  value: mod,
21
21
  enumerable: true
22
22
  }) : target, mod));
23
- //#endregion
24
23
  let async_hooks = require("async_hooks");
25
24
  let module$1 = require("module");
26
25
  let _mastra_core_base = require("@mastra/core/base");
@@ -54,11 +53,10 @@ let _modelcontextprotocol_server_stdio = require("@modelcontextprotocol/server/s
54
53
  let https = require("https");
55
54
  https = __toESM$2(https, 1);
56
55
  let _mastra_core_signals = require("@mastra/core/signals");
57
- //#region src/client/types.ts
56
+ // src/client/types.ts
58
57
  /** The current protocol revision; the one `/mcp` servers speak. */
59
58
  const MCP_CLIENT_PROTOCOL_VERSION = "2026-07-28";
60
- //#endregion
61
- //#region ../schema-compat/dist/json-schema-traverse-Jrimn_T_.js
59
+ // ../schema-compat/dist/json-schema-traverse-D0CId4oM.js
62
60
  var __create$1 = Object.create;
63
61
  var __defProp$2 = Object.defineProperty;
64
62
  var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
@@ -153,8 +151,7 @@ var require_json_schema_traverse = /* @__PURE__ */ __commonJSMin$1(((exports, mo
153
151
  return str.replace(/~/g, "~0").replace(/\//g, "~1");
154
152
  }
155
153
  }));
156
- //#endregion
157
- //#region ../schema-compat/dist/esm-DA8owk0L.js
154
+ // ../schema-compat/dist/esm-BG70JlG8.js
158
155
  const ignoreOverride$1 = Symbol("Let zodToJsonSchema decide on which parser to use");
159
156
  const defaultOptions$1 = {
160
157
  name: void 0,
@@ -1160,8 +1157,7 @@ const zodToJsonSchema$1 = (schema, options) => {
1160
1157
  return combined;
1161
1158
  };
1162
1159
  var esm_default$1 = zodToJsonSchema$1;
1163
- //#endregion
1164
- //#region ../schema-compat/dist/zod-to-json.js
1160
+ // ../schema-compat/dist/zod-to-json.js
1165
1161
  const PATCHED = Symbol("__mastra_patched__");
1166
1162
  /**
1167
1163
  * Recursively patch Zod v4 record schemas that are missing valueType.
@@ -1212,8 +1208,7 @@ function patchRecordSchemas(schema) {
1212
1208
  if (def.innerType) patchRecordSchemas(def.innerType);
1213
1209
  return schema;
1214
1210
  }
1215
- //#endregion
1216
- //#region ../schema-compat/dist/standard-schema/adapters/ai-sdk.js
1211
+ // ../schema-compat/dist/standard-schema/adapters/ai-sdk.js
1217
1212
  /**
1218
1213
  * Vendor name for AI SDK wrapped schemas.
1219
1214
  */
@@ -1361,8 +1356,7 @@ var AiSdkSchemaWrapper = class {
1361
1356
  function toStandardSchema$2(schema) {
1362
1357
  return new AiSdkSchemaWrapper(schema);
1363
1358
  }
1364
- //#endregion
1365
- //#region ../schema-compat/dist/json-schema-DcMkkbbI.js
1359
+ // ../schema-compat/dist/json-schema-BdCwqjfN.js
1366
1360
  var require_code$1 = /* @__PURE__ */ __commonJSMin$1(((exports) => {
1367
1361
  Object.defineProperty(exports, "__esModule", { value: true });
1368
1362
  exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
@@ -4257,6 +4251,38 @@ var require_utils = /* @__PURE__ */ __commonJSMin$1(((exports, module) => {
4257
4251
  return output.join("");
4258
4252
  }
4259
4253
  /**
4254
+ * Removes dot segments from the path of a relative reference (a path that does
4255
+ * not start with "/") without changing what it resolves to against any base.
4256
+ * Unlike `removeDotSegments`, leading ".." segments that cannot be collapsed
4257
+ * are kept, the result never becomes root-relative, and a result that would be
4258
+ * empty or start with an empty segment is prefixed with "." (an empty path
4259
+ * means "same document" and a leading "//" would introduce an authority).
4260
+ *
4261
+ * @param {string} path
4262
+ * @returns {string}
4263
+ */
4264
+ function removeDotSegmentsRelative(path) {
4265
+ if (path === "" || path[0] === "/") return removeDotSegments(path);
4266
+ const segments = path.split("/");
4267
+ const last = segments.length - 1;
4268
+ /** @type {string[]} */
4269
+ const output = [];
4270
+ let trailingDirectory = false;
4271
+ for (let i = 0; i <= last; i++) {
4272
+ const segment = segments[i];
4273
+ if (segment === "." || segment === "..") {
4274
+ if (segment === "..") {
4275
+ if (output.length !== 0 && output[output.length - 1] !== "..") output.pop();
4276
+ else output.push("..");
4277
+ }
4278
+ trailingDirectory = i === last;
4279
+ } else output.push(segment);
4280
+ }
4281
+ if (trailingDirectory && output[output.length - 1] !== "..") output.push("");
4282
+ if (output.length === 0 || output[0] === "" || output[0].includes(":")) output.unshift(".");
4283
+ return output.join("/");
4284
+ }
4285
+ /**
4260
4286
  * Re-escape RFC 3986 gen-delims that must not appear literally in the host.
4261
4287
  * After the URI regex parses, these characters cannot be literal in the host
4262
4288
  * field, so any that appear after decoding came from percent-encoding and
@@ -4560,6 +4586,7 @@ var require_utils = /* @__PURE__ */ __commonJSMin$1(((exports, module) => {
4560
4586
  encodeFragment,
4561
4587
  escapePreservingEscapes,
4562
4588
  removeDotSegments,
4589
+ removeDotSegmentsRelative,
4563
4590
  isIPv4,
4564
4591
  isUUID,
4565
4592
  normalizeIPv6,
@@ -4749,18 +4776,24 @@ var require_schemes = /* @__PURE__ */ __commonJSMin$1(((exports, module) => {
4749
4776
  };
4750
4777
  }));
4751
4778
  var require_fast_uri = /* @__PURE__ */ __commonJSMin$1(((exports, module) => {
4752
- const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils();
4779
+ const { normalizeIPv6, removeDotSegments, removeDotSegmentsRelative, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils();
4753
4780
  const { SCHEMES, getSchemeHandler } = require_schemes();
4754
4781
  const VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u;
4755
4782
  const MALFORMED_SCHEME_ERROR = "URI scheme is malformed.";
4783
+ const MALFORMED_HOST_ERROR = "URI host is malformed.";
4784
+ const FORBIDDEN_DOMAIN_HOST_CHARACTER = /[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;
4756
4785
  /**
4786
+ * RFC 3986 section 3.1 does not allow percent-encoding in a scheme, so the
4787
+ * scheme is validated as-is and never decoded. Decoding would let inert input
4788
+ * such as `%6Aavascript:` become a live `javascript:` scheme.
4789
+ *
4757
4790
  * @param {string} scheme
4758
4791
  * @returns {string}
4759
4792
  */
4760
- function decodeValidScheme(scheme) {
4761
- const decodedScheme = unescape(String(scheme));
4762
- if (!VALID_SCHEME.test(decodedScheme)) throw new TypeError(MALFORMED_SCHEME_ERROR);
4763
- return decodedScheme;
4793
+ function validateScheme(scheme) {
4794
+ const stringScheme = String(scheme);
4795
+ if (!VALID_SCHEME.test(stringScheme)) throw new TypeError(MALFORMED_SCHEME_ERROR);
4796
+ return stringScheme;
4764
4797
  }
4765
4798
  /**
4766
4799
  * @template {import('./types/index').URIComponent|string} T
@@ -4788,6 +4821,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin$1(((exports, module) => {
4788
4821
  const resolvedSchemeHandler = getSchemeHandler(options && options.scheme || resolved.scheme);
4789
4822
  const resolvedHost = resolved.host;
4790
4823
  const resolvedHostIsIP = resolvedHost !== void 0 && resolvedHost !== "" && (isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6);
4824
+ if (hasForbiddenDomainHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP)) throw new Error(MALFORMED_HOST_ERROR);
4791
4825
  canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP);
4792
4826
  const encodedASCIIHost = resolvedHost && resolvedHost.indexOf("%") !== -1 && !/\P{ASCII}/u.test(resolvedHost);
4793
4827
  if (resolved.error && !encodedASCIIHost) throw new Error(resolved.error);
@@ -4831,10 +4865,11 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin$1(((exports, module) => {
4831
4865
  } else {
4832
4866
  if (relative.path[0] === "/") target.path = removeDotSegments(relative.path);
4833
4867
  else {
4834
- if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path;
4868
+ const baseHasAuthority = base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0;
4869
+ if (baseHasAuthority && !base.path) target.path = "/" + relative.path;
4835
4870
  else if (!base.path) target.path = relative.path;
4836
4871
  else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
4837
- target.path = removeDotSegments(target.path);
4872
+ target.path = base.scheme === void 0 && !baseHasAuthority && target.path[0] !== "/" ? removeDotSegmentsRelative(target.path) : removeDotSegments(target.path);
4838
4873
  }
4839
4874
  target.query = relative.query;
4840
4875
  }
@@ -4882,17 +4917,18 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin$1(((exports, module) => {
4882
4917
  };
4883
4918
  const options = Object.assign({}, opts);
4884
4919
  const uriTokens = [];
4885
- if (component.scheme) component.scheme = decodeValidScheme(component.scheme);
4920
+ if (component.scheme) component.scheme = validateScheme(component.scheme);
4886
4921
  const schemeHandler = getSchemeHandler(options.scheme || component.scheme);
4887
4922
  if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);
4888
4923
  const hasAuthority = component.userinfo !== void 0 || component.host !== void 0 || component.port !== void 0;
4889
- const pathNoScheme = !options.skipEscape && component.scheme === void 0 && !hasAuthority;
4924
+ const schemelessReference = (component.scheme === void 0 || options.reference === "suffix") && !hasAuthority;
4925
+ const pathNoScheme = !options.skipEscape && schemelessReference;
4890
4926
  if (component.path !== void 0) {
4891
4927
  if (!options.skipEscape) component.path = serializePathEncoding(component.path, pathNoScheme);
4892
4928
  else component.path = normalizePercentEncoding(component.path);
4893
4929
  }
4894
4930
  if (options.reference !== "suffix" && component.scheme) {
4895
- component.scheme = decodeValidScheme(component.scheme);
4931
+ component.scheme = validateScheme(component.scheme);
4896
4932
  uriTokens.push(component.scheme, ":");
4897
4933
  }
4898
4934
  const authority = recomposeAuthority(component);
@@ -4903,8 +4939,8 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin$1(((exports, module) => {
4903
4939
  }
4904
4940
  if (component.path !== void 0) {
4905
4941
  let s = component.path;
4906
- if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s);
4907
- if (pathNoScheme) s = serializePathEncoding(s, true);
4942
+ if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = schemelessReference && s[0] !== "/" ? removeDotSegmentsRelative(s) : removeDotSegments(s);
4943
+ if (schemelessReference) s = serializePathEncoding(s, true);
4908
4944
  if (authority === void 0 && s[0] === "/" && s[1] === "/") s = "/%2F" + s.slice(2);
4909
4945
  uriTokens.push(s);
4910
4946
  }
@@ -4968,15 +5004,50 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin$1(((exports, module) => {
4968
5004
  * @returns {boolean} whether host conversion failed
4969
5005
  */
4970
5006
  function canonicalizeHost(parsed, options, schemeHandler, isIP) {
4971
- if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport) && parsed.host && !isIPLiteral(parsed.host) && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try {
4972
- parsed.host = new URL("http://" + parsed.host).hostname;
4973
- } catch (e) {
4974
- parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
5007
+ if (hasForbiddenDomainHost(parsed, options, schemeHandler, isIP)) {
5008
+ parsed.error = parsed.error || MALFORMED_HOST_ERROR;
4975
5009
  return true;
4976
5010
  }
5011
+ if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport) && parsed.host && !isIPLiteral(parsed.host) && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) {
5012
+ let url;
5013
+ try {
5014
+ url = new URL("http://" + parsed.host);
5015
+ } catch (e) {
5016
+ parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
5017
+ return true;
5018
+ }
5019
+ if (!isHostOnlyURL(url)) {
5020
+ parsed.error = parsed.error || MALFORMED_HOST_ERROR;
5021
+ return true;
5022
+ }
5023
+ parsed.host = url.hostname;
5024
+ }
4977
5025
  return false;
4978
5026
  }
4979
5027
  /**
5028
+ * Whether a domain host contains an ASCII character that RFC 3986 does not
5029
+ * allow in a reg-name (unreserved, sub-delims, or pct-encoded). Such a host is
5030
+ * rejected instead of being handed to the WHATWG URL parser, which would treat
5031
+ * "@" as a userinfo delimiter (silently dropping the data before it) and strip
5032
+ * TAB, LF, and CR. Non-ASCII characters remain allowed for IDNs.
5033
+ *
5034
+ * @param {import('./types/index').URIComponent} parsed
5035
+ * @param {import('./types/index').Options} options
5036
+ * @param {{ domainHost?: boolean }|undefined} schemeHandler
5037
+ * @param {boolean} isIP
5038
+ * @returns {boolean}
5039
+ */
5040
+ function hasForbiddenDomainHost(parsed, options, schemeHandler, isIP) {
5041
+ return Boolean(parsed.host && isIP === false && !isIPLiteral(parsed.host) && (options.domainHost || schemeHandler && schemeHandler.domainHost) && FORBIDDEN_DOMAIN_HOST_CHARACTER.test(parsed.host));
5042
+ }
5043
+ /**
5044
+ * @param {URL} url
5045
+ * @returns {boolean}
5046
+ */
5047
+ function isHostOnlyURL(url) {
5048
+ return url.username === "" && url.password === "" && url.port === "" && url.pathname === "/" && url.search === "" && url.hash === "" && url.hostname !== "";
5049
+ }
5050
+ /**
4980
5051
  * @param {string} uri
4981
5052
  * @param {import('./types/index').Options} [opts]
4982
5053
  * @returns {{ parsed: import('./types/index').URIComponent, malformedAuthorityOrPort: boolean, malformedPercentEncoding: boolean, malformedSchemeSpecific: boolean, malformedHost: boolean, malformedScheme: boolean }}
@@ -5033,8 +5104,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin$1(((exports, module) => {
5033
5104
  parsed.query = matches[7];
5034
5105
  parsed.fragment = matches[8];
5035
5106
  if (parsed.scheme !== void 0) {
5036
- const decodedScheme = unescape(parsed.scheme);
5037
- if (VALID_SCHEME.test(decodedScheme)) parsed.scheme = decodedScheme.toLowerCase();
5107
+ if (VALID_SCHEME.test(parsed.scheme)) parsed.scheme = parsed.scheme.toLowerCase();
5038
5108
  else {
5039
5109
  parsed.error = parsed.error || MALFORMED_SCHEME_ERROR;
5040
5110
  malformedScheme = true;
@@ -5057,7 +5127,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin$1(((exports, module) => {
5057
5127
  malformedIPLiteral = hasIPLiteralBracket && (!bracketedIPLiteral || ipv6result.error === true);
5058
5128
  parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase();
5059
5129
  if (malformedIPLiteral) {
5060
- parsed.error = parsed.error || "URI host is malformed.";
5130
+ parsed.error = parsed.error || MALFORMED_HOST_ERROR;
5061
5131
  malformedAuthorityOrPort = true;
5062
5132
  }
5063
5133
  } else isIP = true;
@@ -5072,7 +5142,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin$1(((exports, module) => {
5072
5142
  if (uri.indexOf("%") !== -1 && parsed.host !== void 0 && !malformedIPLiteral) {
5073
5143
  let host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true);
5074
5144
  if (!isIP) host = normalizePercentEncoding(host.toLowerCase());
5075
- parsed.host = reescapeHostDelimiters(host, isIP);
5145
+ parsed.host = isIP || options.scheme !== "null" ? reescapeHostDelimiters(host, isIP) : host;
5076
5146
  }
5077
5147
  if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
5078
5148
  if (parsed.path) parsed.path = normalizePathEncoding(parsed.path);
@@ -8318,8 +8388,7 @@ var JsonSchemaWrapper = class {
8318
8388
  function toStandardSchema$4(schema, options) {
8319
8389
  return new JsonSchemaWrapper(schema, options);
8320
8390
  }
8321
- //#endregion
8322
- //#region ../schema-compat/dist/standard-schema/adapters/zod-v3.js
8391
+ // ../schema-compat/dist/standard-schema/adapters/zod-v3.js
8323
8392
  var import_json_schema_traverse$1 = /* @__PURE__ */ __toESM$1(require_json_schema_traverse(), 1);
8324
8393
  /**
8325
8394
  * Target mapping from Standard Schema targets to zod-to-json-schema targets.
@@ -8413,8 +8482,7 @@ function toStandardSchema$3(zodSchema) {
8413
8482
  });
8414
8483
  return wrapper;
8415
8484
  }
8416
- //#endregion
8417
- //#region ../schema-compat/dist/schema-CzbEIyhE.js
8485
+ // ../schema-compat/dist/schema-Bf12g7KC.js
8418
8486
  /**
8419
8487
  * Supported JSON Schema targets for z.toJSONSchema().
8420
8488
  * Works with both real Zod v4 and Zod 3.25's v4 compat layer.
@@ -8621,8 +8689,7 @@ function isStandardJSONSchema(value) {
8621
8689
  function isStandardSchemaWithJSON$2(value) {
8622
8690
  return isStandardSchema(value) && isStandardJSONSchema(value);
8623
8691
  }
8624
- //#endregion
8625
- //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/zod-from-json-schema/0.5.2/938b1a90632b5c19aade6e212477c764befeb6d6e1cdb7cfde7de2557cd03f99/node_modules/zod-from-json-schema/dist/index.mjs
8692
+ // ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/zod-from-json-schema/0.5.2/938b1a90632b5c19aade6e212477c764befeb6d6e1cdb7cfde7de2557cd03f99/node_modules/zod-from-json-schema/dist/index.mjs
8626
8693
  var TypeHandler = class {
8627
8694
  apply(types, schema) {
8628
8695
  if (!schema.type) return;
@@ -9178,8 +9245,7 @@ function convertJsonSchemaToZod(schema) {
9178
9245
  for (const handler of refinementHandlers) zodSchema = handler.apply(zodSchema, schema);
9179
9246
  return zodSchema;
9180
9247
  }
9181
- //#endregion
9182
- //#region ../schema-compat/dist/index.js
9248
+ // ../schema-compat/dist/index.js
9183
9249
  var marker$1 = "vercel.ai.error";
9184
9250
  var symbol$1 = Symbol.for(marker$1);
9185
9251
  var _a$1;
@@ -12403,8 +12469,7 @@ function trimStartOfStream() {
12403
12469
  };
12404
12470
  }
12405
12471
  require_json_schema_traverse();
12406
- //#endregion
12407
- //#region src/shared/events/constants.ts
12472
+ // src/shared/events/constants.ts
12408
12473
  /**
12409
12474
  * Wire constants for the MCP Events extension (SEP-3415).
12410
12475
  *
@@ -12460,8 +12525,7 @@ const WEBHOOK_HEADERS = {
12460
12525
  signature: "webhook-signature",
12461
12526
  subscriptionId: "x-mcp-subscription-id"
12462
12527
  };
12463
- //#endregion
12464
- //#region src/shared/events/schemas.ts
12528
+ // src/shared/events/schemas.ts
12465
12529
  /**
12466
12530
  * Zod schemas for the MCP Events extension (SEP-3415) wire format.
12467
12531
  *
@@ -12667,8 +12731,7 @@ function parseWebhookBody(body) {
12667
12731
  event: EventOccurrenceSchema.parse(body)
12668
12732
  };
12669
12733
  }
12670
- //#endregion
12671
- //#region src/shared/events/capability.ts
12734
+ // src/shared/events/capability.ts
12672
12735
  /**
12673
12736
  * Read the negotiated events extension settings from a capabilities object.
12674
12737
  * Returns `undefined` when the peer did not advertise the extension (or advertised a malformed entry).
@@ -12684,8 +12747,7 @@ function getEventsCapability(capabilities) {
12684
12747
  const parsed = EventsCapabilitySchema.safeParse(entry);
12685
12748
  return parsed.success ? parsed.data : void 0;
12686
12749
  }
12687
- //#endregion
12688
- //#region src/shared/events/webhook.ts
12750
+ // src/shared/events/webhook.ts
12689
12751
  /**
12690
12752
  * Standard Webhooks signing and verification for MCP Events webhook delivery (SEP-3415).
12691
12753
  *
@@ -12773,8 +12835,7 @@ function verifyWebhook({ secret, headers, body, toleranceSec = DEFAULT_TOLERANCE
12773
12835
  reason: "invalid_signature"
12774
12836
  };
12775
12837
  }
12776
- //#endregion
12777
- //#region src/shared/events/webhook-url.ts
12838
+ // src/shared/events/webhook-url.ts
12778
12839
  /**
12779
12840
  * SSRF policy for MCP Events webhook callback URLs (SEP-3415 "Webhook security").
12780
12841
  *
@@ -12944,8 +13005,7 @@ async function resolveAndValidate(url, opts = {}) {
12944
13005
  family: first.family
12945
13006
  };
12946
13007
  }
12947
- //#endregion
12948
- //#region src/shared/json-schema-dialect.ts
13008
+ // src/shared/json-schema-dialect.ts
12949
13009
  const JSON_SCHEMA_2020_12 = "https://json-schema.org/draft/2020-12/schema";
12950
13010
  const JSON_SCHEMA_2019_09 = /^https?:\/\/json-schema\.org\/draft\/2019-09\/schema#?$/;
12951
13011
  /** Keywords whose value is a subschema (`items` may also be an array of subschemas). */
@@ -12979,6 +13039,89 @@ const SCHEMA_MAP_KEYWORDS$1 = /* @__PURE__ */ new Set([
12979
13039
  const MAX_JSON_SCHEMA_NODES = 1e4;
12980
13040
  var Unconvertible = class extends Error {};
12981
13041
  /**
13042
+ * Bounds the work a validator or type generator can be asked to do for an untrusted schema.
13043
+ * Only schema-bearing keywords are walked, so deeply nested annotation data such as `default`
13044
+ * or `examples` does not count. The counted nodes are returned so callers can also budget
13045
+ * across a whole catalogue rather than one schema at a time.
13046
+ *
13047
+ * The keyword lists are intentionally wider than the conversion sets above: this walk has to
13048
+ * reach every position that can carry validation rules, including `dependencies`,
13049
+ * `prefixItems`, and `contentSchema`.
13050
+ */
13051
+ function jsonSchemaComplexity(schema) {
13052
+ const seen = /* @__PURE__ */ new Set();
13053
+ let nodes = 0;
13054
+ const stack = [{
13055
+ value: schema,
13056
+ depth: 0
13057
+ }];
13058
+ const schemaMapKeywords = [
13059
+ "$defs",
13060
+ "definitions",
13061
+ "properties",
13062
+ "patternProperties",
13063
+ "dependentSchemas",
13064
+ "dependencies"
13065
+ ];
13066
+ const schemaArrayKeywords = [
13067
+ "prefixItems",
13068
+ "allOf",
13069
+ "anyOf",
13070
+ "oneOf",
13071
+ "items"
13072
+ ];
13073
+ const schemaKeywords = [
13074
+ "additionalProperties",
13075
+ "unevaluatedProperties",
13076
+ "additionalItems",
13077
+ "unevaluatedItems",
13078
+ "items",
13079
+ "contains",
13080
+ "propertyNames",
13081
+ "not",
13082
+ "if",
13083
+ "then",
13084
+ "else",
13085
+ "contentSchema"
13086
+ ];
13087
+ while (stack.length > 0) {
13088
+ const { value, depth } = stack.pop();
13089
+ if (value === null || typeof value !== "object" || Array.isArray(value) || seen.has(value)) continue;
13090
+ seen.add(value);
13091
+ nodes += 1;
13092
+ if (depth > 128) return {
13093
+ error: `JSON Schema exceeds the maximum depth of 128`,
13094
+ limit: "depth",
13095
+ nodes
13096
+ };
13097
+ if (nodes > 1e4) return {
13098
+ error: `JSON Schema exceeds the maximum node count of ${MAX_JSON_SCHEMA_NODES}`,
13099
+ limit: "nodes",
13100
+ nodes
13101
+ };
13102
+ const record = value;
13103
+ for (const keyword of schemaMapKeywords) {
13104
+ const schemas = record[keyword];
13105
+ if (schemas && typeof schemas === "object" && !Array.isArray(schemas)) for (const child of Object.values(schemas)) stack.push({
13106
+ value: child,
13107
+ depth: depth + 1
13108
+ });
13109
+ }
13110
+ for (const keyword of schemaArrayKeywords) {
13111
+ const schemas = record[keyword];
13112
+ if (Array.isArray(schemas)) for (const child of schemas) stack.push({
13113
+ value: child,
13114
+ depth: depth + 1
13115
+ });
13116
+ }
13117
+ for (const keyword of schemaKeywords) if (record[keyword] !== void 0) stack.push({
13118
+ value: record[keyword],
13119
+ depth: depth + 1
13120
+ });
13121
+ }
13122
+ return { nodes };
13123
+ }
13124
+ /**
12982
13125
  * Converts a 2019-09 schema (e.g. from zod v3) into 2020-12 form. Tuples are the
12983
13126
  * only structural difference handled: array-form `items` becomes `prefixItems`,
12984
13127
  * and `additionalItems` becomes `items`.
@@ -13028,8 +13171,7 @@ function rewrite(schema, depth, budget, isRoot = false) {
13028
13171
  delete out.additionalItems;
13029
13172
  return out;
13030
13173
  }
13031
- //#endregion
13032
- //#region src/shared/mastra-tool-meta.ts
13174
+ // src/shared/mastra-tool-meta.ts
13033
13175
  const MASTRA_META_KEY$1 = "mastra";
13034
13176
  const STRICT_META_KEY = "strict";
13035
13177
  function withMastraToolStrictMeta(meta, strict) {
@@ -13049,8 +13191,7 @@ function getMastraToolStrictMeta(meta) {
13049
13191
  const strict = mastraMeta[STRICT_META_KEY];
13050
13192
  return typeof strict === "boolean" ? strict : void 0;
13051
13193
  }
13052
- //#endregion
13053
- //#region src/shared/oauth-types.ts
13194
+ // src/shared/oauth-types.ts
13054
13195
  /**
13055
13196
  * Escapes backslashes and double quotes in a string for use in HTTP header quoted-string values.
13056
13197
  */
@@ -13109,8 +13250,7 @@ function extractBearerToken(authHeader) {
13109
13250
  if (authHeader.slice(0, 7).toLowerCase() !== prefix) return void 0;
13110
13251
  return authHeader.slice(7).trim() || void 0;
13111
13252
  }
13112
- //#endregion
13113
- //#region src/shared/trace-context.ts
13253
+ // src/shared/trace-context.ts
13114
13254
  /** `_meta` keys defined by the MCP specification for W3C trace propagation. */
13115
13255
  const TRACEPARENT_META_KEY = "traceparent";
13116
13256
  const TRACESTATE_META_KEY = "tracestate";
@@ -13254,8 +13394,7 @@ function takeServerTraceContext(result) {
13254
13394
  } } : {}
13255
13395
  };
13256
13396
  }
13257
- //#endregion
13258
- //#region src/client/events/errors.ts
13397
+ // src/client/events/errors.ts
13259
13398
  function eventsError(id, text, details = {}, cause) {
13260
13399
  return new _mastra_core_error.MastraError({
13261
13400
  id,
@@ -13287,8 +13426,7 @@ function toTransientError(error, details) {
13287
13426
  if (error instanceof _mastra_core_error.MastraError) return error;
13288
13427
  return eventsError("MCP_EVENTS_DELIVERY_INTERRUPTED", `Event delivery interrupted: ${error instanceof Error ? error.message : String(error)}`, details, error);
13289
13428
  }
13290
- //#endregion
13291
- //#region src/client/events/mode.ts
13429
+ // src/client/events/mode.ts
13292
13430
  /**
13293
13431
  * Modes this client can drive, most preferred first. Webhook comes first, as the SEP recommends,
13294
13432
  * but only when the caller configured a receiver.
@@ -13349,8 +13487,7 @@ const pollDriver = {
13349
13487
  }
13350
13488
  }
13351
13489
  };
13352
- //#endregion
13353
- //#region src/client/events/push-driver.ts
13490
+ // src/client/events/push-driver.ts
13354
13491
  /**
13355
13492
  * Delivers a subscription over one `events/stream` request. The session ends when the stream
13356
13493
  * closes, fails, goes silent for `heartbeatTimeoutMs`, or the server terminates it.
@@ -13431,8 +13568,7 @@ const pushDriver = {
13431
13568
  }
13432
13569
  }
13433
13570
  };
13434
- //#endregion
13435
- //#region src/client/events/webhook-driver.ts
13571
+ // src/client/events/webhook-driver.ts
13436
13572
  const DAY_MS = 864e5;
13437
13573
  const MAX_MARGIN_MS = 6e4;
13438
13574
  const MIN_REFRESH_DELAY_MS = 1e3;
@@ -13628,8 +13764,7 @@ var WebhookShare = class {
13628
13764
  }
13629
13765
  };
13630
13766
  const sharesByPort = /* @__PURE__ */ new WeakMap();
13631
- //#endregion
13632
- //#region src/client/actions/events.ts
13767
+ // src/client/actions/events.ts
13633
13768
  const DRIVERS = {
13634
13769
  webhook: {
13635
13770
  mode: "webhook",
@@ -13806,8 +13941,7 @@ var EventClientActions = class {
13806
13941
  return events;
13807
13942
  }
13808
13943
  };
13809
- //#endregion
13810
- //#region src/client/actions/progress.ts
13944
+ // src/client/actions/progress.ts
13811
13945
  /**
13812
13946
  * Client-side progress actions for handling progress notifications from MCP servers.
13813
13947
  */
@@ -13826,8 +13960,7 @@ var ProgressClientActions = class {
13826
13960
  this.client.setProgressNotificationHandler(handler);
13827
13961
  }
13828
13962
  };
13829
- //#endregion
13830
- //#region src/client/actions/prompt.ts
13963
+ // src/client/actions/prompt.ts
13831
13964
  /**
13832
13965
  * Client-side prompt actions for interacting with MCP server prompts.
13833
13966
  *
@@ -13932,8 +14065,7 @@ var PromptClientActions = class {
13932
14065
  await this.client.setPromptListChangedNotificationHandler(handler);
13933
14066
  }
13934
14067
  };
13935
- //#endregion
13936
- //#region src/client/actions/resource.ts
14068
+ // src/client/actions/resource.ts
13937
14069
  /**
13938
14070
  * Client-side resource actions for interacting with MCP server resources.
13939
14071
  *
@@ -14100,8 +14232,7 @@ var ResourceClientActions = class {
14100
14232
  await this.client.setResourceListChangedNotificationHandler(handler);
14101
14233
  }
14102
14234
  };
14103
- //#endregion
14104
- //#region src/client/error-utils.ts
14235
+ // src/client/error-utils.ts
14105
14236
  /**
14106
14237
  * Whether a failed MCP call is worth one transport reconnect and retry.
14107
14238
  *
@@ -14182,8 +14313,7 @@ function getMCPDiscoveryErrorDetails(error) {
14182
14313
  ...code !== void 0 ? { code } : {}
14183
14314
  };
14184
14315
  }
14185
- //#endregion
14186
- //#region src/client/events/stream-router.ts
14316
+ // src/client/events/stream-router.ts
14187
14317
  /**
14188
14318
  * Routes push-stream notifications for one MCP server to the subscription that owns them.
14189
14319
  *
@@ -14306,8 +14436,7 @@ var EventStreamRouter = class {
14306
14436
  });
14307
14437
  }
14308
14438
  };
14309
- //#endregion
14310
- //#region src/client/events/subscription.ts
14439
+ // src/client/events/subscription.ts
14311
14440
  const DEFAULT_DEDUP_WINDOW = 1e3;
14312
14441
  const DEFAULT_MAX_BUFFERED_EVENTS = 1e3;
14313
14442
  const DEFAULT_RETRY = {
@@ -14680,8 +14809,7 @@ var EventSubscription = class EventSubscription {
14680
14809
  this.end();
14681
14810
  }
14682
14811
  };
14683
- //#endregion
14684
- //#region src/client/input-schema-meta-schema.ts
14812
+ // src/client/input-schema-meta-schema.ts
14685
14813
  /**
14686
14814
  * Structural JSON Schema meta-schema, used to check that a server-supplied tool input schema is
14687
14815
  * shaped like a JSON Schema before it is handed to a model provider.
@@ -15000,8 +15128,7 @@ function getInputSchemaError(schema) {
15000
15128
  }
15001
15129
  return result.valid ? void 0 : result.errorMessage.split("; ").at(-1);
15002
15130
  }
15003
- //#endregion
15004
- //#region src/client/url-policy.ts
15131
+ // src/client/url-policy.ts
15005
15132
  /**
15006
15133
  * Redirect status codes the manual redirect loop follows. Other 3xx statuses
15007
15134
  * (e.g. 304) are not redirects and are returned to the caller as-is.
@@ -15166,78 +15293,8 @@ async function fetchFollowingAllowedRedirects(fetchImpl, url, init, allowedHosts
15166
15293
  currentUrl = nextUrl;
15167
15294
  }
15168
15295
  }
15169
- //#endregion
15170
- //#region src/client/client.ts
15296
+ // src/client/client.ts
15171
15297
  const DEFAULT_SERVER_CONNECT_TIMEOUT_MSEC = 3e3;
15172
- /**
15173
- * Bounds the work a validator can be asked to do for an untrusted tool catalogue.
15174
- * Only schema-bearing keywords are walked, so deeply nested annotation data such as
15175
- * `default` or `examples` does not count.
15176
- */
15177
- function getJsonSchemaComplexityError(schema) {
15178
- const seen = /* @__PURE__ */ new Set();
15179
- let nodes = 0;
15180
- const stack = [{
15181
- value: schema,
15182
- depth: 0
15183
- }];
15184
- const schemaMapKeywords = [
15185
- "$defs",
15186
- "definitions",
15187
- "properties",
15188
- "patternProperties",
15189
- "dependentSchemas",
15190
- "dependencies"
15191
- ];
15192
- const schemaArrayKeywords = [
15193
- "prefixItems",
15194
- "allOf",
15195
- "anyOf",
15196
- "oneOf",
15197
- "items"
15198
- ];
15199
- const schemaKeywords = [
15200
- "additionalProperties",
15201
- "unevaluatedProperties",
15202
- "additionalItems",
15203
- "unevaluatedItems",
15204
- "items",
15205
- "contains",
15206
- "propertyNames",
15207
- "not",
15208
- "if",
15209
- "then",
15210
- "else",
15211
- "contentSchema"
15212
- ];
15213
- while (stack.length > 0) {
15214
- const { value, depth } = stack.pop();
15215
- if (value === null || typeof value !== "object" || Array.isArray(value) || seen.has(value)) continue;
15216
- seen.add(value);
15217
- nodes += 1;
15218
- if (depth > 128) return `JSON Schema exceeds the maximum depth of 128`;
15219
- if (nodes > 1e4) return `JSON Schema exceeds the maximum node count of ${MAX_JSON_SCHEMA_NODES}`;
15220
- const record = value;
15221
- for (const keyword of schemaMapKeywords) {
15222
- const schemas = record[keyword];
15223
- if (schemas && typeof schemas === "object" && !Array.isArray(schemas)) for (const child of Object.values(schemas)) stack.push({
15224
- value: child,
15225
- depth: depth + 1
15226
- });
15227
- }
15228
- for (const keyword of schemaArrayKeywords) {
15229
- const schemas = record[keyword];
15230
- if (Array.isArray(schemas)) for (const child of schemas) stack.push({
15231
- value: child,
15232
- depth: depth + 1
15233
- });
15234
- }
15235
- for (const keyword of schemaKeywords) if (record[keyword] !== void 0) stack.push({
15236
- value: record[keyword],
15237
- depth: depth + 1
15238
- });
15239
- }
15240
- }
15241
15298
  const SUPPORTED_DIALECTS = /* @__PURE__ */ new Set([
15242
15299
  JSON_SCHEMA_2020_12,
15243
15300
  `${JSON_SCHEMA_2020_12}#`,
@@ -15443,6 +15500,7 @@ var InternalMastraMCPClient = class extends _mastra_core_base.MastraBase {
15443
15500
  name;
15444
15501
  client;
15445
15502
  timeout;
15503
+ processHooks;
15446
15504
  logHandler;
15447
15505
  serverLogLevel;
15448
15506
  enableProgressTracking;
@@ -15479,12 +15537,13 @@ var InternalMastraMCPClient = class extends _mastra_core_base.MastraBase {
15479
15537
  /**
15480
15538
  * @internal
15481
15539
  */
15482
- constructor({ name, version = "1.0.0", clientInfo, server, timeout = _modelcontextprotocol_client.DEFAULT_REQUEST_TIMEOUT_MSEC, webhook }) {
15540
+ constructor({ name, version = "1.0.0", clientInfo, server, timeout = _modelcontextprotocol_client.DEFAULT_REQUEST_TIMEOUT_MSEC, registerProcessHooks = true, webhook }) {
15483
15541
  super({ name: "MastraMCPClient" });
15484
15542
  this.webhook = webhook;
15485
15543
  loadInputSchemaMetaValidator();
15486
15544
  this.name = name;
15487
15545
  this.timeout = timeout;
15546
+ this.processHooks = registerProcessHooks;
15488
15547
  this.logHandler = server.logger;
15489
15548
  this.serverLogLevel = server.enableServerLogs ?? true ? server.serverLogLevel ?? DEFAULT_SERVER_LOG_LEVEL : void 0;
15490
15549
  this.serverConfig = server;
@@ -15827,7 +15886,7 @@ var InternalMastraMCPClient = class extends _mastra_core_base.MastraBase {
15827
15886
  reject(e);
15828
15887
  }
15829
15888
  });
15830
- this.registerProcessHooks();
15889
+ if (this.processHooks) this.registerProcessHooks();
15831
15890
  return this.isConnected;
15832
15891
  }
15833
15892
  /**
@@ -16370,7 +16429,7 @@ var InternalMastraMCPClient = class extends _mastra_core_base.MastraBase {
16370
16429
  buildToolFromListEntry(tool, serverMeta) {
16371
16430
  const rawInputSchema = tool.inputSchema;
16372
16431
  const inputSchema = rawInputSchema && typeof rawInputSchema === "object" && "jsonSchema" in rawInputSchema ? rawInputSchema.jsonSchema : rawInputSchema;
16373
- const inputSchemaError = getJsonSchemaComplexityError(inputSchema) ?? getInputSchemaError(inputSchema);
16432
+ const inputSchemaError = jsonSchemaComplexity(inputSchema).error ?? getInputSchemaError(inputSchema);
16374
16433
  if (inputSchemaError) {
16375
16434
  const details = {
16376
16435
  serverName: this.name,
@@ -16412,7 +16471,7 @@ var InternalMastraMCPClient = class extends _mastra_core_base.MastraBase {
16412
16471
  ...annotations ? { annotations } : {}
16413
16472
  } } : {};
16414
16473
  const outputSchema = tool.outputSchema ? withDefaultDialect("jsonSchema" in tool.outputSchema ? tool.outputSchema.jsonSchema : tool.outputSchema) : void 0;
16415
- const outputSchemaComplexityError = outputSchema ? getJsonSchemaComplexityError(outputSchema) : void 0;
16474
+ const outputSchemaComplexityError = outputSchema ? jsonSchemaComplexity(outputSchema).error : void 0;
16416
16475
  let outputValidationSchema;
16417
16476
  const getOutputValidationSchema = async () => {
16418
16477
  if (!outputSchema) return void 0;
@@ -16559,8 +16618,7 @@ var InternalMastraMCPClient = class extends _mastra_core_base.MastraBase {
16559
16618
  };
16560
16619
  }
16561
16620
  };
16562
- //#endregion
16563
- //#region src/client/events/webhook-receiver.ts
16621
+ // src/client/events/webhook-receiver.ts
16564
16622
  function respond(status, body) {
16565
16623
  return body ? new Response(JSON.stringify(body), {
16566
16624
  status,
@@ -16668,8 +16726,7 @@ async function readBody(request, limit) {
16668
16726
  }
16669
16727
  return body;
16670
16728
  }
16671
- //#endregion
16672
- //#region src/client/oauth-callback-server.ts
16729
+ // src/client/oauth-callback-server.ts
16673
16730
  /**
16674
16731
  * Loopback OAuth Callback Server for MCP Client
16675
16732
  *
@@ -16881,8 +16938,7 @@ async function createOAuthCallbackServer(options) {
16881
16938
  }
16882
16939
  };
16883
16940
  }
16884
- //#endregion
16885
- //#region src/client/oauth-provider.ts
16941
+ // src/client/oauth-provider.ts
16886
16942
  /**
16887
16943
  * OAuth Client Provider Implementation for MCP Client
16888
16944
  *
@@ -17231,8 +17287,7 @@ function createSimpleTokenProvider(accessToken, options) {
17231
17287
  storage
17232
17288
  });
17233
17289
  }
17234
- //#endregion
17235
- //#region src/client/server-proxy.ts
17290
+ // src/client/server-proxy.ts
17236
17291
  /**
17237
17292
  * Wraps a single MCPClient server connection as an `MCPServerBase` so external
17238
17293
  * (non-Mastra) MCP servers connected through MCPClient can be registered in Mastra's
@@ -17351,9 +17406,12 @@ var MCPClientServerProxy = class extends _mastra_core_mcp.MCPServerBase {
17351
17406
  };
17352
17407
  }
17353
17408
  };
17354
- //#endregion
17355
- //#region src/client/configuration.ts
17409
+ // src/client/configuration.ts
17356
17410
  const mcpClientInstances = /* @__PURE__ */ new Map();
17411
+ /** Reads the shared cache without promising the snapshot shape it was created with. */
17412
+ function cachedClient(id) {
17413
+ return mcpClientInstances.get(id);
17414
+ }
17357
17415
  const TOOL_DISCOVERY_MAX_ATTEMPTS = 2;
17358
17416
  const LOOPBACK_IPV4 = /^127\.(?:\d{1,3})\.(?:\d{1,3})\.(?:\d{1,3})$/;
17359
17417
  function isLoopbackHostname(hostname) {
@@ -17386,10 +17444,12 @@ function isLoopbackHostname(hostname) {
17386
17444
  * if packaged docs are unavailable.
17387
17445
  */
17388
17446
  var MCPClient = class extends _mastra_core_base.MastraBase {
17447
+ typegen;
17389
17448
  serverConfigs = {};
17390
17449
  id;
17391
17450
  defaultTimeout;
17392
17451
  defaultClientInfo;
17452
+ registerProcessHooks;
17393
17453
  webhook;
17394
17454
  mcpClientsById = /* @__PURE__ */ new Map();
17395
17455
  disconnectPromise = null;
@@ -17434,6 +17494,7 @@ var MCPClient = class extends _mastra_core_base.MastraBase {
17434
17494
  super({ name: "MCPClient" });
17435
17495
  this.defaultTimeout = args.timeout ?? _modelcontextprotocol_client.DEFAULT_REQUEST_TIMEOUT_MSEC;
17436
17496
  this.defaultClientInfo = args.clientInfo && { ...args.clientInfo };
17497
+ this.registerProcessHooks = args.registerProcessHooks ?? true;
17437
17498
  this.serverConfigs = args.servers;
17438
17499
  this.webhook = args.webhook && {
17439
17500
  options: { ...args.webhook },
@@ -17442,16 +17503,13 @@ var MCPClient = class extends _mastra_core_base.MastraBase {
17442
17503
  this.id = args.id ?? this.makeId();
17443
17504
  if (args.id) {
17444
17505
  this.id = args.id;
17445
- const cached = mcpClientInstances.get(this.id);
17446
- if (cached && (!(0, fast_deep_equal.default)(cached.serverConfigs, args.servers) || !(0, fast_deep_equal.default)(cached.defaultClientInfo, args.clientInfo))) {
17447
- const existingInstance = mcpClientInstances.get(this.id);
17448
- if (existingInstance) {
17449
- existingInstance.disconnect();
17450
- mcpClientInstances.delete(this.id);
17451
- }
17506
+ const cached = cachedClient(this.id);
17507
+ if (cached && (!(0, fast_deep_equal.default)(cached.serverConfigs, args.servers) || !(0, fast_deep_equal.default)(cached.defaultClientInfo, args.clientInfo) || cached.registerProcessHooks !== this.registerProcessHooks || cached.typegen?.outFile !== args.typegen?.outFile)) {
17508
+ cached.disconnect();
17509
+ mcpClientInstances.delete(this.id);
17452
17510
  }
17453
17511
  } else this.id = this.makeId();
17454
- const existingInstance = mcpClientInstances.get(this.id);
17512
+ const existingInstance = cachedClient(this.id);
17455
17513
  if (existingInstance) {
17456
17514
  if (!args.id) throw new Error(`MCPClient was initialized multiple times with the same configuration options.
17457
17515
 
@@ -17464,6 +17522,11 @@ To fix this you have three different options:
17464
17522
  `);
17465
17523
  return existingInstance;
17466
17524
  }
17525
+ const { typegen } = args;
17526
+ if (typegen !== void 0) {
17527
+ if (!typegen || typeof typegen.outFile !== "string" || !typegen.outFile.trim() || typegen.outFile.includes("\0")) throw new Error("typegen.outFile must be a nonempty file path");
17528
+ this.typegen = Object.freeze({ outFile: typegen.outFile });
17529
+ }
17467
17530
  mcpClientInstances.set(this.id, this);
17468
17531
  this.addToInstanceCache();
17469
17532
  return this;
@@ -17927,9 +17990,10 @@ onListChanged: async (serverName, handler) => {
17927
17990
  if (!mcpClientInstances.has(this.id)) mcpClientInstances.set(this.id, this);
17928
17991
  }
17929
17992
  makeId() {
17930
- const text = JSON.stringify(this.defaultClientInfo === void 0 ? this.serverConfigs : {
17993
+ const text = JSON.stringify(this.defaultClientInfo === void 0 && this.registerProcessHooks ? this.serverConfigs : {
17931
17994
  servers: this.serverConfigs,
17932
- clientInfo: this.defaultClientInfo
17995
+ ...this.defaultClientInfo === void 0 ? {} : { clientInfo: this.defaultClientInfo },
17996
+ ...this.registerProcessHooks ? {} : { registerProcessHooks: false }
17933
17997
  }).normalize("NFKC");
17934
17998
  return (0, crypto$1.createHash)("sha256").update("MCPClient").update(text).digest("hex");
17935
17999
  }
@@ -18170,24 +18234,6 @@ onListChanged: async (serverName, handler) => {
18170
18234
  async listTools() {
18171
18235
  return (await this.listToolsWithErrors()).tools;
18172
18236
  }
18173
- /**
18174
- * Retrieves all tools from all configured servers with namespaced names,
18175
- * along with any per-server errors.
18176
- *
18177
- * Like listTools(), but also returns errors for servers that failed to connect
18178
- * or list tools. This allows callers to report specific failure reasons per server.
18179
- *
18180
- * @returns Object with successful `tools`, legacy string `errors`, and structured `errorDetails`.
18181
- * Transient connection failures are retried once after reconnecting the affected server.
18182
- *
18183
- * @example
18184
- * ```typescript
18185
- * const { tools, errors, errorDetails } = await mcp.listToolsWithErrors();
18186
- * for (const [name, err] of Object.entries(errors)) {
18187
- * console.error(`Server ${name} failed: ${err}`, errorDetails[name]);
18188
- * }
18189
- * ```
18190
- */
18191
18237
  async listToolsWithErrors(options) {
18192
18238
  this.addToInstanceCache();
18193
18239
  const connectedTools = {};
@@ -18243,23 +18289,6 @@ onListChanged: async (serverName, handler) => {
18243
18289
  async listToolsets() {
18244
18290
  return (await this.listToolsetsWithErrors()).toolsets;
18245
18291
  }
18246
- /**
18247
- * Returns toolsets organized by server name, along with any per-server errors.
18248
- *
18249
- * Like listToolsets(), but also returns errors for servers that failed to connect
18250
- * or list tools. This allows callers to report specific failure reasons per server.
18251
- *
18252
- * @returns Object with successful `toolsets`, legacy string `errors`, and structured `errorDetails`.
18253
- * Transient connection failures are retried once after reconnecting the affected server.
18254
- *
18255
- * @example
18256
- * ```typescript
18257
- * const { toolsets, errors, errorDetails } = await mcp.listToolsetsWithErrors();
18258
- * for (const [name, err] of Object.entries(errors)) {
18259
- * console.error(`Server ${name} failed: ${err}`, errorDetails[name]);
18260
- * }
18261
- * ```
18262
- */
18263
18292
  async listToolsetsWithErrors(options) {
18264
18293
  this.addToInstanceCache();
18265
18294
  const connectedToolsets = {};
@@ -18590,6 +18619,7 @@ onListChanged: async (serverName, handler) => {
18590
18619
  name,
18591
18620
  server: config,
18592
18621
  timeout: config.timeout ?? this.defaultTimeout,
18622
+ registerProcessHooks: this.registerProcessHooks,
18593
18623
  clientInfo: {
18594
18624
  name: config.clientInfo?.name ?? this.defaultClientInfo?.name,
18595
18625
  version: config.clientInfo?.version ?? this.defaultClientInfo?.version
@@ -18646,8 +18676,7 @@ onListChanged: async (serverName, handler) => {
18646
18676
  return {};
18647
18677
  }
18648
18678
  };
18649
- //#endregion
18650
- //#region src/server/actions.ts
18679
+ // src/server/actions.ts
18651
18680
  /** Runtime tool catalogue mutations. Every change is published to listening clients. */
18652
18681
  var ServerToolActions = class {
18653
18682
  deps;
@@ -18691,8 +18720,7 @@ var ServerPromptActions = class {
18691
18720
  this.deps.getNotifier()?.promptsChanged();
18692
18721
  }
18693
18722
  };
18694
- //#endregion
18695
- //#region src/server/events/actions.ts
18723
+ // src/server/events/actions.ts
18696
18724
  /**
18697
18725
  * `server.events`: publishes occurrences of the event types configured in `MCPServer`'s `events`.
18698
18726
  *
@@ -18731,8 +18759,7 @@ var ServerEventActions = class {
18731
18759
  return this.describe();
18732
18760
  }
18733
18761
  };
18734
- //#endregion
18735
- //#region src/server/request.ts
18762
+ // src/server/request.ts
18736
18763
  const unavailable = (feature, replacement) => () => Promise.reject(/* @__PURE__ */ new Error(`${feature} is not available on a 2026-07-28 server; ${replacement}`));
18737
18764
  /**
18738
18765
  * The `context.mcp` a 2026-07-28 request hands to tools: the 1.x shape, with the
@@ -18845,8 +18872,7 @@ function readContinuation(ctx, requestContext, expected) {
18845
18872
  resumeData: answer.action === "accept" ? answer.content ?? {} : void 0
18846
18873
  };
18847
18874
  }
18848
- //#endregion
18849
- //#region src/server/events/ring-buffer.ts
18875
+ // src/server/events/ring-buffer.ts
18850
18876
  /**
18851
18877
  * Bounded, in-memory history of one event type's emitted occurrences.
18852
18878
  *
@@ -18947,8 +18973,7 @@ var EventRingBuffer = class {
18947
18973
  return seq <= this.seq ? seq : void 0;
18948
18974
  }
18949
18975
  };
18950
- //#endregion
18951
- //#region src/server/events/registry.ts
18976
+ // src/server/events/registry.ts
18952
18977
  const DEFAULT_BUFFER_SIZE = 1e3;
18953
18978
  /**
18954
18979
  * Delivery modes advertised for a definition. They are fixed at construction because clients
@@ -19093,8 +19118,7 @@ function toDescriptor(event, convert) {
19093
19118
  if (payloadSchema) descriptor.payloadSchema = payloadSchema;
19094
19119
  return descriptor;
19095
19120
  }
19096
- //#endregion
19097
- //#region src/server/events/stream.ts
19121
+ // src/server/events/stream.ts
19098
19122
  /**
19099
19123
  * Server side of one push subscription (`events/stream`).
19100
19124
  *
@@ -19205,8 +19229,7 @@ var EventStream = class {
19205
19229
  }, this.options.heartbeatIntervalMs);
19206
19230
  }
19207
19231
  };
19208
- //#endregion
19209
- //#region src/server/events/handlers.ts
19232
+ // src/server/events/handlers.ts
19210
19233
  const DEFAULT_MAX_EVENTS = 100;
19211
19234
  const DEFAULT_LIST_PAGE_SIZE = 100;
19212
19235
  /**
@@ -19437,8 +19460,7 @@ function decodeListCursor(cursor) {
19437
19460
  } catch {}
19438
19461
  throw new _modelcontextprotocol_server.ProtocolError(_modelcontextprotocol_server.ProtocolErrorCode.InvalidParams, "Invalid events/list cursor");
19439
19462
  }
19440
- //#endregion
19441
- //#region src/server/events/inspector.ts
19463
+ // src/server/events/inspector.ts
19442
19464
  /** Prefix of the `eventId` of occurrences sent with the inspector's `emit`. */
19443
19465
  const TEST_EMIT_EVENT_ID_PREFIX = "mastra-test-";
19444
19466
  let localStreamIds = 0;
@@ -19555,8 +19577,7 @@ function protocolErrorId(code) {
19555
19577
  default: return;
19556
19578
  }
19557
19579
  }
19558
- //#endregion
19559
- //#region src/server/events/webhook-store.ts
19580
+ // src/server/events/webhook-store.ts
19560
19581
  /**
19561
19582
  * Default {@link WebhookSubscriptionStore}: a process-local map.
19562
19583
  *
@@ -19577,8 +19598,7 @@ var InMemoryWebhookSubscriptionStore = class {
19577
19598
  return [...this.records.values()].filter((record) => record.name === name);
19578
19599
  }
19579
19600
  };
19580
- //#endregion
19581
- //#region src/server/events/webhook-transport.ts
19601
+ // src/server/events/webhook-transport.ts
19582
19602
  /** Largest response body read from a callback endpoint. Enough for a verification echo. */
19583
19603
  const MAX_RESPONSE_BYTES = 4096;
19584
19604
  /** Maps a non-2xx status to its failure category. */
@@ -19653,8 +19673,7 @@ const nodeWebhookTransport = (request) => new Promise((resolve) => {
19653
19673
  });
19654
19674
  req.end(request.body);
19655
19675
  });
19656
- //#endregion
19657
- //#region src/server/events/webhook-dispatcher.ts
19676
+ // src/server/events/webhook-dispatcher.ts
19658
19677
  const MINUTE = 6e4;
19659
19678
  const HOUR = 60 * MINUTE;
19660
19679
  const MAX_TIMER_MS = 2147483647;
@@ -20211,8 +20230,7 @@ function echoes(body, challenge) {
20211
20230
  const b = Buffer.from(challenge);
20212
20231
  return a.length === b.length && (0, crypto$1.timingSafeEqual)(a, b);
20213
20232
  }
20214
- //#endregion
20215
- //#region src/server/server.ts
20233
+ // src/server/server.ts
20216
20234
  const EMPTY_OBJECT_SCHEMA = {
20217
20235
  type: "object",
20218
20236
  properties: {}
@@ -20270,6 +20288,7 @@ var MCPServer = class extends _mastra_core_mcp.MCPServerBase {
20270
20288
  eventsOptions;
20271
20289
  eventsInspector;
20272
20290
  webhooks;
20291
+ legacy;
20273
20292
  httpHandler;
20274
20293
  nodeHandler;
20275
20294
  stdioHandle;
@@ -20285,6 +20304,7 @@ var MCPServer = class extends _mastra_core_mcp.MCPServerBase {
20285
20304
  this.loadAppResources(config.appResources);
20286
20305
  this.requestStateCodec = this.createRequestStateCodec(config.requestState);
20287
20306
  this.eventsOptions = config.eventsOptions ?? {};
20307
+ this.legacy = config.legacy ?? "reject";
20288
20308
  const webhook = this.eventsOptions.webhook;
20289
20309
  this.eventRegistry = new ServerEventRegistry(config.events, { webhook: webhook !== void 0 });
20290
20310
  if (webhook && this.eventRegistry.size > 0) this.webhooks = new WebhookDispatcher({
@@ -20814,7 +20834,7 @@ var MCPServer = class extends _mastra_core_mcp.MCPServerBase {
20814
20834
  resumeSchema: execution.resumeSchema
20815
20835
  });
20816
20836
  }
20817
- const result = this.toCallToolResult(name, tool, execution.output);
20837
+ const result = server.projectCallToolResult(this.toCallToolResult(name, tool, execution.output), this.toolInfo(name, tool).outputSchema);
20818
20838
  this.logger.info(`Tool '${name}' finished in ${Date.now() - startedAt}ms.`);
20819
20839
  return result;
20820
20840
  } catch (error) {
@@ -21080,7 +21100,7 @@ var MCPServer = class extends _mastra_core_mcp.MCPServerBase {
21080
21100
  getNodeHandler() {
21081
21101
  if (!this.nodeHandler) {
21082
21102
  this.httpHandler = (0, _modelcontextprotocol_server.createMcpHandler)(() => this.createServerInstance(), {
21083
- legacy: "reject",
21103
+ legacy: this.legacy,
21084
21104
  onerror: (error) => this.logger.error("MCP handler error", { error: error.toString() })
21085
21105
  });
21086
21106
  this.nodeHandler = (0, _modelcontextprotocol_node.toNodeHandler)(this.httpHandler, { onerror: (error) => this.logger.error("MCP Node handler adapter error", { error: error.toString() }) });
@@ -21100,7 +21120,8 @@ var MCPServer = class extends _mastra_core_mcp.MCPServerBase {
21100
21120
  }
21101
21121
  /**
21102
21122
  * Handles one Streamable HTTP request at `httpPath`. Every request is
21103
- * self-contained; requests without a 2026-07-28 envelope are rejected.
21123
+ * self-contained; requests without a 2026-07-28 envelope are rejected unless
21124
+ * `legacy: 'stateless'` is configured.
21104
21125
  */
21105
21126
  async startHTTP({ url, httpPath, req, res, options }) {
21106
21127
  if (url.pathname !== httpPath) {
@@ -21324,12 +21345,10 @@ function normalizeUiMeta(meta) {
21324
21345
  [_modelcontextprotocol_ext_apps.RESOURCE_URI_META_KEY]: resourceUri
21325
21346
  };
21326
21347
  }
21327
- //#endregion
21328
- //#region src/server/types.ts
21348
+ // src/server/types.ts
21329
21349
  /** The only protocol revision `@mastra/mcp` serves. */
21330
21350
  const MCP_PROTOCOL_VERSION = "2026-07-28";
21331
- //#endregion
21332
- //#region src/server/oauth-middleware.ts
21351
+ // src/server/oauth-middleware.ts
21333
21352
  /**
21334
21353
  * Creates an OAuth middleware function for protecting MCP server endpoints.
21335
21354
  *
@@ -21574,8 +21593,7 @@ function createIntrospectionValidator(introspectionEndpoint, clientCredentials)
21574
21593
  }
21575
21594
  };
21576
21595
  }
21577
- //#endregion
21578
- //#region src/server/events/define-event.ts
21596
+ // src/server/events/define-event.ts
21579
21597
  /**
21580
21598
  * Declares an event type for `MCPServer`'s `events` option. An identity helper: it types `match`
21581
21599
  * and `poll` from `inputSchema` and `payloadSchema`.
@@ -21595,8 +21613,7 @@ function createIntrospectionValidator(introspectionEndpoint, clientCredentials)
21595
21613
  function defineEvent(definition) {
21596
21614
  return definition;
21597
21615
  }
21598
- //#endregion
21599
- //#region src/integrations/events-cursor-store.ts
21616
+ // src/integrations/events-cursor-store.ts
21600
21617
  /**
21601
21618
  * Process-local {@link MCPEventCursorStore}. Cursors survive a provider restart within the same
21602
21619
  * process, not a process restart.
@@ -21615,8 +21632,7 @@ var InMemoryMCPEventCursorStore = class {
21615
21632
  this.#cursors.delete(key);
21616
21633
  }
21617
21634
  };
21618
- //#endregion
21619
- //#region src/integrations/events-utils.ts
21635
+ // src/integrations/events-utils.ts
21620
21636
  function canonicalize(value) {
21621
21637
  if (Array.isArray(value)) return value.map(canonicalize);
21622
21638
  if (value !== null && typeof value === "object") {
@@ -21659,8 +21675,7 @@ function formatUntrustedEvent({ header, data, footer }) {
21659
21675
  ...footer ? [footer] : []
21660
21676
  ].join("\n");
21661
21677
  }
21662
- //#endregion
21663
- //#region src/integrations/events-tools.ts
21678
+ // src/integrations/events-tools.ts
21664
21679
  function decodeArguments(value) {
21665
21680
  try {
21666
21681
  const parsed = JSON.parse(value);
@@ -21768,8 +21783,7 @@ function createMCPEventsTools({ provider, client, servers }) {
21768
21783
  })
21769
21784
  };
21770
21785
  }
21771
- //#endregion
21772
- //#region src/integrations/events-signals.ts
21786
+ // src/integrations/events-signals.ts
21773
21787
  const GAP_NOTE = "Some events may have been skipped (gap); re-fetch authoritative state with tools if it matters.";
21774
21788
  /**
21775
21789
  * Delivers MCP Events (SEP-3415) occurrences into agent threads as notification signals.
@@ -22022,7 +22036,6 @@ var MCPEventsSignalProvider = class MCPEventsSignalProvider extends _mastra_core
22022
22036
  else console.warn(`[${this.id}] ${info.key}:`, error);
22023
22037
  }
22024
22038
  };
22025
- //#endregion
22026
22039
  exports.InMemoryMCPEventCursorStore = InMemoryMCPEventCursorStore;
22027
22040
  exports.InMemoryOAuthStorage = InMemoryOAuthStorage;
22028
22041
  exports.InMemoryWebhookSubscriptionStore = InMemoryWebhookSubscriptionStore;