@mastra/core 1.11.0-alpha.2 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/CHANGELOG.md +330 -0
  2. package/dist/agent/index.cjs +8 -8
  3. package/dist/agent/index.js +1 -1
  4. package/dist/{chunk-7P77FWM6.js → chunk-7FVJIJGY.js} +3 -3
  5. package/dist/{chunk-7P77FWM6.js.map → chunk-7FVJIJGY.js.map} +1 -1
  6. package/dist/{chunk-MIAFERSL.js → chunk-7UM6FE6A.js} +8 -2
  7. package/dist/chunk-7UM6FE6A.js.map +1 -0
  8. package/dist/{chunk-CDXZJ3PO.cjs → chunk-E7PW4ZAB.cjs} +8 -2
  9. package/dist/chunk-E7PW4ZAB.cjs.map +1 -0
  10. package/dist/{chunk-L7NBGABG.cjs → chunk-FIQRYC7M.cjs} +4 -4
  11. package/dist/{chunk-L7NBGABG.cjs.map → chunk-FIQRYC7M.cjs.map} +1 -1
  12. package/dist/{chunk-V5SM5A4F.cjs → chunk-FN6ZOGJ7.cjs} +6 -6
  13. package/dist/{chunk-V5SM5A4F.cjs.map → chunk-FN6ZOGJ7.cjs.map} +1 -1
  14. package/dist/{chunk-RH5O4YBE.cjs → chunk-NJVIJQ4R.cjs} +3 -3
  15. package/dist/{chunk-RH5O4YBE.cjs.map → chunk-NJVIJQ4R.cjs.map} +1 -1
  16. package/dist/{chunk-6VSVQ62A.cjs → chunk-QAIBZ7GH.cjs} +195 -190
  17. package/dist/{chunk-6VSVQ62A.cjs.map → chunk-QAIBZ7GH.cjs.map} +1 -1
  18. package/dist/{chunk-JNNKF6W5.cjs → chunk-QGT2HJGX.cjs} +24 -24
  19. package/dist/{chunk-JNNKF6W5.cjs.map → chunk-QGT2HJGX.cjs.map} +1 -1
  20. package/dist/{chunk-J4V2WVFG.js → chunk-RF2EPUM4.js} +3 -3
  21. package/dist/{chunk-J4V2WVFG.js.map → chunk-RF2EPUM4.js.map} +1 -1
  22. package/dist/{chunk-VVX2O7XN.js → chunk-S5BMBKUR.js} +19 -14
  23. package/dist/{chunk-VVX2O7XN.js.map → chunk-S5BMBKUR.js.map} +1 -1
  24. package/dist/{chunk-XWMBFPD5.js → chunk-VW4MYD6N.js} +3 -3
  25. package/dist/{chunk-XWMBFPD5.js.map → chunk-VW4MYD6N.js.map} +1 -1
  26. package/dist/{chunk-WLS37KH3.js → chunk-W3LSSG4T.js} +3 -3
  27. package/dist/{chunk-WLS37KH3.js.map → chunk-W3LSSG4T.js.map} +1 -1
  28. package/dist/{chunk-QYYWWS3U.cjs → chunk-YTND5227.cjs} +2 -2
  29. package/dist/chunk-YTND5227.cjs.map +1 -0
  30. package/dist/{chunk-5FNG2ISL.js → chunk-YY3T5AJK.js} +2 -2
  31. package/dist/chunk-YY3T5AJK.js.map +1 -0
  32. package/dist/datasets/index.cjs +16 -16
  33. package/dist/datasets/index.js +1 -1
  34. package/dist/docs/SKILL.md +1 -1
  35. package/dist/docs/assets/SOURCE_MAP.json +310 -310
  36. package/dist/docs/references/reference-observability-tracing-interfaces.md +3 -0
  37. package/dist/evals/index.cjs +19 -19
  38. package/dist/evals/index.js +2 -2
  39. package/dist/evals/scoreTraces/index.cjs +7 -7
  40. package/dist/evals/scoreTraces/index.js +3 -3
  41. package/dist/harness/index.cjs +16 -16
  42. package/dist/harness/index.js +6 -6
  43. package/dist/index.cjs +2 -2
  44. package/dist/index.js +1 -1
  45. package/dist/integration/index.cjs +2 -2
  46. package/dist/integration/index.js +1 -1
  47. package/dist/llm/index.cjs +12 -12
  48. package/dist/llm/index.js +3 -3
  49. package/dist/loop/index.cjs +14 -14
  50. package/dist/loop/index.js +1 -1
  51. package/dist/mastra/index.cjs +2 -2
  52. package/dist/mastra/index.js +1 -1
  53. package/dist/memory/index.cjs +14 -14
  54. package/dist/memory/index.js +1 -1
  55. package/dist/netlify-BFMLDQM5.js +3 -0
  56. package/dist/{netlify-QDVWIV7X.js.map → netlify-BFMLDQM5.js.map} +1 -1
  57. package/dist/netlify-RN36CL4F.cjs +12 -0
  58. package/dist/{netlify-OZA4BKIK.cjs.map → netlify-RN36CL4F.cjs.map} +1 -1
  59. package/dist/observability/index.cjs +17 -17
  60. package/dist/observability/index.js +1 -1
  61. package/dist/observability/types/tracing.d.ts +2 -0
  62. package/dist/observability/types/tracing.d.ts.map +1 -1
  63. package/dist/processor-provider/index.cjs +10 -10
  64. package/dist/processor-provider/index.js +1 -1
  65. package/dist/processors/index.cjs +42 -42
  66. package/dist/processors/index.js +1 -1
  67. package/dist/provider-registry-6FITK73S.js +3 -0
  68. package/dist/{provider-registry-L3ZZWLYW.js.map → provider-registry-6FITK73S.js.map} +1 -1
  69. package/dist/provider-registry-IHJW2WNI.cjs +40 -0
  70. package/dist/{provider-registry-TLYLLTKR.cjs.map → provider-registry-IHJW2WNI.cjs.map} +1 -1
  71. package/dist/relevance/index.cjs +3 -3
  72. package/dist/relevance/index.js +1 -1
  73. package/dist/storage/constants.cjs +56 -56
  74. package/dist/storage/constants.js +1 -1
  75. package/dist/storage/index.cjs +172 -172
  76. package/dist/storage/index.js +2 -2
  77. package/dist/stream/index.cjs +8 -8
  78. package/dist/stream/index.js +1 -1
  79. package/dist/test-utils/llm-mock.cjs +4 -4
  80. package/dist/test-utils/llm-mock.js +1 -1
  81. package/dist/tool-loop-agent/index.cjs +4 -4
  82. package/dist/tool-loop-agent/index.js +1 -1
  83. package/dist/tools/index.cjs +6 -6
  84. package/dist/tools/index.js +1 -1
  85. package/dist/tools/is-vercel-tool.cjs +2 -2
  86. package/dist/tools/is-vercel-tool.js +1 -1
  87. package/dist/tools/tool-builder/builder.d.ts.map +1 -1
  88. package/dist/tools/tool.d.ts +6 -1
  89. package/dist/tools/tool.d.ts.map +1 -1
  90. package/dist/tools/types.d.ts +15 -0
  91. package/dist/tools/types.d.ts.map +1 -1
  92. package/dist/utils.cjs +23 -23
  93. package/dist/utils.js +1 -1
  94. package/dist/vector/index.cjs +7 -7
  95. package/dist/vector/index.js +1 -1
  96. package/dist/workflows/evented/index.cjs +10 -10
  97. package/dist/workflows/evented/index.js +1 -1
  98. package/dist/workflows/index.cjs +24 -24
  99. package/dist/workflows/index.js +1 -1
  100. package/dist/workspace/index.cjs +67 -67
  101. package/dist/workspace/index.js +1 -1
  102. package/package.json +10 -10
  103. package/dist/chunk-5FNG2ISL.js.map +0 -1
  104. package/dist/chunk-CDXZJ3PO.cjs.map +0 -1
  105. package/dist/chunk-MIAFERSL.js.map +0 -1
  106. package/dist/chunk-QYYWWS3U.cjs.map +0 -1
  107. package/dist/netlify-OZA4BKIK.cjs +0 -12
  108. package/dist/netlify-QDVWIV7X.js +0 -3
  109. package/dist/provider-registry-L3ZZWLYW.js +0 -3
  110. package/dist/provider-registry-TLYLLTKR.cjs +0 -40
