UNPKG

@mastra/core

Version:
1 lines 58.4 kB
{"version":3,"file":"tool-d85xHVkl.cjs","names":["unwrapZodType","isZodObject","getZodTypeName","isZodArray","RequestContext"],"sources":["../src/tools/validation.ts","../src/tools/tool.ts"],"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 // 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 - return the original (non-stripped) error since it's\n // more informative about what the schema actually expects\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 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\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: (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\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 { toStandardSchema } from '../schema';\nimport type { PublicSchema, StandardSchemaWithJSON, InferPublicSchema } from '../schema';\nimport type { SuspendOptions } from '../workflows';\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\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 * 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?: ToolAction<\n TSchemaIn,\n TSchemaOut,\n TSuspendSchema,\n TResumeSchema,\n TContext,\n TId,\n TRequestContext\n >['requireApproval'];\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?: 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 * 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.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);\n\n let data: any = inputData;\n if (!isResuming) {\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 // 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 {\n agentId,\n toolCallId,\n messages,\n suspend,\n resumeData,\n threadId,\n resourceId,\n writableStream,\n ...rest\n } = baseContext;\n organizedContext = {\n ...rest,\n agent: {\n agentId: agentId || '',\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 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: 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' | 'execute'\n> & {\n inputSchema?: TInputSchema;\n outputSchema?: TOutputSchema;\n suspendSchema?: TSuspendSchema;\n resumeSchema?: TResumeSchema;\n execute?: ToolExecuteFunction<InferSchema<TInputSchema>, InferSchema<TOutputSchema>, TContext, TRequestContext>;\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":";;;;;;;;;;;;AAaA,SAAS,aACP,QACA,MAC2D;CAC3D,IAAI;EACF,MAAM,SAAS,OAAO,YAAY,CAAC,SAAS,IAAI;EAChD,IAAI,kBAAkB,SACpB,MAAM,IAAI,MAAM,yEAAyE;EAG3F,IAAI,YAAY,UAAU,MAAM,QAAQ,OAAO,MAAM,KAAK,OAAO,OAAO,SAAS,GAC/E,OAAO,EAAE,QAAQ,OAAO,OAAyC;EAEnE,OAAO;CACT,SAAS,KAAK;EAGZ,IAAI,e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