{"version":3,"file":"tool-BQQeYmhc.cjs","names":["unwrapZodType","isZodObject","getZodTypeName","isZodArray","RequestContext","#source","#acceptsInput","#encode","#getSourceValue"],"sources":["../src/request-context/input-source.ts","../src/tools/builder-validation-context.ts","../src/tools/validation.ts","../src/tools/tool.ts"],"sourcesContent":["import type { RequestContext } from './index';\n\n/** @internal */\nexport const REQUEST_CONTEXT_INPUT_SOURCE = Symbol.for('mastra.core.request-context.input-source');\n\ntype RequestContextWithInputSource = RequestContext & {\n  [REQUEST_CONTEXT_INPUT_SOURCE]?: RequestContext;\n};\n\n/**\n * Returns the input-form context that schema validation should consume.\n *\n * Schema-transformed execution views retain their source through a global\n * symbol so forwarding a view across tools or duplicated module instances does\n * not validate already-decoded values again.\n *\n * @internal\n */\nexport function getRequestContextInputSource(requestContext?: RequestContext): RequestContext | undefined {\n  let current = requestContext as RequestContextWithInputSource | undefined;\n  const seen = new Set<RequestContext>();\n\n  while (current && !seen.has(current)) {\n    seen.add(current);\n    const source = current[REQUEST_CONTEXT_INPUT_SOURCE];\n    if (!source) {\n      return current;\n    }\n    current = source as RequestContextWithInputSource;\n  }\n\n  return current;\n}\n\n/** @internal */\nexport function getRequestContextInputValues(requestContext?: RequestContext): Record<string, any> {\n  return getRequestContextInputSource(requestContext)?.all ?? {};\n}\n","const builderValidatedContexts = new WeakSet<object>();\n\nexport function markBuilderValidatedInput(context: object): void {\n  builderValidatedContexts.add(context);\n}\n\nexport function consumeBuilderValidatedInput(context: unknown): boolean {\n  if (typeof context !== 'object' || context === null || !builderValidatedContexts.has(context)) {\n    return false;\n  }\n\n  builderValidatedContexts.delete(context);\n  return true;\n}\n","import type { RequestContext } from '../request-context';\nimport { getRequestContextInputValues } from '../request-context/input-source';\nimport { isStandardSchemaWithJSON, toStandardSchema, standardSchemaToJSONSchema } from '../schema';\nimport type { PublicSchema, StandardSchemaWithJSON, StandardSchemaIssue } from '../schema';\nimport { getZodTypeName, isZodArray, isZodObject, unwrapZodType } from '../utils/zod-utils';\n\nconst TOOL_OUTPUT_VALIDATION_SCHEMA: unique symbol = Symbol.for('mastra.tool.outputValidationSchema');\n\ntype ToolWithOutputSchema = {\n  outputSchema?: unknown;\n  [TOOL_OUTPUT_VALIDATION_SCHEMA]?: StandardSchemaWithJSON;\n};\n\nexport function registerToolOutputValidationSchema(tool: object, schema: unknown): void {\n  if (!isStandardSchemaWithJSON(schema)) return;\n\n  Object.defineProperty(tool, TOOL_OUTPUT_VALIDATION_SCHEMA, {\n    configurable: true,\n    enumerable: true,\n    value: schema,\n  });\n}\n\nexport function resolveToolOutputValidationSchema(tool: ToolWithOutputSchema): StandardSchemaWithJSON | undefined {\n  const outputSchema = typeof tool.outputSchema === 'function' ? tool.outputSchema() : tool.outputSchema;\n  if (isStandardSchemaWithJSON(outputSchema)) return outputSchema;\n\n  return tool[TOOL_OUTPUT_VALIDATION_SCHEMA];\n}\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    // Prioritise issues over value: Valibot returns both on failure (typed: false).\n    if ('issues' in result && Array.isArray(result.issues) && result.issues.length > 0) {\n      return { issues: result.issues as readonly StandardSchemaIssue[] };\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\nexport function isValidationError(value: unknown): value is ValidationError {\n  return (\n    value !== null &&\n    typeof value === 'object' &&\n    'error' in value &&\n    value.error === true &&\n    'validationErrors' in value\n  );\n}\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\n    .map(e => `- ${e.path?.map(p => getPathKey(p)).join('.') || 'root'}: ${e.message}`)\n    .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 * Gets the value at a path in a nested object, using the same path segment format\n * as Standard Schema validation issues.\n *\n * @param obj The object to traverse\n * @param pathSegments Array of path segments from a validation issue\n * @returns The value at the path, or a sentinel symbol if the path doesn't exist\n */\nconst PATH_NOT_FOUND = Symbol('PATH_NOT_FOUND');\nfunction getValueAtPath(obj: unknown, pathSegments: ReadonlyArray<PropertyKey | { key: PropertyKey }>): unknown {\n  let current: unknown = obj;\n  for (const segment of pathSegments) {\n    if (current === null || current === undefined || typeof current !== 'object') {\n      return PATH_NOT_FOUND;\n    }\n    const key =\n      typeof segment === 'object' && segment !== null && 'key' in segment ? String(segment.key) : String(segment);\n    current = (current as Record<string, unknown>)[key];\n  }\n  return current;\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  // Temporary fix: should be validated higher up the chain that it's a complete standard schema\n  schema = toStandardSchema(schema);\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  //\n  // We detect null-related failures by checking the actual value at the failing\n  // path rather than relying on error message string matching (GitHub #14476).\n  // This ensures we catch null values regardless of the validator's error message\n  // format (e.g., \"must be string\", \"must be object\", etc.).\n  const failingNullPaths = new Set(\n    validation.issues\n      .filter(issue => {\n        if (!issue.path || issue.path.length === 0) return false;\n        const value = getValueAtPath(normalizedInput, issue.path);\n        return value === null || value === undefined;\n      })\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  // Step 6: Retry with common prompt alias normalization (GitHub #14154)\n  // LLMs (especially Claude Sonnet via custom gateways) sometimes drift from\n  // using \"prompt\" to \"query\", \"message\", or \"input\" after repeated sub-agent\n  // tool calls in the same thread. Coerce these aliases to \"prompt\" and retry.\n  // Only applies when the schema actually declares a \"prompt\" field.\n  const promptJsonSchema = standardSchemaToJSONSchema(schema, { io: 'input' });\n  const schemaExpectsPrompt =\n    promptJsonSchema.type === 'object' &&\n    promptJsonSchema.properties != null &&\n    'prompt' in promptJsonSchema.properties;\n\n  if (\n    schemaExpectsPrompt &&\n    normalizedInput != null &&\n    typeof normalizedInput === 'object' &&\n    !Array.isArray(normalizedInput)\n  ) {\n    const obj = normalizedInput as Record<string, unknown>;\n    if (obj.prompt == null) {\n      const alias = [obj.query, obj.message, obj.input].find((v): v is string => typeof v === 'string');\n      if (alias !== undefined) {\n        const coercedPromptInput = { ...obj, prompt: alias };\n        const coercedPromptValidation = safeValidate(schema, coercedPromptInput);\n        if ('value' in coercedPromptValidation) {\n          return { data: coercedPromptValidation.value };\n        }\n      }\n    }\n  }\n\n  // All attempts failed. When nulls caused first-pass failures, report the\n  // path-stripped retry's issues: first-pass issues include nulls on optional\n  // fields that stripping already resolved, hiding the real failure (GitHub #24539).\n  // Otherwise the retry stripped every null (including valid .nullable() values),\n  // so the first-pass issues are the accurate ones.\n  const finalIssues = failingNullPaths.size > 0 ? retryValidation.issues : validation.issues;\n  const errorMessages = finalIssues\n    .map(e => `- ${e.path?.map(p => getPathKey(p)).join('.') || 'root'}: ${e.message}`)\n    .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>(finalIssues),\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\n    .map(e => `- ${e.path?.map(p => getPathKey(p)).join('.') || 'root'}: ${e.message}`)\n    .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, 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: getRequestContextInputValues(requestContext) as T };\n  }\n\n  // Get the values from request context\n  const contextValues = getRequestContextInputValues(requestContext);\n\n  // Convert PublicSchema to StandardSchemaWithJSON for validation\n  const standardSchema = toStandardSchema(schema);\n\n  // Validate using standard schema interface\n  const validation = safeValidate(standardSchema, contextValues);\n\n  if ('value' in validation) {\n    return { data: validation.value };\n  }\n\n  // Validation failed, return error\n  const errorMessages = validation.issues\n    .map(e => `- ${e.path?.map(p => getPathKey(p)).join('.') || 'root'}: ${e.message}`)\n    .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 { ToolBackgroundConfig } from '../background-tasks';\nimport type { Mastra } from '../mastra';\nimport { RequestContext } from '../request-context';\nimport { getRequestContextInputSource, REQUEST_CONTEXT_INPUT_SOURCE } from '../request-context/input-source';\nimport { toStandardSchema } from '../schema';\nimport type { PublicSchema, StandardSchemaWithJSON, InferPublicSchema } from '../schema';\nimport type { SuspendOptions } from '../workflows';\nimport { consumeBuilderValidatedInput } from './builder-validation-context';\nimport type {\n  McpMetadata,\n  MCPToolProperties,\n  NeedsApprovalFn,\n  ToolAction,\n  ToolExecuteFunction,\n  ToolExecutionContext,\n  ToolPayloadTransform,\n} 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\ntype RequestContextEncoder = (values: Record<string, unknown>) => Record<string, unknown> | undefined;\ntype RequestContextInputValidator = (values: Record<string, unknown>) => boolean;\n\nfunction getRequestContextInputValidator(schema: PublicSchema): RequestContextInputValidator {\n  const standardSchema = toStandardSchema(schema);\n\n  return values => {\n    try {\n      const result = standardSchema['~standard'].validate(values);\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 !('issues' in result) || !result.issues?.length;\n    } catch {\n      return false;\n    }\n  };\n}\n\nfunction getRequestContextEncoder(schema: PublicSchema | undefined): RequestContextEncoder | undefined {\n  if (!schema || (typeof schema !== 'object' && typeof schema !== 'function')) {\n    return undefined;\n  }\n\n  const encodableSchema = schema as {\n    safeEncode?: (value: unknown) => { success: boolean; data?: unknown };\n    '~standard'?: { vendor?: string };\n  };\n  if (encodableSchema['~standard']?.vendor !== 'zod' || typeof encodableSchema.safeEncode !== 'function') {\n    return undefined;\n  }\n\n  return values => {\n    try {\n      const result = encodableSchema.safeEncode!(values);\n      if (result.success && result.data && typeof result.data === 'object' && !Array.isArray(result.data)) {\n        return result.data as Record<string, unknown>;\n      }\n    } catch {\n      // Unidirectional transforms cannot encode.\n    }\n\n    return undefined;\n  };\n}\n\n/**\n * Exposes schema-transformed values for one tool execution while keeping\n * explicit mutations connected to the shared request context.\n */\nclass TransformedRequestContext extends RequestContext<Record<string, any>> {\n  readonly #source: RequestContext;\n  readonly #acceptsInput: RequestContextInputValidator;\n  readonly #encode?: RequestContextEncoder;\n\n  constructor(\n    source: RequestContext,\n    transformedValues: Record<string, unknown>,\n    acceptsInput: RequestContextInputValidator,\n    encode?: RequestContextEncoder,\n  ) {\n    super(Object.entries({ ...source.all, ...transformedValues }));\n    this.#source = source;\n    this.#acceptsInput = acceptsInput;\n    this.#encode = encode;\n    Object.defineProperty(this, REQUEST_CONTEXT_INPUT_SOURCE, { value: source });\n  }\n\n  #getSourceValue(key: string, value: unknown): unknown {\n    const nextSourceValues = { ...this.#source.all, [key]: value };\n    if (this.#acceptsInput(nextSourceValues)) {\n      return value;\n    }\n\n    const encodedValues = this.#encode?.({ ...this.all, [key]: value });\n    if (encodedValues && Object.prototype.hasOwnProperty.call(encodedValues, key)) {\n      return encodedValues[key];\n    }\n\n    throw new Error(\n      `Unable to persist request context key \"${key}\": the value is not valid schema input and cannot be encoded from the schema output.`,\n    );\n  }\n\n  public override set(key: string, value: any): void {\n    const sourceValue = this.#getSourceValue(key, value);\n    this.#source.setRaw(key, sourceValue);\n    super.set(key, value);\n  }\n\n  public override setRaw(key: string, value: unknown): void {\n    const sourceValue = this.#getSourceValue(key, value);\n    this.#source.setRaw(key, sourceValue);\n    super.setRaw(key, value);\n  }\n\n  public override delete(key: string): boolean {\n    this.#source.deleteRaw(key);\n    return super.delete(key);\n  }\n\n  public override deleteRaw(key: string): boolean {\n    this.#source.deleteRaw(key);\n    return super.deleteRaw(key);\n  }\n\n  public override clear(): void {\n    super.clear();\n    this.#source.clear();\n  }\n}\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  /** Display name for UIs and MCP clients. Never sent to the model. */\n  title?: string;\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?: NonNullable<\n    ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext>['execute']\n  >;\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   * Accepts a boolean for static behavior, or a function evaluated per-call\n   * for conditional approval.\n   * @example\n   * ```typescript\n   * // Static\n   * requireApproval: true\n   *\n   * // Conditional — only require approval for non-dry-run calls\n   * requireApproval: async ({ isDryRun }) => !isDryRun\n   * ```\n   */\n  requireApproval?: NonNullable<\n    ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext>['requireApproval']\n  >;\n\n  /**\n   * Runtime-resolved per-tool approval predicate, evaluated per call.\n   *\n   * This is set automatically when a tool's `requireApproval` is a function, or by the\n   * MCP client when wrapping a server-level `requireToolApproval` function — not something\n   * you normally set yourself (prefer the `requireApproval` option). When present it is the\n   * authoritative per-tool approval decision and is always evaluated by the agent runtime.\n   */\n  needsApprovalFn?: NeedsApprovalFn;\n\n  /**\n   * Enables strict tool input generation for providers that support it.\n   */\n  strict?: 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 target-aware transform for display and transcript payloads.\n   */\n  transform?: ToolPayloadTransform<TSchemaIn, TSchemaOut>;\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?: NonNullable<\n    ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext>['onInputStart']\n  >;\n  onInputDelta?: NonNullable<\n    ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext>['onInputDelta']\n  >;\n  onInputAvailable?: NonNullable<\n    ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext>['onInputAvailable']\n  >;\n  onOutput?: NonNullable<\n    ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext>['onOutput']\n  >;\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   * Background task configuration for this tool.\n   * When enabled, the tool can be executed in the background while the agent conversation continues.\n   */\n  background?: ToolBackgroundConfig;\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(\n    opts: Omit<\n      ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext>,\n      'execute'\n    > & {\n      execute?: ToolExecuteFunction<TSchemaIn, TSchemaOut, TContext, TRequestContext>;\n    },\n  ) {\n    (this as any)[MASTRA_TOOL_MARKER] = true;\n    this.id = opts.id;\n    this.title = opts.title;\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.strict = opts.strict;\n    this.providerOptions = opts.providerOptions;\n    this.toModelOutput = opts.toModelOutput;\n    this.transform = opts.transform;\n    this.inputExamples = opts.inputExamples;\n    this.mcp = opts.mcp;\n    this.mcpMetadata = opts.mcpMetadata;\n    this.background = opts.background;\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        // When a tool is being resumed (resumeData present in context), skip input\n        // validation. The original args were already validated during the initial\n        // execution, and during resume the tool's execute function checks resumeData\n        // and returns early without using the input args.\n        const isResuming = (context?.resumeData ?? context?.agent?.resumeData ?? context?.workflow?.resumeData) != null;\n        const wasBuilderValidated = consumeBuilderValidatedInput(context);\n        const skipInputValidation = isResuming || wasBuilderValidated;\n\n        let data: any = inputData;\n        if (!skipInputValidation) {\n          // Validate input if schema exists\n          const validationResult = validateToolInput(this.inputSchema, inputData, this.id);\n          if (validationResult.error) {\n            return validationResult.error;\n          }\n          data = validationResult.data;\n        }\n\n        const sourceRequestContext = getRequestContextInputSource(context?.requestContext);\n\n        // Validate request context if schema exists\n        const { data: validatedRequestContext, error: requestContextError } = validateRequestContext(\n          this.requestContextSchema,\n          sourceRequestContext,\n          this.id,\n        );\n        if (requestContextError) {\n          return requestContextError as any;\n        }\n\n        const executionRequestContext = this.requestContextSchema\n          ? new TransformedRequestContext(\n              sourceRequestContext ?? new RequestContext(),\n              validatedRequestContext as Record<string, unknown>,\n              getRequestContextInputValidator(this.requestContextSchema),\n              getRequestContextEncoder(this.requestContextSchema),\n            )\n          : context?.requestContext;\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: executionRequestContext ?? 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 {\n              agentId,\n              toolCallId,\n              messages,\n              suspend,\n              resumeData,\n              suspendPayload,\n              threadId,\n              resourceId,\n              writableStream,\n              isBackgroundTask,\n              background,\n              ...rest\n            } = baseContext;\n            organizedContext = {\n              ...rest,\n              background,\n              agent: {\n                agentId: agentId || '',\n                toolCallId,\n                messages,\n                suspend,\n                resumeData,\n                suspendPayload,\n                threadId,\n                resourceId,\n                writableStream,\n                ...(isBackgroundTask ? { isBackgroundTask: true } : {}),\n              },\n              // Ensure requestContext is always present\n              requestContext: executionRequestContext ?? 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, suspendPayload, ...rest } = baseContext;\n            organizedContext = {\n              ...rest,\n              workflow: {\n                workflowId,\n                runId,\n                state,\n                setState,\n                suspend,\n                resumeData,\n                suspendPayload,\n              },\n              // Ensure requestContext is always present\n              requestContext: executionRequestContext ?? 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                    agentId: baseContext.agent.agentId ?? '',\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: executionRequestContext ?? new RequestContext(),\n            };\n          }\n        }\n\n        const resumeData =\n          organizedContext.agent?.resumeData ?? organizedContext.workflow?.resumeData ?? organizedContext?.resumeData;\n\n        if (resumeData != null) {\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' | 'execute'\n> & {\n  inputSchema?: TInputSchema;\n  outputSchema?: TOutputSchema;\n  suspendSchema?: TSuspendSchema;\n  resumeSchema?: TResumeSchema;\n  execute?: ToolExecuteFunction<InferSchema<TInputSchema>, InferSchema<TOutputSchema>, TContext, TRequestContext>;\n};\n/**\n * Defines a tool with a description, input/output schemas, and an execution function.\n *\n * @example\n * ```typescript\n * import { createTool } from '@mastra/core/tools';\n * import { z } from 'zod';\n *\n * const greet = createTool({\n *   id: 'greet',\n *   description: 'Greet someone by name.',\n *   inputSchema: z.object({ name: z.string() }),\n *   outputSchema: z.string(),\n *   execute: async ({ name }) => `Hello, ${name}!`,\n * });\n * ```\n *\n * @see For documentation bundled with your installed package, locate\n * `@mastra/core/package.json` with your project's resolver or package-manager\n * tooling, then read `dist/docs/SKILL.md` from that package root and follow its\n * reference links. Use package-manager tools for virtual or archived packages.\n *\n * @see [Tool documentation](https://mastra.ai/reference/tools/create-tool)\n * if packaged docs are unavailable.\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"],"mappings":";;;;;AAGA,MAAa,+BAA+B,OAAO,IAAI,0CAA0C;;;;;;;;;;AAejG,SAAgB,6BAA6B,gBAA6D;CACxG,IAAI,UAAU;CACd,MAAM,uBAAO,IAAI,IAAoB;CAErC,OAAO,WAAW,CAAC,KAAK,IAAI,OAAO,GAAG;EACpC,KAAK,IAAI,OAAO;EAChB,MAAM,SAAS,QAAQ;EACvB,IAAI,CAAC,QACH,OAAO;EAET,UAAU;CACZ;CAEA,OAAO;AACT;;AAGA,SAAgB,6BAA6B,gBAAsD;CACjG,OAAO,6BAA6B,cAAc,CAAC,EAAE,OAAO,CAAC;AAC/D;;;ACrCA,MAAM,2CAA2B,IAAI,QAAgB;AAErD,SAAgB,0BAA0B,SAAuB;CAC/D,yBAAyB,IAAI,OAAO;AACtC;AAEA,SAAgB,6BAA6B,SAA2B;CACtE,IAAI,OAAO,YAAY,YAAY,YAAY,QAAQ,CAAC,yBAAyB,IAAI,OAAO,GAC1F,OAAO;CAGT,yBAAyB,OAAO,OAAO;CACvC,OAAO;AACT;;;ACPA,MAAM,gCAA+C,OAAO,IAAI,oCAAoC;AAOpG,SAAgB,mCAAmC,MAAc,QAAuB;CACtF,IAAI,EAAA,GAAA,6BAAA,yBAAA,CAA0B,MAAM,GAAG;CAEvC,OAAO,eAAe,MAAM,+BAA+B;EACzD,cAAc;EACd,YAAY;EACZ,OAAO;CACT,CAAC;AACH;AAEA,SAAgB,kCAAkC,MAAgE;CAChH,MAAM,eAAe,OAAO,KAAK,iBAAiB,aAAa,KAAK,aAAa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