@@ -394,6 +394,11 @@ var Tool = class {
394
394
  * Examples of valid tool inputs passed through to the AI SDK.
395
395
  */
396
396
  inputExamples;
397
+ /**
398
+ * Metadata identifying this tool as originating from an MCP server.
399
+ * Set automatically by the MCP client when creating tools.
400
+ */
401
+ mcpMetadata;
397
402
  /**
398
403
  * Creates a new Tool instance with input validation wrapper.
399
404
  *
@@ -423,6 +428,7 @@ var Tool = class {
423
428
  this.toModelOutput = opts.toModelOutput;
424
429
  this.inputExamples = opts.inputExamples;
425
430
  this.mcp = opts.mcp;
431
+ this.mcpMetadata = opts.mcpMetadata;
426
432
  this.onInputStart = opts.onInputStart;
427
433
  this.onInputDelta = opts.onInputDelta;
428
434
  this.onInputAvailable = opts.onInputAvailable;
@@ -556,5 +562,5 @@ function isProviderDefinedTool(tool) {
556
562
  }
557
563
 
558
564
  export { MASTRA_TOOL_MARKER, Tool, createTool, isMastraTool, isProviderDefinedTool, isVercelTool, validateToolInput, validateToolOutput, validateToolSuspendData };
559
- //# sourceMappingURL=chunk-MIAFERSL.js.map
560
- //# sourceMappingURL=chunk-MIAFERSL.js.map
565
+ //# sourceMappingURL=chunk-7UM6FE6A.js.map
566
+ //# sourceMappingURL=ch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AQ,IAAA,CAAK,IAAI,qBAAqB,CAAA;AAErG,QAAA,IAAI,iBAAiB,KAAA,EAAO;AAC1B,UAAA,OAAO,gBAAA,CAAiB,KAAA;AAAA,QAC1B;AAEA,QAAA,OAAO,gBAAA,CAAiB,IAAA;AAAA,MAC1B,CAAA;AAAA,IACF;AAAA,EACF;AACF;AA0GO,SAAS,WAUd,IAAA,EASA;AACA,EAAA,OAAO,IAAI,KAAK,IAAI,CAAA;AACtB;;;ACngBO,SAAS,aAAa,IAAA,EAAwB;AACnD,EAAA,OAAO,gBAAgB,IAAA,IAAS,OAAO,SAAS,QAAA,IAAY,IAAA,KAAS,QAAQ,kBAAA,IAAsB,IAAA;AACrG;AAOO,SAAS,aAAa,IAAA,EAA0C;AAKrE,EAAA,OAAO,CAAC,EACN,IAAA,IACA,CAAC,aAAa,IAAI,CAAA,KACjB,YAAA,IAAgB,IAAA,IAAS,aAAa,IAAA,IAAQ,OAAO,IAAA,CAAK,OAAA,KAAY,cAAc,aAAA,IAAiB,IAAA,CAAA,CAAA;AAE1G;AAWO,SAAS,sBAAsB,IAAA,EAAwB;AAC5D,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,IAAA,KAAS,MAAM,OAAO,KAAA;AACtD,EAAA,MAAM,CAAA,GAAI,IAAA;AACV,EAAA,MAAM,cAAA,GAAiB,CAAA,CAAE,IAAA,KAAS,kBAAA,IAAsB,EAAE,IAAA,KAAS,UAAA;AACnE,EAAA,OAAO,cAAA,IAAkB,OAAO,CAAA,CAAE,EAAA,KAAO,QAAA;AAC3C","file":"chunk-7UM6FE6A.js","sourcesContent":["import type { RequestContext } from '../request-context';\nimport { toStandardSchema, standardSchemaToJSONSchema } from '../schema';\nimport type { PublicSchema, StandardSchemaWithJSON, StandardSchemaIssue } from '../schema';\nimport { getZodTypeName, isZodArray, isZodObject, unwrapZodType } from '../utils/zod-utils';\n\n/**\n * Safely validates data against a Standard Schema.\n * Catches internal Zod errors (like undefined union options) and provides better error messages.\n *\n * @param schema The Standard Schema to validate against\n * @param data The data to validate\n * @returns The validation result or throws with a descriptive error\n */\nfunction safeValidate<T>(\n schema: StandardSchemaWithJSON<T>,\n data: unknown,\n): { value: T } | { issues: readonly StandardSchemaIssue[] } {\n try {\n const result = schema['~standard'].validate(data);\n if (result instanceof Promise) {\n throw new Error('Your schema is async, which is not supported. Please use a sync schema.');\n }\n return result as { value: T } | { issues: readonly StandardSchemaIssue[] };\n } catch (err) {\n // Catch Zod internal errors like \"Cannot read properties of undefined (reading 'run')\"\n // This happens when a union schema has undefined options\n if (err instanceof TypeError && err.message.includes('Cannot read properties of undefined')) {\n throw new Error(\n `Schema validation failed due to an invalid schema definition. ` +\n `This often happens when a union schema (z.union or z.or) has undefined options. ` +\n `Please check that all schema options are properly defined. Original error: ${err.message}`,\n );\n }\n throw err;\n }\n}\n\n/**\n * Formatted validation errors structure.\n * Contains `errors` array for messages at this level, and `fields` for nested field errors.\n */\nexport type FormattedValidationErrors<T = unknown> = {\n errors: string[];\n fields: T extends object ? { [K in keyof T]?: FormattedValidationErrors<T[K]> } : unknown;\n};\n\nexport interface ValidationError<T = unknown> {\n error: true;\n message: string;\n validationErrors: FormattedValidationErrors<T>;\n}\n/**\n * Extracts a string key from a path segment (handles both PropertyKey and PathSegment objects).\n */\nfunction getPathKey(segment: PropertyKey | { key: PropertyKey }): string {\n if (typeof segment === 'object' && segment !== null && 'key' in segment) {\n return String(segment.key);\n }\n return String(segment);\n}\n\n/**\n * Creates an empty FormattedValidationErrors object.\n */\nfunction createEmptyErrors(): { errors: string[]; fields: Record<string, unknown> } {\n return { errors: [], fields: {} };\n}\n\n/**\n * Builds a formatted errors object from standard schema validation issues.\n *\n * @param issues Array of validation issues from standard schema validation\n * @returns Formatted errors object with nested structure based on paths\n */\nfunction buildFormattedErrors<T>(issues: readonly StandardSchemaIssue[]): FormattedValidationErrors<T> {\n const result = createEmptyErrors();\n\n for (const issue of issues) {\n if (!issue.path || issue.path.length === 0) {\n // Root-level error\n result.errors.push(issue.message);\n } else {\n // Nested error - build path through fields\n let current = result;\n for (let i = 0; i < issue.path.length; i++) {\n const key = getPathKey(issue.path[i]!);\n if (i === issue.path.length - 1) {\n // Last segment - add the error message\n if (!current.fields[key]) {\n current.fields[key] = createEmptyErrors();\n }\n (current.fields[key] as { errors: string[]; fields: Record<string, unknown> }).errors.push(issue.message);\n } else {\n // Intermediate segment - ensure object exists\n if (!current.fields[key]) {\n current.fields[key] = createEmptyErrors();\n }\n current = current.fields[key] as { errors: string[]; fields: Record<string, unknown> };\n }\n }\n }\n }\n\n return result as FormattedValidationErrors<T>;\n}\n\n/**\n * Safely truncates data for error messages to avoid exposing sensitive information.\n * @param data The data to truncate\n * @param maxLength Maximum length of the truncated string (default: 200)\n * @returns Truncated string representation\n */\nfunction truncateForLogging(data: unknown, maxLength: number = 200): string {\n try {\n const stringified = JSON.stringify(data, null, 2);\n if (stringified.length <= maxLength) {\n return stringified;\n }\n return stringified.slice(0, maxLength) + '... (truncated)';\n } catch {\n return '[Unable to serialize data]';\n }\n}\n\n/**\n * Validates raw suspend data against a schema.\n *\n * @param schema The schema to validate against\n * @param suspendData The raw suspend data to validate\n * @param toolId Optional tool ID for better error messages\n * @returns The validated data or a validation error\n */\nexport function validateToolSuspendData<T = unknown>(\n schema: StandardSchemaWithJSON<T> | undefined,\n suspendData: unknown,\n toolId?: string,\n): { data: T; error?: undefined } | { data?: undefined; error: ValidationError<T> } {\n // If no schema, or schema is not a Standard Schema, return suspend data as-is\n if (!schema || !('~standard' in schema)) {\n return { data: suspendData as T };\n }\n\n // Validate the input using standard schema interface\n const validation = safeValidate(schema, suspendData);\n\n if ('value' in validation) {\n return { data: validation.value };\n }\n\n // Validation failed, return error\n const errorMessages = validation.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n const error: ValidationError<T> = {\n error: true,\n message: `Tool suspension data validation failed${toolId ? ` for ${toolId}` : ''}. Please fix the following errors and try again:\\n${errorMessages}\\n\\nProvided arguments: ${truncateForLogging(suspendData)}`,\n validationErrors: buildFormattedErrors<T>(validation.issues),\n };\n\n return { error };\n}\n\n/**\n * Normalizes undefined/null input to an appropriate default value based on schema type.\n * This handles LLMs (Claude Sonnet 4.5, Gemini 2.4, etc.) that send undefined/null\n * instead of {} or [] when all parameters are optional.\n *\n * @param schema The Zod schema to check\n * @param input The input to normalize\n * @returns The normalized input (original value, {}, or [])\n */\nfunction normalizeNullishInput(schema: StandardSchemaWithJSON<any>, input: unknown): unknown {\n if (typeof input !== 'undefined' && input !== null) {\n return input;\n }\n\n const jsonSchema = standardSchemaToJSONSchema(schema, { io: 'input' });\n\n // Check if schema is an array type (using typeName to avoid dual-package hazard)\n if (jsonSchema.type === 'array') {\n return [];\n }\n\n // Check if schema is an object type (using typeName to avoid dual-package hazard)\n if (jsonSchema.type === 'object') {\n return {};\n }\n\n // For other schema types, return the original input and let Zod validate\n return input;\n}\n\n/**\n * Checks if a value is a plain object (created by {} or new Object()).\n * This excludes class instances, built-in objects like Date/Map/URL, etc.\n *\n * @param value The value to check\n * @returns true if the value is a plain object\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Recursively converts undefined values to null in an object.\n * This is needed for OpenAI compat layers which convert .optional() to .nullable()\n * for strict mode compliance. When fields are omitted (undefined), we convert them\n * to null so the schema validation passes, and the transform then converts null back\n * to undefined. (GitHub #11457)\n *\n * Only recurses into plain objects to preserve class instances and built-in objects\n * like Date, Map, URL, etc. (GitHub #11502)\n *\n * @param input The input to process\n * @returns The processed input with undefined values converted to null\n */\nfunction convertUndefinedToNull(input: unknown): unknown {\n if (input === undefined) {\n return null;\n }\n\n if (input === null || typeof input !== 'object') {\n return input;\n }\n\n if (Array.isArray(input)) {\n return input.map(convertUndefinedToNull);\n }\n\n // Only recurse into plain objects - preserve class instances, built-in objects\n // (Date, Map, Set, URL, etc.) and any other non-plain objects\n if (!isPlainObject(input)) {\n return input;\n }\n\n // It's a plain object - recursively process all properties\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(input)) {\n result[key] = convertUndefinedToNull(value);\n }\n return result;\n}\n\n/**\n * Recursively strips null/undefined values from object properties.\n * This handles LLMs (e.g. Gemini) that send null for .optional() fields,\n * where Zod expects undefined, not null. By stripping nullish values,\n * we let Zod treat them as \"not provided\" which matches .optional() semantics.\n * (GitHub #12362)\n *\n * @param input The input to process\n * @returns The processed input with null/undefined values stripped from objects\n */\nfunction stripNullishValues(input: unknown): unknown {\n // Top-level null/undefined becomes undefined\n if (input === null || input === undefined) {\n return undefined;\n }\n\n if (typeof input !== 'object') {\n return input;\n }\n\n if (Array.isArray(input)) {\n // For arrays, recursively process elements but keep nulls in arrays\n // (array elements with null may be intentional)\n return input.map(item => (item === null ? null : stripNullishValues(item)));\n }\n\n // Only recurse into plain objects - preserve class instances, built-in objects\n if (!isPlainObject(input)) {\n return input;\n }\n\n // It's a plain object - recursively process all properties, omitting null/undefined values\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(input)) {\n if (value === null || value === undefined) {\n // Omit null/undefined values - equivalent to \"not provided\" for optional fields\n continue;\n }\n result[key] = stripNullishValues(value);\n }\n return result;\n}\n\n/**\n * Strip null/undefined values only at specific paths that caused validation errors.\n * Preserves null for .nullable() fields that are valid.\n */\nfunction stripNullishValuesAtPaths(input: unknown, paths: Set<string>, currentPath = ''): unknown {\n if (input === null || input === undefined) {\n return paths.has(currentPath) ? undefined : input;\n }\n\n if (typeof input !== 'object') {\n return input;\n }\n\n if (Array.isArray(input)) {\n return input.map((item, i) =>\n stripNullishValuesAtPaths(item, paths, currentPath ? `${currentPath}.${i}` : String(i)),\n );\n }\n\n if (!isPlainObject(input)) {\n return input;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(input)) {\n const fieldPath = currentPath ? `${currentPath}.${key}` : key;\n if ((value === null || value === undefined) && paths.has(fieldPath)) {\n // Only omit null/undefined for fields that caused validation errors\n continue;\n }\n result[key] = stripNullishValuesAtPaths(value, paths, fieldPath);\n }\n return result;\n}\n\n/**\n * Coerces stringified JSON values in object properties when the schema expects\n * an array or object but the LLM returned a JSON string.\n *\n * Some LLMs (e.g., GLM4.7) return stringified JSON for array/object parameters:\n * { \"args\": \"[\\\"parse_excel.py\\\"]\" }\n * instead of:\n * { \"args\": [\"parse_excel.py\"] }\n *\n * This function walks the top-level properties of a plain object and attempts\n * to JSON.parse string values when the schema expects a non-string type.\n * (GitHub #12757)\n *\n * @param schema The Zod schema to check field types against\n * @param input The input to process\n * @returns The input with stringified JSON values coerced, or the original input\n */\nfunction coerceStringifiedJsonValues(schema: StandardSchemaWithJSON<unknown>, input: unknown): unknown {\n // Only process plain objects with object schemas\n if (!isPlainObject(input)) {\n return input;\n }\n\n const unwrapped = unwrapZodType(schema as any);\n if (!isZodObject(unwrapped)) {\n return input;\n }\n\n const shape = (unwrapped as any).shape;\n if (!shape || typeof shape !== 'object') {\n return input;\n }\n\n let changed = false;\n const result: Record<string, unknown> = { ...input };\n\n for (const [key, value] of Object.entries(input)) {\n if (typeof value !== 'string') {\n continue;\n }\n\n const fieldSchema = shape[key];\n if (!fieldSchema) {\n continue;\n }\n\n // Unwrap the field schema to find the base type\n const baseFieldSchema = unwrapZodType(fieldSchema);\n\n // Only attempt coercion if the schema expects a non-string type\n // and the string looks like it could be JSON (starts with [ or {)\n if (getZodTypeName(baseFieldSchema) === 'ZodString') {\n continue;\n }\n\n const trimmed = value.trim();\n if (\n (isZodArray(baseFieldSchema) && trimmed.startsWith('[')) ||\n (isZodObject(baseFieldSchema) && trimmed.startsWith('{'))\n ) {\n try {\n const parsed = JSON.parse(value);\n if (\n (isZodArray(baseFieldSchema) && Array.isArray(parsed)) ||\n (isZodObject(baseFieldSchema) && isPlainObject(parsed))\n ) {\n result[key] = parsed;\n changed = true;\n }\n } catch {\n // Not valid JSON, leave as-is\n }\n }\n }\n\n return changed ? result : input;\n}\n\n/**\n * Validates raw input data against a schema.\n *\n * @param schema The schema to validate against (or undefined to skip validation)\n * @param input The raw input data to validate\n * @param toolId Optional tool ID for better error messages\n * @returns The validated data or a validation error\n */\nexport function validateToolInput<T = unknown>(\n schema: StandardSchemaWithJSON<T> | undefined,\n input: unknown,\n toolId?: string,\n): { data: T; error?: undefined } | { data?: undefined; error: ValidationError<T> } {\n // If no schema, or schema is not a Standard Schema (e.g. plain JSON Schema from Vercel tools),\n // return input as-is. Only validate when we have a proper Standard Schema with ~standard.validate.\n if (!schema || !('~standard' in schema)) {\n return { data: input as T };\n }\n\n // Validation pipeline:\n //\n // 1. normalizeNullishInput: Convert top-level null/undefined to {} or [] based on schema type.\n // Handles LLMs that send undefined instead of {} or [] for all-optional parameters.\n //\n // 2. convertUndefinedToNull: Convert undefined values to null in object properties.\n // Needed for OpenAI compat layers that convert .optional() to .nullable() for\n // strict mode compliance. The schema's transform converts null back to undefined.\n // (GitHub #11457)\n //\n // 3. First validation attempt with null values preserved. This handles .nullable()\n // schemas correctly (where null is a valid value).\n //\n // 4. If validation fails, retry with stringified JSON values coerced to their\n // proper types. Some LLMs (e.g. GLM4.7) return JSON arrays/objects as strings.\n // (GitHub #12757)\n //\n // 5. If validation still fails, retry with null values stripped from object properties.\n // This handles LLMs (e.g. Gemini) that send null for .optional() fields, where\n // Zod expects undefined, not null. (GitHub #12362)\n\n // Step 1: Normalize top-level null/undefined to appropriate default\n let normalizedInput = normalizeNullishInput(schema, input);\n\n // Step 2: Convert undefined values to null recursively (GitHub #11457)\n normalizedInput = convertUndefinedToNull(normalizedInput);\n\n // Step 3: Validate the normalized input\n const validation = safeValidate(schema, normalizedInput);\n\n if ('value' in validation) {\n return { data: validation.value };\n }\n\n // Step 4: Retry with stringified JSON values coerced (GitHub #12757)\n // LLMs like GLM4.7 send stringified JSON for array/object parameters, e.g.\n // { \"args\": \"[\\\"file.py\\\"]\" } instead of { \"args\": [\"file.py\"] }.\n const coercedInput = coerceStringifiedJsonValues(schema, normalizedInput);\n if (coercedInput !== normalizedInput) {\n const coercedValidation = safeValidate(schema, coercedInput);\n if ('value' in coercedValidation) {\n return { data: coercedValidation.value };\n }\n }\n\n // Step 5: Retry with null values stripped only for failing fields (GitHub #12362)\n // LLMs like Gemini send null for optional fields, but Zod's .optional() only\n // accepts undefined, not null. We only strip nulls for fields that caused\n // validation errors, preserving null for .nullable() schemas that need it.\n const failingNullPaths = new Set(\n validation.issues\n .filter(issue => issue.message?.includes('null'))\n .map(issue => issue.path?.map(p => (typeof p === 'object' && 'key' in p ? String(p.key) : String(p))).join('.'))\n .filter((p): p is string => !!p),\n );\n const strippedInput =\n failingNullPaths.size > 0 ? stripNullishValuesAtPaths(input, failingNullPaths) : stripNullishValues(input);\n const normalizedStripped = normalizeNullishInput(schema, strippedInput);\n const retryValidation = safeValidate(schema, normalizedStripped);\n\n if ('value' in retryValidation) {\n return { data: retryValidation.value };\n }\n\n // All attempts failed - return the original (non-stripped) error since it's\n // more informative about what the schema actually expects\n const errorMessages = validation.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n const error: ValidationError<T> = {\n error: true,\n message: `Tool input validation failed${toolId ? ` for ${toolId}` : ''}. Please fix the following errors and try again:\\n${errorMessages}\\n\\nProvided arguments: ${truncateForLogging(input)}`,\n validationErrors: buildFormattedErrors<T>(validation.issues),\n };\n\n return { error };\n}\n\n/**\n * Validates tool output data against a schema.\n *\n * @param schema The schema to validate against\n * @param output The output data to validate\n * @param toolId Optional tool ID for better error messages\n * @returns The validated data or a validation error\n */\nexport function validateToolOutput<T = unknown>(\n schema: StandardSchemaWithJSON<T> | undefined,\n output: unknown,\n toolId?: string,\n suspendCalled?: boolean,\n): { data: T; error?: undefined } | { data?: undefined; error: ValidationError<T> } {\n // If no schema, not a Standard Schema, or suspend was called, return output as-is\n if (!schema || !('~standard' in schema) || suspendCalled) {\n return { data: output as T };\n }\n\n // Validate the output using standard schema interface\n const validation = safeValidate(schema, output);\n\n if ('value' in validation) {\n return { data: validation.value };\n }\n\n // Validation failed, return error\n const errorMessages = validation.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n const error: ValidationError<T> = {\n error: true,\n message: `Tool output validation failed${toolId ? ` for ${toolId}` : ''}. The tool returned invalid output:\\n${errorMessages}\\n\\nReturned output: ${truncateForLogging(output)}`,\n validationErrors: buildFormattedErrors<T>(validation.issues),\n };\n\n return { error };\n}\n\n/**\n * Keys that are considered sensitive and should be redacted in error messages.\n */\nconst SENSITIVE_KEYS = ['password', 'secret', 'token', 'apiKey', 'api_key', 'auth', 'credential'];\n\n/**\n * Redacts sensitive keys from an object for safe logging.\n * @param obj The object to redact\n * @returns A new object with sensitive values replaced with '[REDACTED]'\n */\nfunction redactSensitiveKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(redactSensitiveKeys);\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (SENSITIVE_KEYS.some(sensitive => key.toLowerCase().includes(sensitive.toLowerCase()))) {\n result[key] = '[REDACTED]';\n } else if (typeof value === 'object' && value !== null) {\n result[key] = redactSensitiveKeys(value);\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * Validates request context data against a schema.\n * This is used to validate the request context before tool execution.\n *\n * @param schema The schema to validate against (PublicSchema which accepts Zod v3/v4, JSONSchema, etc.)\n * @param requestContext The request context to validate\n * @param identifier Optional identifier (tool/step ID) for better error messages\n * @returns The validated data or a validation error\n */\nexport function validateRequestContext<T = any>(\n schema: PublicSchema<T> | undefined,\n requestContext: RequestContext | undefined,\n identifier?: string,\n): { data: T | Record<string, any>; error?: ValidationError<T> } {\n // If no schema, return request context values as-is\n if (!schema) {\n return { data: (requestContext?.all ?? {}) as T };\n }\n\n // Get the values from request context\n const contextValues = requestContext?.all ?? {};\n\n // Convert PublicSchema to StandardSchemaWithJSON for validation\n const standardSchema = toStandardSchema(schema);\n\n // Validate using standard schema interface\n const validation = standardSchema['~standard'].validate(contextValues);\n\n if (validation instanceof Promise) {\n throw new Error('Your schema is async, which is not supported. Please use a sync schema.');\n }\n\n if ('value' in validation) {\n return { data: validation.value };\n }\n\n // Validation failed, return error\n const errorMessages = validation.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n // Redact sensitive keys before including in error message\n const redactedContext = redactSensitiveKeys(contextValues);\n\n const error: ValidationError<T> = {\n error: true,\n message: `Request context validation failed${identifier ? ` for ${identifier}` : ''}. Please fix the following errors and try again:\\n${errorMessages}\\n\\nProvided request context: ${truncateForLogging(redactedContext)}`,\n validationErrors: buildFormattedErrors<T>(validation.issues),\n };\n\n return { data: contextValues as T, error };\n}\n","import type { Mastra } from '../mastra';\nimport { RequestContext } from '../request-context';\nimport { toStandardSchema } from '../schema';\nimport type { PublicSchema, StandardSchemaWithJSON, InferPublicSchema } from '../schema';\nimport type { SuspendOptions } from '../workflows';\nimport type { McpMetadata, MCPToolProperties, ToolAction, ToolExecutionContext } from './types';\nimport { validateToolInput, validateToolOutput, validateToolSuspendData, validateRequestContext } from './validation';\n\n/**\n * Marker to identify Mastra tools even when `instanceof` fails.\n * This can happen in environments like Vite SSR where the same module\n * may be loaded multiple times, creating different class instances.\n * Uses Symbol.for() so the same symbol is shared across module copies.\n * Follows the naming convention: <org>.<product>.<category>.<className>\n */\nexport const MASTRA_TOOL_MARKER = Symbol.for('mastra.core.tool.Tool');\n\n/**\n * A type-safe tool that agents and workflows can call to perform specific actions.\n *\n * @template TSchemaIn - Input schema type\n * @template TSchemaOut - Output schema type\n * @template TSuspendSchema - Suspend operation schema type\n * @template TResumeSchema - Resume operation schema type\n * @template TContext - Execution context type\n *\n * @example Basic tool with validation\n * ```typescript\n * const weatherTool = createTool({\n * id: 'get-weather',\n * description: 'Get weather for a location',\n * inputSchema: z.object({\n * location: z.string(),\n * units: z.enum(['celsius', 'fahrenheit']).optional()\n * }),\n * execute: async (inputData) => {\n * return await fetchWeather(inputData.location, inputData.units);\n * }\n * });\n * ```\n *\n * @example Tool requiring approval\n * ```typescript\n * const deleteFileTool = createTool({\n * id: 'delete-file',\n * description: 'Delete a file',\n * requireApproval: true,\n * inputSchema: z.object({ filepath: z.string() }),\n * execute: async (inputData) => {\n * await fs.unlink(inputData.filepath);\n * return { deleted: true };\n * }\n * });\n * ```\n *\n * @example Tool with Mastra integration\n * ```typescript\n * const saveTool = createTool({\n * id: 'save-data',\n * description: 'Save data to storage',\n * inputSchema: z.object({ key: z.string(), value: z.any() }),\n * execute: async (inputData, context) => {\n * const storage = context?.mastra?.getStorage();\n * await storage?.set(inputData.key, inputData.value);\n * return { saved: true };\n * }\n * });\n * ```\n */\nexport class Tool<\n TSchemaIn = unknown,\n TSchemaOut = unknown,\n TSuspendSchema = unknown,\n TResumeSchema = unknown,\n TContext extends ToolExecutionContext<TSuspendSchema, TResumeSchema, any> = ToolExecutionContext<\n TSuspendSchema,\n TResumeSchema\n >,\n TId extends string = string,\n TRequestContext extends Record<string, any> | unknown = unknown,\n> implements ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext> {\n /** Unique identifier for the tool */\n id: TId;\n\n /** Description of what the tool does */\n description: string;\n\n /** Schema for validating input parameters */\n inputSchema?: StandardSchemaWithJSON<TSchemaIn>;\n\n /** Schema for validating output structure */\n outputSchema?: StandardSchemaWithJSON<TSchemaOut>;\n\n /** Schema for suspend operation data */\n suspendSchema?: StandardSchemaWithJSON<TSuspendSchema>;\n\n /** Schema for resume operation data */\n resumeSchema?: StandardSchemaWithJSON<TResumeSchema>;\n\n /**\n * Schema for validating request context values.\n * When provided, the request context will be validated against this schema before tool execution.\n */\n requestContextSchema?: PublicSchema<TRequestContext>;\n\n /**\n * Tool execution function\n * @param inputData - The raw, validated input data\n * @param context - Optional execution context with metadata\n * @returns Promise resolving to tool output or a ValidationError if input validation fails\n */\n execute?: ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext>['execute'];\n\n /** Parent Mastra instance for accessing shared resources */\n mastra?: Mastra;\n\n /**\n * Whether the tool requires explicit user approval before execution\n * @example\n * ```typescript\n * // For destructive operations\n * requireApproval: true\n * ```\n */\n requireApproval?: boolean;\n\n /**\n * Provider-specific options passed to the model when this tool is used.\n * Keys are provider names (e.g., 'anthropic', 'openai'), values are provider-specific configs.\n * @example\n * ```typescript\n * providerOptions: {\n * anthropic: {\n * cacheControl: { type: 'ephemeral' }\n * }\n * }\n * ```\n */\n providerOptions?: Record<string, Record<string, unknown>>;\n\n /**\n * Optional function to transform the tool's raw output before sending it to the model.\n * The raw result is still available for application logic; only the model sees the transformed version.\n */\n toModelOutput?: (output: TSchemaOut) => unknown;\n\n /**\n * Optional MCP-specific properties including annotations and metadata.\n * Only relevant when the tool is being used in an MCP context.\n * @example\n * ```typescript\n * mcp: {\n * annotations: {\n * title: 'Weather Lookup',\n * readOnlyHint: true,\n * destructiveHint: false\n * },\n * _meta: {\n * version: '1.0.0',\n * author: 'team@example.com'\n * }\n * }\n * ```\n */\n mcp?: MCPToolProperties;\n\n onInputStart?: ToolAction<\n TSchemaIn,\n TSchemaOut,\n TSuspendSchema,\n TResumeSchema,\n TContext,\n TId,\n TRequestContext\n >['onInputStart'];\n onInputDelta?: ToolAction<\n TSchemaIn,\n TSchemaOut,\n TSuspendSchema,\n TResumeSchema,\n TContext,\n TId,\n TRequestContext\n >['onInputDelta'];\n onInputAvailable?: ToolAction<\n TSchemaIn,\n TSchemaOut,\n TSuspendSchema,\n TResumeSchema,\n TContext,\n TId,\n TRequestContext\n >['onInputAvailable'];\n onOutput?: ToolAction<\n TSchemaIn,\n TSchemaOut,\n TSuspendSchema,\n TResumeSchema,\n TContext,\n TId,\n TRequestContext\n >['onOutput'];\n\n /**\n * Examples of valid tool inputs passed through to the AI SDK.\n */\n inputExamples?: Array<{ input: Record<string, unknown> }>;\n\n /**\n * Metadata identifying this tool as originating from an MCP server.\n * Set automatically by the MCP client when creating tools.\n */\n mcpMetadata?: McpMetadata;\n\n /**\n * Creates a new Tool instance with input validation wrapper.\n *\n * @param opts - Tool configuration and execute function\n * @example\n * ```typescript\n * const tool = new Tool({\n * id: 'my-tool',\n * description: 'Does something useful',\n * inputSchema: z.object({ name: z.string() }),\n * execute: async (inputData) => ({ greeting: `Hello ${inputData.name}` })\n * });\n * ```\n */\n constructor(opts: ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext>) {\n (this as any)[MASTRA_TOOL_MARKER] = true;\n this.id = opts.id;\n this.description = opts.description;\n this.inputSchema = opts.inputSchema ? toStandardSchema(opts.inputSchema) : undefined;\n this.outputSchema = opts.outputSchema ? toStandardSchema(opts.outputSchema) : undefined;\n this.suspendSchema = opts.suspendSchema ? toStandardSchema(opts.suspendSchema) : undefined;\n this.resumeSchema = opts.resumeSchema ? toStandardSchema(opts.resumeSchema) : undefined;\n this.requestContextSchema = opts.requestContextSchema;\n this.mastra = opts.mastra;\n this.requireApproval = opts.requireApproval || false;\n this.providerOptions = opts.providerOptions;\n this.toModelOutput = opts.toModelOutput;\n this.inputExamples = opts.inputExamples;\n this.mcp = opts.mcp;\n this.mcpMetadata = opts.mcpMetadata;\n this.onInputStart = opts.onInputStart;\n this.onInputDelta = opts.onInputDelta;\n this.onInputAvailable = opts.onInputAvailable;\n this.onOutput = opts.onOutput;\n\n // Tools receive two parameters:\n // 1. input - The raw, validated input data\n // 2. context - Execution metadata (mastra, suspend, etc.)\n if (opts.execute) {\n const originalExecute = opts.execute;\n this.execute = async (inputData: TSchemaIn, context?: any) => {\n // Validate input if schema exists\n const { data, error } = validateToolInput(this.inputSchema, inputData, this.id);\n if (error) {\n return error;\n }\n\n // Validate request context if schema exists\n const { error: requestContextError } = validateRequestContext(\n this.requestContextSchema,\n context?.requestContext,\n this.id,\n );\n if (requestContextError) {\n return requestContextError as any;\n }\n\n let suspendData = null;\n\n const baseContext = context\n ? {\n ...context,\n ...(context.suspend\n ? {\n suspend: (args: any, suspendOptions?: SuspendOptions) => {\n suspendData = args;\n return context.suspend?.(args, suspendOptions);\n },\n }\n : {}),\n }\n : {};\n\n // Organize context based on execution source\n let organizedContext = baseContext;\n if (!context) {\n // No context provided - create a minimal context with requestContext\n organizedContext = {\n requestContext: new RequestContext(),\n mastra: undefined,\n };\n } else {\n // Check if this is agent execution (has toolCallId and messages)\n const isAgentExecution = baseContext.toolCallId && baseContext.messages;\n\n // Check if this is workflow execution (has workflow properties)\n // Agent execution takes precedence - don't treat as workflow if it's an agent call\n const isWorkflowExecution = !isAgentExecution && (baseContext.workflow || baseContext.workflowId);\n\n if (isAgentExecution && !baseContext.agent) {\n // Reorganize agent context - nest agent-specific properties under 'agent' key\n const { toolCallId, messages, suspend, resumeData, threadId, resourceId, writableStream, ...rest } =\n baseContext;\n organizedContext = {\n ...rest,\n agent: {\n toolCallId,\n messages,\n suspend,\n resumeData,\n threadId,\n resourceId,\n writableStream,\n },\n // Ensure requestContext is always present\n requestContext: rest.requestContext || new RequestContext(),\n };\n } else if (isWorkflowExecution && !baseContext.workflow) {\n // Reorganize workflow context - nest workflow-specific properties under 'workflow' key\n const { workflowId, runId, state, setState, suspend, resumeData, ...rest } = baseContext;\n organizedContext = {\n ...rest,\n workflow: {\n workflowId,\n runId,\n state,\n setState,\n suspend,\n resumeData,\n },\n // Ensure requestContext is always present\n requestContext: rest.requestContext || new RequestContext(),\n };\n } else {\n // Ensure requestContext is always present even for direct execution\n organizedContext = {\n ...baseContext,\n agent: baseContext.agent\n ? {\n ...baseContext.agent,\n suspend: (args: any, suspendOptions?: SuspendOptions) => {\n suspendData = args;\n return baseContext.agent?.suspend?.(args, suspendOptions);\n },\n }\n : baseContext.agent,\n workflow: baseContext.workflow\n ? {\n ...baseContext.workflow,\n suspend: (args: any, suspendOptions?: SuspendOptions) => {\n suspendData = args;\n return baseContext.workflow?.suspend?.(args, suspendOptions);\n },\n }\n : baseContext.workflow,\n requestContext: baseContext.requestContext || new RequestContext(),\n };\n }\n }\n\n const resumeData =\n organizedContext.agent?.resumeData ?? organizedContext.workflow?.resumeData ?? organizedContext?.resumeData;\n\n if (resumeData) {\n const resumeValidation = validateToolInput(this.resumeSchema, resumeData, this.id);\n if (resumeValidation.error) {\n return resumeValidation.error as any;\n }\n }\n\n // Call the original execute with validated input and organized context\n const output = await originalExecute(data as any, organizedContext);\n\n if (suspendData) {\n const suspendValidation = validateToolSuspendData(this.suspendSchema, suspendData, this.id);\n if (suspendValidation.error) {\n return suspendValidation.error as any;\n }\n }\n\n const skiptOutputValidation = !!(typeof output === 'undefined' && suspendData);\n\n // Validate output if schema exists\n const outputValidation = validateToolOutput(this.outputSchema, output, this.id, skiptOutputValidation);\n\n if (outputValidation.error) {\n return outputValidation.error as any;\n }\n\n return outputValidation.data;\n };\n }\n }\n}\n\n/**\n * Creates a type-safe tool with automatic input validation.\n *\n * @template TSchemaIn - Input schema type\n * @template TSchemaOut - Output schema type\n * @template TSuspendSchema - Suspend operation schema type\n * @template TResumeSchema - Resume operation schema type\n * @template TContext - Execution context type\n * @template TExecute - Execute function type\n *\n * @param opts - Tool configuration including schemas and execute function\n * @returns Type-safe Tool instance with conditional typing based on schemas\n *\n * @example Simple tool\n * ```typescript\n * const greetTool = createTool({\n * id: 'greet',\n * description: 'Say hello',\n * execute: async () => ({ message: 'Hello!' })\n * });\n * ```\n *\n * @example Tool with input validation\n * ```typescript\n * const calculateTool = createTool({\n * id: 'calculate',\n * description: 'Perform calculations',\n * inputSchema: z.object({\n * operation: z.enum(['add', 'subtract']),\n * a: z.number(),\n * b: z.number()\n * }),\n * execute: async (inputData) => {\n * const result = inputData.operation === 'add'\n * ? inputData.a + inputData.b\n * : inputData.a - inputData.b;\n * return { result };\n * }\n * });\n * ```\n *\n * @example Tool with output schema\n * ```typescript\n * const userTool = createTool({\n * id: 'get-user',\n * description: 'Get user data',\n * inputSchema: z.object({ userId: z.string() }),\n * outputSchema: z.object({\n * id: z.string(),\n * name: z.string(),\n * email: z.string()\n * }),\n * execute: async (inputData) => {\n * return await fetchUser(inputData.userId);\n * }\n * });\n * ```\n *\n * @example Tool with external API\n * ```typescript\n * const weatherTool = createTool({\n * id: 'weather',\n * description: 'Get weather data',\n * inputSchema: z.object({\n * city: z.string(),\n * units: z.enum(['metric', 'imperial']).default('metric')\n * }),\n * execute: async (inputData) => {\n * const response = await fetch(\n * `https://api.weather.com/v1/weather?q=${inputData.city}&units=${inputData.units}`\n * );\n * return response.json();\n * }\n * });\n * ```\n */\ntype SchemaLike = PublicSchema<any> | undefined;\ntype InferSchema<T extends SchemaLike> = T extends PublicSchema<any> ? InferPublicSchema<T> : unknown;\n\ntype CreateToolOpts<\n TId extends string,\n TInputSchema extends SchemaLike,\n TOutputSchema extends SchemaLike,\n TSuspendSchema extends SchemaLike,\n TResumeSchema extends SchemaLike,\n TRequestContext,\n TContext extends ToolExecutionContext<InferSchema<TSuspendSchema>, InferSchema<TResumeSchema>, TRequestContext>,\n> = Omit<\n ToolAction<\n InferSchema<TInputSchema>,\n InferSchema<TOutputSchema>,\n InferSchema<TSuspendSchema>,\n InferSchema<TResumeSchema>,\n TContext,\n TId,\n TRequestContext\n >,\n 'inputSchema' | 'outputSchema' | 'suspendSchema' | 'resumeSchema'\n> & {\n inputSchema?: TInputSchema;\n outputSchema?: TOutputSchema;\n suspendSchema?: TSuspendSchema;\n resumeSchema?: TResumeSchema;\n};\nexport function createTool<\n TId extends string = string,\n TInputSchema extends SchemaLike = undefined,\n TOutputSchema extends SchemaLike = undefined,\n TSuspendSchema extends SchemaLike = undefined,\n TResumeSchema extends SchemaLike = undefined,\n TRequestContext extends Record<string, any> | unknown = unknown,\n TContext extends ToolExecutionContext<InferSchema<TSuspendSchema>, InferSchema<TResumeSchema>, TRequestContext> =\n ToolExecutionContext<InferSchema<TSuspendSchema>, InferSchema<TResumeSchema>, TRequestContext>,\n>(\n opts: CreateToolOpts<TId, TInputSchema, TOutputSchema, TSuspendSchema, TResumeSchema, TRequestContext, TContext>,\n): Tool<\n InferSchema<TInputSchema>,\n InferSchema<TOutputSchema>,\n InferSchema<TSuspendSchema>,\n InferSchema<TResumeSchema>,\n TContext,\n TId,\n TRequestContext\n> {\n return new Tool(opts);\n}\n","import { Tool, MASTRA_TOOL_MARKER } from './tool';\nimport type { ToolToConvert } from './tool-builder/builder';\nimport type { VercelTool } from './types';\n\n/**\n * Checks if a tool is a Mastra Tool, using both instanceof and marker.\n * The marker fallback handles environments like Vite SSR where the same\n * module may be loaded multiple times, causing instanceof to fail.\n */\nexport function isMastraTool(tool: unknown): boolean {\n return tool instanceof Tool || (typeof tool === 'object' && tool !== null && MASTRA_TOOL_MARKER in tool);\n}\n\n/**\n * Checks if a tool is a Vercel Tool (AI SDK tool)\n * @param tool - The tool to check\n * @returns True if the tool is a Vercel Tool, false otherwise\n */\nexport function isVercelTool(tool?: ToolToConvert): tool is VercelTool {\n // Checks if this tool is not an instance of Mastra's Tool class\n // AI SDK tools must have an execute function and either:\n // - 'parameters' (v4) or 'inputSchema' (v5/v6)\n // This prevents plain objects with inputSchema (like client tools) from being treated as VercelTools\n return !!(\n tool &&\n !isMastraTool(tool) &&\n ('parameters' in tool || ('execute' in tool && typeof tool.execute === 'function' && 'inputSchema' in tool))\n );\n}\n\n/**\n * Checks if a tool is a provider-defined tool from the AI SDK.\n * Provider tools (like google.tools.googleSearch(), openai.tools.webSearch()) have:\n * - type: \"provider-defined\" (AI SDK v5) or \"provider\" (AI SDK v6)\n * - id: in format 'provider.tool_name' (e.g., 'google.google_search')\n *\n * These tools have a lazy `inputSchema` function that returns an AI SDK Schema\n * (not a Zod schema), so they require special handling during serialization.\n */\nexport function isProviderDefinedTool(tool: unknown): boolean {\n if (typeof tool !== 'object' || tool === null) return false;\n const t = tool as Record<string, unknown>;\n const isProviderType = t.type === 'provider-defined' || t.type === 'provider';\n return isProviderType && typeof t.id === 'string';\n}\n"]}
@@ -396,6 +396,11 @@ var Tool = class {
396
396
  * Examples of valid tool inputs passed through to the AI SDK.
397
397
  */
398
398
  inputExamples;
399
+ /**
400
+ * Metadata identifying this tool as originating from an MCP server.
401
+ * Set automatically by the MCP client when creating tools.
402
+ */
403
+ mcpMetadata;
399
404
  /**
400
405
  * Creates a new Tool instance with input validation wrapper.
401
406
  *
@@ -425,6 +430,7 @@ var Tool = class {
425
430
  this.toModelOutput = opts.toModelOutput;
426
431
  this.inputExamples = opts.inputExamples;
427
432
  this.mcp = opts.mcp;
433
+ this.mcpMetadata = opts.mcpMetadata;
428
434
  this.onInputStart = opts.onInputStart;
429
435
  this.onInputDelta = opts.onInputDelta;
430
436
  this.onInputAvailable = opts.onInputAvailable;
@@ -566,5 +572,5 @@ exports.isVercelTool = isVercelTool;
566
572
  exports.validateToolInput = validateToolInput;
567
573
  exports.validateToolOutput = validateToolOutput;
568
574
  exports.validateToolSuspendData = validateToolSuspendData;
569
- //# sourceMappingURL=chunk-CDXZJ3PO.cjs.map
570
- //# sourceMappingURL=chunk-CDXZJ3PO.cjs.map
575
+ //# sourceMappingURL=chunk-E7PW4ZAB.cjs.map
576
+ //# sourceMappingURL=chunk-E7PW4ZAB.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tools/validation.ts","../src/tools/tool.ts","../src/tools/toolchecks.ts"],"names":["standardSchemaToJSONSchema","unwrapZodType","isZodObject","getZodTypeName","isZodArray","toStandardSchema","RequestContext","resumeData"],"mappings":";;;;;;;AAaA,SAAS,YAAA,CACP,QACA,IAAA,EAC2D;AAC3D,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,MAAA,CAAO,WAAW,CAAA,CAAE,SAAS,IAAI,CAAA;AAChD,IAAA,IAAI,kBAAkB,OAAA,EAAS;AAC7B,MAAA,MAAM,IAAI,MAAM,yEAAyE,CAAA;AAAA,IAC3F;AACA,IAAA,OAAO,MAAA;AAAA,EACT,SAAS,GAAA,EAAK;AAGZ,IAAA,I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AAS,QAAQ,kBAAA,IAAsB,IAAA;AACrG;AAOO,SAAS,aAAa,IAAA,EAA0C;AAKrE,EAAA,OAAO,CAAC,EACN,IAAA,IACA,CAAC,aAAa,IAAI,CAAA,KACjB,YAAA,IAAgB,IAAA,IAAS,aAAa,IAAA,IAAQ,OAAO,IAAA,CAAK,OAAA,KAAY,cAAc,aAAA,IAAiB,IAAA,CAAA,CAAA;AAE1G;AAWO,SAAS,sBAAsB,IAAA,EAAwB;AAC5D,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,IAAA,KAAS,MAAM,OAAO,KAAA;AACtD,EAAA,MAAM,CAAA,GAAI,IAAA;AACV,EAAA,MAAM,cAAA,GAAiB,CAAA,CAAE,IAAA,KAAS,kBAAA,IAAsB,EAAE,IAAA,KAAS,UAAA;AACnE,EAAA,OAAO,cAAA,IAAkB,OAAO,CAAA,CAAE,EAAA,KAAO,QAAA;AAC3C","file":"chunk-E7PW4ZAB.cjs","sourcesContent":["import type { RequestContext } from '../request-context';\nimport { toStandardSchema, standardSchemaToJSONSchema } from '../schema';\nimport type { PublicSchema, StandardSchemaWithJSON, StandardSchemaIssue } from '../schema';\nimport { getZodTypeName, isZodArray, isZodObject, unwrapZodType } from '../utils/zod-utils';\n\n/**\n * Safely validates data against a Standard Schema.\n * Catches internal Zod errors (like undefined union options) and provides better error messages.\n *\n * @param schema The Standard Schema to validate against\n * @param data The data to validate\n * @returns The validation result or throws with a descriptive error\n */\nfunction safeValidate<T>(\n schema: StandardSchemaWithJSON<T>,\n data: unknown,\n): { value: T } | { issues: readonly StandardSchemaIssue[] } {\n try {\n const result = schema['~standard'].validate(data);\n if (result instanceof Promise) {\n throw new Error('Your schema is async, which is not supported. Please use a sync schema.');\n }\n return result as { value: T } | { issues: readonly StandardSchemaIssue[] };\n } catch (err) {\n // Catch Zod internal errors like \"Cannot read properties of undefined (reading 'run')\"\n // This happens when a union schema has undefined options\n if (err instanceof TypeError && err.message.includes('Cannot read properties of undefined')) {\n throw new Error(\n `Schema validation failed due to an invalid schema definition. ` +\n `This often happens when a union schema (z.union or z.or) has undefined options. ` +\n `Please check that all schema options are properly defined. Original error: ${err.message}`,\n );\n }\n throw err;\n }\n}\n\n/**\n * Formatted validation errors structure.\n * Contains `errors` array for messages at this level, and `fields` for nested field errors.\n */\nexport type FormattedValidationErrors<T = unknown> = {\n errors: string[];\n fields: T extends object ? { [K in keyof T]?: FormattedValidationErrors<T[K]> } : unknown;\n};\n\nexport interface ValidationError<T = unknown> {\n error: true;\n message: string;\n validationErrors: FormattedValidationErrors<T>;\n}\n/**\n * Extracts a string key from a path segment (handles both PropertyKey and PathSegment objects).\n */\nfunction getPathKey(segment: PropertyKey | { key: PropertyKey }): string {\n if (typeof segment === 'object' && segment !== null && 'key' in segment) {\n return String(segment.key);\n }\n return String(segment);\n}\n\n/**\n * Creates an empty FormattedValidationErrors object.\n */\nfunction createEmptyErrors(): { errors: string[]; fields: Record<string, unknown> } {\n return { errors: [], fields: {} };\n}\n\n/**\n * Builds a formatted errors object from standard schema validation issues.\n *\n * @param issues Array of validation issues from standard schema validation\n * @returns Formatted errors object with nested structure based on paths\n */\nfunction buildFormattedErrors<T>(issues: readonly StandardSchemaIssue[]): FormattedValidationErrors<T> {\n const result = createEmptyErrors();\n\n for (const issue of issues) {\n if (!issue.path || issue.path.length === 0) {\n // Root-level error\n result.errors.push(issue.message);\n } else {\n // Nested error - build path through fields\n let current = result;\n for (let i = 0; i < issue.path.length; i++) {\n const key = getPathKey(issue.path[i]!);\n if (i === issue.path.length - 1) {\n // Last segment - add the error message\n if (!current.fields[key]) {\n current.fields[key] = createEmptyErrors();\n }\n (current.fields[key] as { errors: string[]; fields: Record<string, unknown> }).errors.push(issue.message);\n } else {\n // Intermediate segment - ensure object exists\n if (!current.fields[key]) {\n current.fields[key] = createEmptyErrors();\n }\n current = current.fields[key] as { errors: string[]; fields: Record<string, unknown> };\n }\n }\n }\n }\n\n return result as FormattedValidationErrors<T>;\n}\n\n/**\n * Safely truncates data for error messages to avoid exposing sensitive information.\n * @param data The data to truncate\n * @param maxLength Maximum length of the truncated string (default: 200)\n * @returns Truncated string representation\n */\nfunction truncateForLogging(data: unknown, maxLength: number = 200): string {\n try {\n const stringified = JSON.stringify(data, null, 2);\n if (stringified.length <= maxLength) {\n return stringified;\n }\n return stringified.slice(0, maxLength) + '... (truncated)';\n } catch {\n return '[Unable to serialize data]';\n }\n}\n\n/**\n * Validates raw suspend data against a schema.\n *\n * @param schema The schema to validate against\n * @param suspendData The raw suspend data to validate\n * @param toolId Optional tool ID for better error messages\n * @returns The validated data or a validation error\n */\nexport function validateToolSuspendData<T = unknown>(\n schema: StandardSchemaWithJSON<T> | undefined,\n suspendData: unknown,\n toolId?: string,\n): { data: T; error?: undefined } | { data?: undefined; error: ValidationError<T> } {\n // If no schema, or schema is not a Standard Schema, return suspend data as-is\n if (!schema || !('~standard' in schema)) {\n return { data: suspendData as T };\n }\n\n // Validate the input using standard schema interface\n const validation = safeValidate(schema, suspendData);\n\n if ('value' in validation) {\n return { data: validation.value };\n }\n\n // Validation failed, return error\n const errorMessages = validation.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n const error: ValidationError<T> = {\n error: true,\n message: `Tool suspension data validation failed${toolId ? ` for ${toolId}` : ''}. Please fix the following errors and try again:\\n${errorMessages}\\n\\nProvided arguments: ${truncateForLogging(suspendData)}`,\n validationErrors: buildFormattedErrors<T>(validation.issues),\n };\n\n return { error };\n}\n\n/**\n * Normalizes undefined/null input to an appropriate default value based on schema type.\n * This handles LLMs (Claude Sonnet 4.5, Gemini 2.4, etc.) that send undefined/null\n * instead of {} or [] when all parameters are optional.\n *\n * @param schema The Zod schema to check\n * @param input The input to normalize\n * @returns The normalized input (original value, {}, or [])\n */\nfunction normalizeNullishInput(schema: StandardSchemaWithJSON<any>, input: unknown): unknown {\n if (typeof input !== 'undefined' && input !== null) {\n return input;\n }\n\n const jsonSchema = standardSchemaToJSONSchema(schema, { io: 'input' });\n\n // Check if schema is an array type (using typeName to avoid dual-package hazard)\n if (jsonSchema.type === 'array') {\n return [];\n }\n\n // Check if schema is an object type (using typeName to avoid dual-package hazard)\n if (jsonSchema.type === 'object') {\n return {};\n }\n\n // For other schema types, return the original input and let Zod validate\n return input;\n}\n\n/**\n * Checks if a value is a plain object (created by {} or new Object()).\n * This excludes class instances, built-in objects like Date/Map/URL, etc.\n *\n * @param value The value to check\n * @returns true if the value is a plain object\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Recursively converts undefined values to null in an object.\n * This is needed for OpenAI compat layers which convert .optional() to .nullable()\n * for strict mode compliance. When fields are omitted (undefined), we convert them\n * to null so the schema validation passes, and the transform then converts null back\n * to undefined. (GitHub #11457)\n *\n * Only recurses into plain objects to preserve class instances and built-in objects\n * like Date, Map, URL, etc. (GitHub #11502)\n *\n * @param input The input to process\n * @returns The processed input with undefined values converted to null\n */\nfunction convertUndefinedToNull(input: unknown): unknown {\n if (input === undefined) {\n return null;\n }\n\n if (input === null || typeof input !== 'object') {\n return input;\n }\n\n if (Array.isArray(input)) {\n return input.map(convertUndefinedToNull);\n }\n\n // Only recurse into plain objects - preserve class instances, built-in objects\n // (Date, Map, Set, URL, etc.) and any other non-plain objects\n if (!isPlainObject(input)) {\n return input;\n }\n\n // It's a plain object - recursively process all properties\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(input)) {\n result[key] = convertUndefinedToNull(value);\n }\n return result;\n}\n\n/**\n * Recursively strips null/undefined values from object properties.\n * This handles LLMs (e.g. Gemini) that send null for .optional() fields,\n * where Zod expects undefined, not null. By stripping nullish values,\n * we let Zod treat them as \"not provided\" which matches .optional() semantics.\n * (GitHub #12362)\n *\n * @param input The input to process\n * @returns The processed input with null/undefined values stripped from objects\n */\nfunction stripNullishValues(input: unknown): unknown {\n // Top-level null/undefined becomes undefined\n if (input === null || input === undefined) {\n return undefined;\n }\n\n if (typeof input !== 'object') {\n return input;\n }\n\n if (Array.isArray(input)) {\n // For arrays, recursively process elements but keep nulls in arrays\n // (array elements with null may be intentional)\n return input.map(item => (item === null ? null : stripNullishValues(item)));\n }\n\n // Only recurse into plain objects - preserve class instances, built-in objects\n if (!isPlainObject(input)) {\n return input;\n }\n\n // It's a plain object - recursively process all properties, omitting null/undefined values\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(input)) {\n if (value === null || value === undefined) {\n // Omit null/undefined values - equivalent to \"not provided\" for optional fields\n continue;\n }\n result[key] = stripNullishValues(value);\n }\n return result;\n}\n\n/**\n * Strip null/undefined values only at specific paths that caused validation errors.\n * Preserves null for .nullable() fields that are valid.\n */\nfunction stripNullishValuesAtPaths(input: unknown, paths: Set<string>, currentPath = ''): unknown {\n if (input === null || input === undefined) {\n return paths.has(currentPath) ? undefined : input;\n }\n\n if (typeof input !== 'object') {\n return input;\n }\n\n if (Array.isArray(input)) {\n return input.map((item, i) =>\n stripNullishValuesAtPaths(item, paths, currentPath ? `${currentPath}.${i}` : String(i)),\n );\n }\n\n if (!isPlainObject(input)) {\n return input;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(input)) {\n const fieldPath = currentPath ? `${currentPath}.${key}` : key;\n if ((value === null || value === undefined) && paths.has(fieldPath)) {\n // Only omit null/undefined for fields that caused validation errors\n continue;\n }\n result[key] = stripNullishValuesAtPaths(value, paths, fieldPath);\n }\n return result;\n}\n\n/**\n * Coerces stringified JSON values in object properties when the schema expects\n * an array or object but the LLM returned a JSON string.\n *\n * Some LLMs (e.g., GLM4.7) return stringified JSON for array/object parameters:\n * { \"args\": \"[\\\"parse_excel.py\\\"]\" }\n * instead of:\n * { \"args\": [\"parse_excel.py\"] }\n *\n * This function walks the top-level properties of a plain object and attempts\n * to JSON.parse string values when the schema expects a non-string type.\n * (GitHub #12757)\n *\n * @param schema The Zod schema to check field types against\n * @param input The input to process\n * @returns The input with stringified JSON values coerced, or the original input\n */\nfunction coerceStringifiedJsonValues(schema: StandardSchemaWithJSON<unknown>, input: unknown): unknown {\n // Only process plain objects with object schemas\n if (!isPlainObject(input)) {\n return input;\n }\n\n const unwrapped = unwrapZodType(schema as any);\n if (!isZodObject(unwrapped)) {\n return input;\n }\n\n const shape = (unwrapped as any).shape;\n if (!shape || typeof shape !== 'object') {\n return input;\n }\n\n let changed = false;\n const result: Record<string, unknown> = { ...input };\n\n for (const [key, value] of Object.entries(input)) {\n if (typeof value !== 'string') {\n continue;\n }\n\n const fieldSchema = shape[key];\n if (!fieldSchema) {\n continue;\n }\n\n // Unwrap the field schema to find the base type\n const baseFieldSchema = unwrapZodType(fieldSchema);\n\n // Only attempt coercion if the schema expects a non-string type\n // and the string looks like it could be JSON (starts with [ or {)\n if (getZodTypeName(baseFieldSchema) === 'ZodString') {\n continue;\n }\n\n const trimmed = value.trim();\n if (\n (isZodArray(baseFieldSchema) && trimmed.startsWith('[')) ||\n (isZodObject(baseFieldSchema) && trimmed.startsWith('{'))\n ) {\n try {\n const parsed = JSON.parse(value);\n if (\n (isZodArray(baseFieldSchema) && Array.isArray(parsed)) ||\n (isZodObject(baseFieldSchema) && isPlainObject(parsed))\n ) {\n result[key] = parsed;\n changed = true;\n }\n } catch {\n // Not valid JSON, leave as-is\n }\n }\n }\n\n return changed ? result : input;\n}\n\n/**\n * Validates raw input data against a schema.\n *\n * @param schema The schema to validate against (or undefined to skip validation)\n * @param input The raw input data to validate\n * @param toolId Optional tool ID for better error messages\n * @returns The validated data or a validation error\n */\nexport function validateToolInput<T = unknown>(\n schema: StandardSchemaWithJSON<T> | undefined,\n input: unknown,\n toolId?: string,\n): { data: T; error?: undefined } | { data?: undefined; error: ValidationError<T> } {\n // If no schema, or schema is not a Standard Schema (e.g. plain JSON Schema from Vercel tools),\n // return input as-is. Only validate when we have a proper Standard Schema with ~standard.validate.\n if (!schema || !('~standard' in schema)) {\n return { data: input as T };\n }\n\n // Validation pipeline:\n //\n // 1. normalizeNullishInput: Convert top-level null/undefined to {} or [] based on schema type.\n // Handles LLMs that send undefined instead of {} or [] for all-optional parameters.\n //\n // 2. convertUndefinedToNull: Convert undefined values to null in object properties.\n // Needed for OpenAI compat layers that convert .optional() to .nullable() for\n // strict mode compliance. The schema's transform converts null back to undefined.\n // (GitHub #11457)\n //\n // 3. First validation attempt with null values preserved. This handles .nullable()\n // schemas correctly (where null is a valid value).\n //\n // 4. If validation fails, retry with stringified JSON values coerced to their\n // proper types. Some LLMs (e.g. GLM4.7) return JSON arrays/objects as strings.\n // (GitHub #12757)\n //\n // 5. If validation still fails, retry with null values stripped from object properties.\n // This handles LLMs (e.g. Gemini) that send null for .optional() fields, where\n // Zod expects undefined, not null. (GitHub #12362)\n\n // Step 1: Normalize top-level null/undefined to appropriate default\n let normalizedInput = normalizeNullishInput(schema, input);\n\n // Step 2: Convert undefined values to null recursively (GitHub #11457)\n normalizedInput = convertUndefinedToNull(normalizedInput);\n\n // Step 3: Validate the normalized input\n const validation = safeValidate(schema, normalizedInput);\n\n if ('value' in validation) {\n return { data: validation.value };\n }\n\n // Step 4: Retry with stringified JSON values coerced (GitHub #12757)\n // LLMs like GLM4.7 send stringified JSON for array/object parameters, e.g.\n // { \"args\": \"[\\\"file.py\\\"]\" } instead of { \"args\": [\"file.py\"] }.\n const coercedInput = coerceStringifiedJsonValues(schema, normalizedInput);\n if (coercedInput !== normalizedInput) {\n const coercedValidation = safeValidate(schema, coercedInput);\n if ('value' in coercedValidation) {\n return { data: coercedValidation.value };\n }\n }\n\n // Step 5: Retry with null values stripped only for failing fields (GitHub #12362)\n // LLMs like Gemini send null for optional fields, but Zod's .optional() only\n // accepts undefined, not null. We only strip nulls for fields that caused\n // validation errors, preserving null for .nullable() schemas that need it.\n const failingNullPaths = new Set(\n validation.issues\n .filter(issue => issue.message?.includes('null'))\n .map(issue => issue.path?.map(p => (typeof p === 'object' && 'key' in p ? String(p.key) : String(p))).join('.'))\n .filter((p): p is string => !!p),\n );\n const strippedInput =\n failingNullPaths.size > 0 ? stripNullishValuesAtPaths(input, failingNullPaths) : stripNullishValues(input);\n const normalizedStripped = normalizeNullishInput(schema, strippedInput);\n const retryValidation = safeValidate(schema, normalizedStripped);\n\n if ('value' in retryValidation) {\n return { data: retryValidation.value };\n }\n\n // All attempts failed - return the original (non-stripped) error since it's\n // more informative about what the schema actually expects\n const errorMessages = validation.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n const error: ValidationError<T> = {\n error: true,\n message: `Tool input validation failed${toolId ? ` for ${toolId}` : ''}. Please fix the following errors and try again:\\n${errorMessages}\\n\\nProvided arguments: ${truncateForLogging(input)}`,\n validationErrors: buildFormattedErrors<T>(validation.issues),\n };\n\n return { error };\n}\n\n/**\n * Validates tool output data against a schema.\n *\n * @param schema The schema to validate against\n * @param output The output data to validate\n * @param toolId Optional tool ID for better error messages\n * @returns The validated data or a validation error\n */\nexport function validateToolOutput<T = unknown>(\n schema: StandardSchemaWithJSON<T> | undefined,\n output: unknown,\n toolId?: string,\n suspendCalled?: boolean,\n): { data: T; error?: undefined } | { data?: undefined; error: ValidationError<T> } {\n // If no schema, not a Standard Schema, or suspend was called, return output as-is\n if (!schema || !('~standard' in schema) || suspendCalled) {\n return { data: output as T };\n }\n\n // Validate the output using standard schema interface\n const validation = safeValidate(schema, output);\n\n if ('value' in validation) {\n return { data: validation.value };\n }\n\n // Validation failed, return error\n const errorMessages = validation.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n const error: ValidationError<T> = {\n error: true,\n message: `Tool output validation failed${toolId ? ` for ${toolId}` : ''}. The tool returned invalid output:\\n${errorMessages}\\n\\nReturned output: ${truncateForLogging(output)}`,\n validationErrors: buildFormattedErrors<T>(validation.issues),\n };\n\n return { error };\n}\n\n/**\n * Keys that are considered sensitive and should be redacted in error messages.\n */\nconst SENSITIVE_KEYS = ['password', 'secret', 'token', 'apiKey', 'api_key', 'auth', 'credential'];\n\n/**\n * Redacts sensitive keys from an object for safe logging.\n * @param obj The object to redact\n * @returns A new object with sensitive values replaced with '[REDACTED]'\n */\nfunction redactSensitiveKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(redactSensitiveKeys);\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (SENSITIVE_KEYS.some(sensitive => key.toLowerCase().includes(sensitive.toLowerCase()))) {\n result[key] = '[REDACTED]';\n } else if (typeof value === 'object' && value !== null) {\n result[key] = redactSensitiveKeys(value);\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * Validates request context data against a schema.\n * This is used to validate the request context before tool execution.\n *\n * @param schema The schema to validate against (PublicSchema which accepts Zod v3/v4, JSONSchema, etc.)\n * @param requestContext The request context to validate\n * @param identifier Optional identifier (tool/step ID) for better error messages\n * @returns The validated data or a validation error\n */\nexport function validateRequestContext<T = any>(\n schema: PublicSchema<T> | undefined,\n requestContext: RequestContext | undefined,\n identifier?: string,\n): { data: T | Record<string, any>; error?: ValidationError<T> } {\n // If no schema, return request context values as-is\n if (!schema) {\n return { data: (requestContext?.all ?? {}) as T };\n }\n\n // Get the values from request context\n const contextValues = requestContext?.all ?? {};\n\n // Convert PublicSchema to StandardSchemaWithJSON for validation\n const standardSchema = toStandardSchema(schema);\n\n // Validate using standard schema interface\n const validation = standardSchema['~standard'].validate(contextValues);\n\n if (validation instanceof Promise) {\n throw new Error('Your schema is async, which is not supported. Please use a sync schema.');\n }\n\n if ('value' in validation) {\n return { data: validation.value };\n }\n\n // Validation failed, return error\n const errorMessages = validation.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n // Redact sensitive keys before including in error message\n const redactedContext = redactSensitiveKeys(contextValues);\n\n const error: ValidationError<T> = {\n error: true,\n message: `Request context validation failed${identifier ? ` for ${identifier}` : ''}. Please fix the following errors and try again:\\n${errorMessages}\\n\\nProvided request context: ${truncateForLogging(redactedContext)}`,\n validationErrors: buildFormattedErrors<T>(validation.issues),\n };\n\n return { data: contextValues as T, error };\n}\n","import type { Mastra } from '../mastra';\nimport { RequestContext } from '../request-context';\nimport { toStandardSchema } from '../schema';\nimport type { PublicSchema, StandardSchemaWithJSON, InferPublicSchema } from '../schema';\nimport type { SuspendOptions } from '../workflows';\nimport type { McpMetadata, MCPToolProperties, ToolAction, ToolExecutionContext } from './types';\nimport { validateToolInput, validateToolOutput, validateToolSuspendData, validateRequestContext } from './validation';\n\n/**\n * Marker to identify Mastra tools even when `instanceof` fails.\n * This can happen in environments like Vite SSR where the same module\n * may be loaded multiple times, creating different class instances.\n * Uses Symbol.for() so the same symbol is shared across module copies.\n * Follows the naming convention: <org>.<product>.<category>.<className>\n */\nexport const MASTRA_TOOL_MARKER = Symbol.for('mastra.core.tool.Tool');\n\n/**\n * A type-safe tool that agents and workflows can call to perform specific actions.\n *\n * @template TSchemaIn - Input schema type\n * @template TSchemaOut - Output schema type\n * @template TSuspendSchema - Suspend operation schema type\n * @template TResumeSchema - Resume operation schema type\n * @template TContext - Execution context type\n *\n * @example Basic tool with validation\n * ```typescript\n * const weatherTool = createTool({\n * id: 'get-weather',\n * description: 'Get weather for a location',\n * inputSchema: z.object({\n * location: z.string(),\n * units: z.enum(['celsius', 'fahrenheit']).optional()\n * }),\n * execute: async (inputData) => {\n * return await fetchWeather(inputData.location, inputData.units);\n * }\n * });\n * ```\n *\n * @example Tool requiring approval\n * ```typescript\n * const deleteFileTool = createTool({\n * id: 'delete-file',\n * description: 'Delete a file',\n * requireApproval: true,\n * inputSchema: z.object({ filepath: z.string() }),\n * execute: async (inputData) => {\n * await fs.unlink(inputData.filepath);\n * return { deleted: true };\n * }\n * });\n * ```\n *\n * @example Tool with Mastra integration\n * ```typescript\n * const saveTool = createTool({\n * id: 'save-data',\n * description: 'Save data to storage',\n * inputSchema: z.object({ key: z.string(), value: z.any() }),\n * execute: async (inputData, context) => {\n * const storage = context?.mastra?.getStorage();\n * await storage?.set(inputData.key, inputData.value);\n * return { saved: true };\n * }\n * });\n * ```\n */\nexport class Tool<\n TSchemaIn = unknown,\n TSchemaOut = unknown,\n TSuspendSchema = unknown,\n TResumeSchema = unknown,\n TContext extends ToolExecutionContext<TSuspendSchema, TResumeSchema, any> = ToolExecutionContext<\n TSuspendSchema,\n TResumeSchema\n >,\n TId extends string = string,\n TRequestContext extends Record<string, any> | unknown = unknown,\n> implements ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext> {\n /** Unique identifier for the tool */\n id: TId;\n\n /** Description of what the tool does */\n description: string;\n\n /** Schema for validating input parameters */\n inputSchema?: StandardSchemaWithJSON<TSchemaIn>;\n\n /** Schema for validating output structure */\n outputSchema?: StandardSchemaWithJSON<TSchemaOut>;\n\n /** Schema for suspend operation data */\n suspendSchema?: StandardSchemaWithJSON<TSuspendSchema>;\n\n /** Schema for resume operation data */\n resumeSchema?: StandardSchemaWithJSON<TResumeSchema>;\n\n /**\n * Schema for validating request context values.\n * When provided, the request context will be validated against this schema before tool execution.\n */\n requestContextSchema?: PublicSchema<TRequestContext>;\n\n /**\n * Tool execution function\n * @param inputData - The raw, validated input data\n * @param context - Optional execution context with metadata\n * @returns Promise resolving to tool output or a ValidationError if input validation fails\n */\n execute?: ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext>['execute'];\n\n /** Parent Mastra instance for accessing shared resources */\n mastra?: Mastra;\n\n /**\n * Whether the tool requires explicit user approval before execution\n * @example\n * ```typescript\n * // For destructive operations\n * requireApproval: true\n * ```\n */\n requireApproval?: boolean;\n\n /**\n * Provider-specific options passed to the model when this tool is used.\n * Keys are provider names (e.g., 'anthropic', 'openai'), values are provider-specific configs.\n * @example\n * ```typescript\n * providerOptions: {\n * anthropic: {\n * cacheControl: { type: 'ephemeral' }\n * }\n * }\n * ```\n */\n providerOptions?: Record<string, Record<string, unknown>>;\n\n /**\n * Optional function to transform the tool's raw output before sending it to the model.\n * The raw result is still available for application logic; only the model sees the transformed version.\n */\n toModelOutput?: (output: TSchemaOut) => unknown;\n\n /**\n * Optional MCP-specific properties including annotations and metadata.\n * Only relevant when the tool is being used in an MCP context.\n * @example\n * ```typescript\n * mcp: {\n * annotations: {\n * title: 'Weather Lookup',\n * readOnlyHint: true,\n * destructiveHint: false\n * },\n * _meta: {\n * version: '1.0.0',\n * author: 'team@example.com'\n * }\n * }\n * ```\n */\n mcp?: MCPToolProperties;\n\n onInputStart?: ToolAction<\n TSchemaIn,\n TSchemaOut,\n TSuspendSchema,\n TResumeSchema,\n TContext,\n TId,\n TRequestContext\n >['onInputStart'];\n onInputDelta?: ToolAction<\n TSchemaIn,\n TSchemaOut,\n TSuspendSchema,\n TResumeSchema,\n TContext,\n TId,\n TRequestContext\n >['onInputDelta'];\n onInputAvailable?: ToolAction<\n TSchemaIn,\n TSchemaOut,\n TSuspendSchema,\n TResumeSchema,\n TContext,\n TId,\n TRequestContext\n >['onInputAvailable'];\n onOutput?: ToolAction<\n TSchemaIn,\n TSchemaOut,\n TSuspendSchema,\n TResumeSchema,\n TContext,\n TId,\n TRequestContext\n >['onOutput'];\n\n /**\n * Examples of valid tool inputs passed through to the AI SDK.\n */\n inputExamples?: Array<{ input: Record<string, unknown> }>;\n\n /**\n * Metadata identifying this tool as originating from an MCP server.\n * Set automatically by the MCP client when creating tools.\n */\n mcpMetadata?: McpMetadata;\n\n /**\n * Creates a new Tool instance with input validation wrapper.\n *\n * @param opts - Tool configuration and execute function\n * @example\n * ```typescript\n * const tool = new Tool({\n * id: 'my-tool',\n * description: 'Does something useful',\n * inputSchema: z.object({ name: z.string() }),\n * execute: async (inputData) => ({ greeting: `Hello ${inputData.name}` })\n * });\n * ```\n */\n constructor(opts: ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext>) {\n (this as any)[MASTRA_TOOL_MARKER] = true;\n this.id = opts.id;\n this.description = opts.description;\n this.inputSchema = opts.inputSchema ? toStandardSchema(opts.inputSchema) : undefined;\n this.outputSchema = opts.outputSchema ? toStandardSchema(opts.outputSchema) : undefined;\n this.suspendSchema = opts.suspendSchema ? toStandardSchema(opts.suspendSchema) : undefined;\n this.resumeSchema = opts.resumeSchema ? toStandardSchema(opts.resumeSchema) : undefined;\n this.requestContextSchema = opts.requestContextSchema;\n this.mastra = opts.mastra;\n this.requireApproval = opts.requireApproval || false;\n this.providerOptions = opts.providerOptions;\n this.toModelOutput = opts.toModelOutput;\n this.inputExamples = opts.inputExamples;\n this.mcp = opts.mcp;\n this.mcpMetadata = opts.mcpMetadata;\n this.onInputStart = opts.onInputStart;\n this.onInputDelta = opts.onInputDelta;\n this.onInputAvailable = opts.onInputAvailable;\n this.onOutput = opts.onOutput;\n\n // Tools receive two parameters:\n // 1. input - The raw, validated input data\n // 2. context - Execution metadata (mastra, suspend, etc.)\n if (opts.execute) {\n const originalExecute = opts.execute;\n this.execute = async (inputData: TSchemaIn, context?: any) => {\n // Validate input if schema exists\n const { data, error } = validateToolInput(this.inputSchema, inputData, this.id);\n if (error) {\n return error;\n }\n\n // Validate request context if schema exists\n const { error: requestContextError } = validateRequestContext(\n this.requestContextSchema,\n context?.requestContext,\n this.id,\n );\n if (requestContextError) {\n return requestContextError as any;\n }\n\n let suspendData = null;\n\n const baseContext = context\n ? {\n ...context,\n ...(context.suspend\n ? {\n suspend: (args: any, suspendOptions?: SuspendOptions) => {\n suspendData = args;\n return context.suspend?.(args, suspendOptions);\n },\n }\n : {}),\n }\n : {};\n\n // Organize context based on execution source\n let organizedContext = baseContext;\n if (!context) {\n // No context provided - create a minimal context with requestContext\n organizedContext = {\n requestContext: new RequestContext(),\n mastra: undefined,\n };\n } else {\n // Check if this is agent execution (has toolCallId and messages)\n const isAgentExecution = baseContext.toolCallId && baseContext.messages;\n\n // Check if this is workflow execution (has workflow properties)\n // Agent execution takes precedence - don't treat as workflow if it's an agent call\n const isWorkflowExecution = !isAgentExecution && (baseContext.workflow || baseContext.workflowId);\n\n if (isAgentExecution && !baseContext.agent) {\n // Reorganize agent context - nest agent-specific properties under 'agent' key\n const { toolCallId, messages, suspend, resumeData, threadId, resourceId, writableStream, ...rest } =\n baseContext;\n organizedContext = {\n ...rest,\n agent: {\n toolCallId,\n messages,\n suspend,\n resumeData,\n threadId,\n resourceId,\n writableStream,\n },\n // Ensure requestContext is always present\n requestContext: rest.requestContext || new RequestContext(),\n };\n } else if (isWorkflowExecution && !baseContext.workflow) {\n // Reorganize workflow context - nest workflow-specific properties under 'workflow' key\n const { workflowId, runId, state, setState, suspend, resumeData, ...rest } = baseContext;\n organizedContext = {\n ...rest,\n workflow: {\n workflowId,\n runId,\n state,\n setState,\n suspend,\n resumeData,\n },\n // Ensure requestContext is always present\n requestContext: rest.requestContext || new RequestContext(),\n };\n } else {\n // Ensure requestContext is always present even for direct execution\n organizedContext = {\n ...baseContext,\n agent: baseContext.agent\n ? {\n ...baseContext.agent,\n suspend: (args: any, suspendOptions?: SuspendOptions) => {\n suspendData = args;\n return baseContext.agent?.suspend?.(args, suspendOptions);\n },\n }\n : baseContext.agent,\n workflow: baseContext.workflow\n ? {\n ...baseContext.workflow,\n suspend: (args: any, suspendOptions?: SuspendOptions) => {\n suspendData = args;\n return baseContext.workflow?.suspend?.(args, suspendOptions);\n },\n }\n : baseContext.workflow,\n requestContext: baseContext.requestContext || new RequestContext(),\n };\n }\n }\n\n const resumeData =\n organizedContext.agent?.resumeData ?? organizedContext.workflow?.resumeData ?? organizedContext?.resumeData;\n\n if (resumeData) {\n const resumeValidation = validateToolInput(this.resumeSchema, resumeData, this.id);\n if (resumeValidation.error) {\n return resumeValidation.error as any;\n }\n }\n\n // Call the original execute with validated input and organized context\n const output = await originalExecute(data as any, organizedContext);\n\n if (suspendData) {\n const suspendValidation = validateToolSuspendData(this.suspendSchema, suspendData, this.id);\n if (suspendValidation.error) {\n return suspendValidation.error as any;\n }\n }\n\n const skiptOutputValidation = !!(typeof output === 'undefined' && suspendData);\n\n // Validate output if schema exists\n const outputValidation = validateToolOutput(this.outputSchema, output, this.id, skiptOutputValidation);\n\n if (outputValidation.error) {\n return outputValidation.error as any;\n }\n\n return outputValidation.data;\n };\n }\n }\n}\n\n/**\n * Creates a type-safe tool with automatic input validation.\n *\n * @template TSchemaIn - Input schema type\n * @template TSchemaOut - Output schema type\n * @template TSuspendSchema - Suspend operation schema type\n * @template TResumeSchema - Resume operation schema type\n * @template TContext - Execution context type\n * @template TExecute - Execute function type\n *\n * @param opts - Tool configuration including schemas and execute function\n * @returns Type-safe Tool instance with conditional typing based on schemas\n *\n * @example Simple tool\n * ```typescript\n * const greetTool = createTool({\n * id: 'greet',\n * description: 'Say hello',\n * execute: async () => ({ message: 'Hello!' })\n * });\n * ```\n *\n * @example Tool with input validation\n * ```typescript\n * const calculateTool = createTool({\n * id: 'calculate',\n * description: 'Perform calculations',\n * inputSchema: z.object({\n * operation: z.enum(['add', 'subtract']),\n * a: z.number(),\n * b: z.number()\n * }),\n * execute: async (inputData) => {\n * const result = inputData.operation === 'add'\n * ? inputData.a + inputData.b\n * : inputData.a - inputData.b;\n * return { result };\n * }\n * });\n * ```\n *\n * @example Tool with output schema\n * ```typescript\n * const userTool = createTool({\n * id: 'get-user',\n * description: 'Get user data',\n * inputSchema: z.object({ userId: z.string() }),\n * outputSchema: z.object({\n * id: z.string(),\n * name: z.string(),\n * email: z.string()\n * }),\n * execute: async (inputData) => {\n * return await fetchUser(inputData.userId);\n * }\n * });\n * ```\n *\n * @example Tool with external API\n * ```typescript\n * const weatherTool = createTool({\n * id: 'weather',\n * description: 'Get weather data',\n * inputSchema: z.object({\n * city: z.string(),\n * units: z.enum(['metric', 'imperial']).default('metric')\n * }),\n * execute: async (inputData) => {\n * const response = await fetch(\n * `https://api.weather.com/v1/weather?q=${inputData.city}&units=${inputData.units}`\n * );\n * return response.json();\n * }\n * });\n * ```\n */\ntype SchemaLike = PublicSchema<any> | undefined;\ntype InferSchema<T extends SchemaLike> = T extends PublicSchema<any> ? InferPublicSchema<T> : unknown;\n\ntype CreateToolOpts<\n TId extends string,\n TInputSchema extends SchemaLike,\n TOutputSchema extends SchemaLike,\n TSuspendSchema extends SchemaLike,\n TResumeSchema extends SchemaLike,\n TRequestContext,\n TContext extends ToolExecutionContext<InferSchema<TSuspendSchema>, InferSchema<TResumeSchema>, TRequestContext>,\n> = Omit<\n ToolAction<\n InferSchema<TInputSchema>,\n InferSchema<TOutputSchema>,\n InferSchema<TSuspendSchema>,\n InferSchema<TResumeSchema>,\n TContext,\n TId,\n TRequestContext\n >,\n 'inputSchema' | 'outputSchema' | 'suspendSchema' | 'resumeSchema'\n> & {\n inputSchema?: TInputSchema;\n outputSchema?: TOutputSchema;\n suspendSchema?: TSuspendSchema;\n resumeSchema?: TResumeSchema;\n};\nexport function createTool<\n TId extends string = string,\n TInputSchema extends SchemaLike = undefined,\n TOutputSchema extends SchemaLike = undefined,\n TSuspendSchema extends SchemaLike = undefined,\n TResumeSchema extends SchemaLike = undefined,\n TRequestContext extends Record<string, any> | unknown = unknown,\n TContext extends ToolExecutionContext<InferSchema<TSuspendSchema>, InferSchema<TResumeSchema>, TRequestContext> =\n ToolExecutionContext<InferSchema<TSuspendSchema>, InferSchema<TResumeSchema>, TRequestContext>,\n>(\n opts: CreateToolOpts<TId, TInputSchema, TOutputSchema, TSuspendSchema, TResumeSchema, TRequestContext, TContext>,\n): Tool<\n InferSchema<TInputSchema>,\n InferSchema<TOutputSchema>,\n InferSchema<TSuspendSchema>,\n InferSchema<TResumeSchema>,\n TContext,\n TId,\n TRequestContext\n> {\n return new Tool(opts);\n}\n","import { Tool, MASTRA_TOOL_MARKER } from './tool';\nimport type { ToolToConvert } from './tool-builder/builder';\nimport type { VercelTool } from './types';\n\n/**\n * Checks if a tool is a Mastra Tool, using both instanceof and marker.\n * The marker fallback handles environments like Vite SSR where the same\n * module may be loaded multiple times, causing instanceof to fail.\n */\nexport function isMastraTool(tool: unknown): boolean {\n return tool instanceof Tool || (typeof tool === 'object' && tool !== null && MASTRA_TOOL_MARKER in tool);\n}\n\n/**\n * Checks if a tool is a Vercel Tool (AI SDK tool)\n * @param tool - The tool to check\n * @returns True if the tool is a Vercel Tool, false otherwise\n */\nexport function isVercelTool(tool?: ToolToConvert): tool is VercelTool {\n // Checks if this tool is not an instance of Mastra's Tool class\n // AI SDK tools must have an execute function and either:\n // - 'parameters' (v4) or 'inputSchema' (v5/v6)\n // This prevents plain objects with inputSchema (like client tools) from being treated as VercelTools\n return !!(\n tool &&\n !isMastraTool(tool) &&\n ('parameters' in tool || ('execute' in tool && typeof tool.execute === 'function' && 'inputSchema' in tool))\n );\n}\n\n/**\n * Checks if a tool is a provider-defined tool from the AI SDK.\n * Provider tools (like google.tools.googleSearch(), openai.tools.webSearch()) have:\n * - type: \"provider-defined\" (AI SDK v5) or \"provider\" (AI SDK v6)\n * - id: in format 'provider.tool_name' (e.g., 'google.google_search')\n *\n * These tools have a lazy `inputSchema` function that returns an AI SDK Schema\n * (not a Zod schema), so they require special handling during serialization.\n */\nexport function isProviderDefinedTool(tool: unknown): boolean {\n if (typeof tool !== 'object' || tool === null) return false;\n const t = tool as Record<string, unknown>;\n const isProviderType = t.type === 'provider-defined' || t.type === 'provider';\n return isProviderType && typeof t.id === 'string';\n}\n"]}
@@ -7524,7 +7524,7 @@ function saveLastRefreshTimeToDisk(date) {
7524
7524
  }
7525
7525
  function getPackageRoot() {
7526
7526
  try {
7527
- const require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-L7NBGABG.cjs', document.baseURI).href)) || "file://");
7527
+ const require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-FIQRYC7M.cjs', document.baseURI).href)) || "file://");
7528
7528
  const packageJsonPath = require2.resolve("@mastra/core/package.json");
7529
7529
  return path__default.default.dirname(packageJsonPath);
7530
7530
  } catch {
@@ -7721,7 +7721,7 @@ var GatewayRegistry = class _GatewayRegistry {
7721
7721
  this.isRefreshing = true;
7722
7722
  try {
7723
7723
  const { ModelsDevGateway } = await import('./models-dev-7JBNQXVK.cjs');
7724
- const { NetlifyGateway } = await import('./netlify-OZA4BKIK.cjs');
7724
+ const { NetlifyGateway } = await import('./netlify-RN36CL4F.cjs');
7725
7725
  const { fetchProvidersFromGateways, writeRegistryFiles } = await import('./registry-generator-PUWKZKVW.cjs');
7726
7726
  const defaultGateways = [new ModelsDevGateway({}), new NetlifyGateway()];
7727
7727
  const gateways = [...defaultGateways, ...this.customGateways];
@@ -7846,5 +7846,5 @@ exports.getRegisteredProviders = getRegisteredProviders;
7846
7846
  exports.isProviderRegistered = isProviderRegistered;
7847
7847
  exports.isValidModelId = isValidModelId;
7848
7848
  exports.parseModelString = parseModelString;
7849
- //# sourceMappingURL=chunk-L7NBGABG.cjs.map
7850
- //# sourceMappingURL=chunk-L7NBGABG.cjs.map
7849
+ //# sourceMappingURL=chunk-FIQRYC7M.cjs.map
7850
+ //# sourceMappingURL=chunk-FIQRYC7M.cjs.map