@mastra/core
Version:
1 lines • 132 kB
Source Map (JSON)
{"version":3,"file":"tool-BMl4Lb5_.cjs","names":["createObservabilityContext","executeWithContext","isStandardSchemaWithJSON","standardSchemaToJSONSchema","toStandardSchema","unwrapZodType","isZodObject","getZodTypeName","isZodArray","toStandardSchema","RequestContext","resolveCurrentSpan"],"sources":["../src/request-context/input-source.ts","../src/tools/builder-validation-context.ts","../src/tools/types.ts","../src/tools/observe.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 { WritableStream } from 'node:stream/web';\nimport type {\n Tool,\n ToolV5,\n FlexibleSchema,\n ToolCallOptions,\n ToolExecutionOptions,\n Schema,\n} from '@internal/external-types';\nimport type { MastraPrimitives, MastraUnion } from '../action';\nexport type { MastraPrimitives, MastraUnion };\nimport type { MastraDBMessage } from '../agent/message-list';\nimport type { ActorSignal } from '../auth/ee';\nimport type { BackgroundTaskAdoptionContext, ToolBackgroundConfig } from '../background-tasks';\nimport type { MastraBrowser } from '../browser/browser';\nimport type { Mastra } from '../mastra';\nimport type { ObservabilityContext } from '../observability';\nimport type { RequestContext } from '../request-context';\nimport type { PublicSchema } from '../schema';\nimport type { SuspendOptions, OutputWriter } from '../workflows';\nimport type { Workspace } from '../workspace/workspace';\nimport type { ElicitRequest, ElicitResult, ServerContext } from './mcp-types';\nimport type { ToolStream } from './stream';\nimport type { ValidationError } from './validation';\n\nexport type VercelTool = Tool;\nexport type VercelToolV5 = ToolV5;\n\nexport type ToolInvocationOptions = ToolExecutionOptions | ToolCallOptions;\n\n/**\n * Context passed to a global `requireToolApproval` function, evaluated per tool call.\n */\nexport type ToolApprovalContext = {\n /** Name of the tool being called. */\n toolName: string;\n /** Arguments the model is passing to the tool. */\n args: Record<string, unknown>;\n /** Plain object view of the request context, when available. */\n requestContext?: Record<string, unknown>;\n /** Active workspace, when the run is bound to one. */\n workspace?: Workspace;\n};\n\n/**\n * Function form of the global `requireToolApproval` option. Evaluated per tool call;\n * return `true` to require approval for that call, `false` to allow it. Enables\n * conditional, per-call approval policies (e.g. regex matching on `toolName`).\n */\nexport type RequireToolApprovalFn = (ctx: ToolApprovalContext) => boolean | Promise<boolean>;\n\n/**\n * Global tool approval setting. `true` requires approval for every tool call,\n * `false`/omitted requires none, and a function decides per call.\n */\nexport type RequireToolApproval = boolean | RequireToolApprovalFn;\n\n/**\n * Context passed to a per-tool `needsApprovalFn` alongside the parsed tool input.\n * This is the same context surfaced to a tool-level `requireApproval` function.\n */\nexport type NeedsApprovalContext = {\n /** Plain object view of the request context, when available. */\n requestContext?: Record<string, unknown>;\n /** Active workspace, when the run is bound to one. */\n workspace?: Workspace;\n};\n\n/**\n * Per-tool approval predicate attached to a tool instance.\n *\n * This is the runtime-resolved form of a tool's `requireApproval` function (or of an\n * MCP server-level `requireToolApproval` function wrapped by the MCP client). It is\n * evaluated per tool call with the parsed input and the available context; return\n * `true` to require approval for that call, `false` to allow it.\n *\n * It is attached to the tool instance by {@link CoreToolBuilder} / the MCP client and\n * read by the agent runtime. Prefer the public `requireApproval` option on\n * `createTool` over setting this directly.\n */\nexport type NeedsApprovalFn = (input: any, ctx?: NeedsApprovalContext) => boolean | Promise<boolean>;\n\n/**\n * Context passed to a tool's `beforeApproval` hook alongside the parsed tool input.\n */\nexport type BeforeApprovalContext = NeedsApprovalContext & {\n /** ID of the tool call awaiting approval. */\n toolCallId: string;\n /** Name the model used to call the tool. */\n toolName: string;\n};\n\n/**\n * Per-tool hook that runs after the call is known to require approval but before the\n * run suspends for it. Return `{ proceed: false, output }` to reject the call: the run\n * does not pause, the tool does not execute, and `output` is returned to the model as\n * the tool result. Return nothing to continue to the approval gate. `input` is validated\n * against the tool's `inputSchema`; calls whose input fails validation skip the hook.\n */\nexport type BeforeApprovalFn<TInput = any, TOutput = unknown> = (\n input: TInput,\n ctx: BeforeApprovalContext,\n) => void | ToolBeforeHookResult<TOutput> | Promise<void | ToolBeforeHookResult<TOutput>>;\n\n/**\n * Trusted runtime values the agent runtime passes to a built tool's `beforeApproval`\n * wrapper so it can run the same authorization check as `execute`. Not exposed to user hooks.\n * @internal\n */\nexport type BeforeApprovalRuntime = {\n requestContext?: RequestContext;\n actor?: ActorSignal;\n};\n\nexport interface ToolHookContext<\n TInput = unknown,\n TContext = unknown,\n TMetadata extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** The name exposed to the model for this tool call. */\n toolName: string;\n /** Input passed to the tool. */\n input: TInput;\n /** Execution context passed to the tool. */\n context: TContext;\n /** Optional adapter-specific metadata. */\n metadata?: TMetadata;\n}\n\nexport interface ToolBeforeHookResult<TOutput = unknown> {\n /** Set to false to skip the tool execution and return `output` instead. */\n proceed: false;\n output: TOutput;\n}\n\nexport interface ToolAfterHookContext<\n TInput = unknown,\n TOutput = unknown,\n TContext = unknown,\n TMetadata extends Record<string, unknown> = Record<string, unknown>,\n> extends ToolHookContext<TInput, TContext, TMetadata> {\n /** Tool output when execution completed. Undefined when execution failed before producing output. */\n output?: TOutput;\n /** Error thrown by the tool, if execution failed. */\n error?: unknown;\n}\n\nexport interface ToolHooks<\n TInput = unknown,\n TOutput = unknown,\n TContext = unknown,\n TMetadata extends Record<string, unknown> = Record<string, unknown>,\n> {\n beforeToolCall?: (\n context: ToolHookContext<TInput, TContext, TMetadata>,\n ) => void | ToolBeforeHookResult<TOutput> | Promise<void | ToolBeforeHookResult<TOutput>>;\n afterToolCall?: (context: ToolAfterHookContext<TInput, TOutput, TContext, TMetadata>) => void | Promise<void>;\n}\n\nexport type ToolPayloadTransformTarget = 'display' | 'transcript';\n\nexport type ToolPayloadTransformPhase =\n | 'input-delta'\n | 'input-available'\n | 'output-available'\n | 'error'\n | 'approval'\n | 'suspend'\n | 'resume';\n\nexport type ToolPayloadTransformContext<TInput = unknown, TOutput = unknown, TError = unknown> = {\n target: ToolPayloadTransformTarget;\n phase: ToolPayloadTransformPhase;\n toolName: string;\n toolCallId: string;\n input?: TInput;\n inputTextDelta?: string;\n output?: TOutput;\n error?: TError;\n suspendPayload?: unknown;\n resumeData?: unknown;\n providerMetadata?: Record<string, unknown>;\n context?: Record<string, unknown>;\n};\n\nexport type ToolPayloadTransformResult = unknown;\n\nexport type ToolPayloadTransformFunction<TInput = unknown, TOutput = unknown, TError = unknown> = (\n context: ToolPayloadTransformContext<TInput, TOutput, TError>,\n) => ToolPayloadTransformResult | Promise<ToolPayloadTransformResult>;\n\nexport type ToolPayloadTransformTargetConfig<TInput = unknown, TOutput = unknown, TError = unknown> = {\n input?: ToolPayloadTransformFunction<TInput, TOutput, TError>;\n inputDelta?: ToolPayloadTransformFunction<TInput, TOutput, TError>;\n output?: ToolPayloadTransformFunction<TInput, TOutput, TError>;\n error?: ToolPayloadTransformFunction<TInput, TOutput, TError>;\n approval?: ToolPayloadTransformFunction<TInput, TOutput, TError>;\n suspend?: ToolPayloadTransformFunction<TInput, TOutput, TError>;\n resume?: ToolPayloadTransformFunction<TInput, TOutput, TError>;\n};\n\nexport type ToolPayloadTransform<TInput = unknown, TOutput = unknown, TError = unknown> = Partial<\n Record<ToolPayloadTransformTarget, ToolPayloadTransformTargetConfig<TInput, TOutput, TError>>\n>;\n\nexport type ToolPayloadTransformPolicy = {\n transformToolPayload?: ToolPayloadTransformFunction;\n targets?: ToolPayloadTransformTarget[];\n};\n\n/**\n * Observability helpers available on the tool execution context.\n * Wraps child span creation and structured log emission in a\n * null-safe API that callers never need to check — when no tracing\n * context is active, `span` runs the function directly and `log` is\n * a no-op.\n */\nexport interface ToolObserve {\n span<T>(name: string, fn: () => Promise<T> | T, attributes?: Record<string, unknown>): Promise<T>;\n log(level: 'debug' | 'info' | 'warn' | 'error' | 'fatal', message: string, data?: Record<string, unknown>): void;\n}\n\n/**\n * A no-op ToolObserve implementation. `span` runs the function\n * directly; `log` does nothing. Used as the default when no\n * collector/tracing context is active, so user code never needs to\n * null-check `observe`.\n */\nexport const noopObserve: ToolObserve = {\n async span<T>(_name: string, fn: () => Promise<T> | T): Promise<T> {\n return fn();\n },\n log(): void {},\n};\n\n/**\n * MCP-specific context properties available during tool execution in MCP environments.\n */\n// Agent tool execution context - properties specific when tools are executed by agents\nexport interface AgentToolExecutionContext<TSuspend, TResume> {\n // Always present when called from agent context\n agentId: string;\n toolCallId: string;\n messages: any[];\n /**\n * Reads the current in-memory conversation, including remembered messages and this run's responses.\n * Reflects message-list removals, but not transient provider-prompt transforms. Treat messages as read-only.\n * Not available outside a supported agent loop.\n */\n getMessages?: () => readonly MastraDBMessage[];\n suspend: (suspendPayload: TSuspend, suspendOptions?: SuspendOptions) => Promise<void>;\n\n // Optional - memory identifiers\n threadId?: string;\n resourceId?: string;\n\n // Optional - only present if tool was previously suspended\n resumeData?: TResume;\n /** Framework-resolved delegated run ID recovered from persisted suspension state. */\n suspendedToolRunId?: string;\n // Optional - the payload this tool suspended with, present on resume\n suspendPayload?: TSuspend;\n\n // Optional - original WritableStream passed from AI SDK (without Mastra metadata wrapping)\n writableStream?: WritableStream<any>;\n\n /**\n * Flushes the parent stream's pending messages to persistent storage.\n * See `MastraToolInvocationOptions.flushMessages` for details.\n */\n flushMessages?: () => Promise<void>;\n\n /**\n * True when the tool is running as a dispatched background task rather than\n * inline in the agent loop. The parent model has already received a\n * placeholder result by the time the tool executes.\n */\n isBackgroundTask?: boolean;\n}\n\n// Workflow tool execution context - properties specific when tools are executed in workflows\nexport interface WorkflowToolExecutionContext<TSuspend, TResume> {\n // Always present when called from workflow context\n runId: string;\n workflowId: string;\n state: any;\n /** Resolves to the run's state, or only its named top-level keys. Use it instead of `state` on storage v2 runs. */\n getState: (keys?: readonly string[]) => Promise<any>;\n setState: (state: any) => void;\n /** Merges the given top-level keys into the run's state and validates the merged state. */\n updateState: (state: any) => void;\n suspend: (suspendPayload: TSuspend, suspendOptions?: SuspendOptions) => Promise<void>;\n // Optional - only present if workflow step was previously suspended\n resumeData?: TResume;\n /** Framework-resolved delegated run ID recovered from persisted suspension state. */\n suspendedToolRunId?: string;\n // Optional - the payload this step suspended with, present on resume\n suspendPayload?: TSuspend;\n}\n\n/** Log levels for MCP `notifications/message`, ordered per RFC 5424. */\nexport type MCPLoggingLevel = 'debug' | 'info' | 'notice' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency';\n\n/** Protocol context the MCP server hands to a tool as `context.mcp.extra`. */\nexport type MCPServerContext = ServerContext & {\n /** Aborts when the client cancels the request or disconnects. */\n signal: ServerContext['mcpReq']['signal'];\n requestId: ServerContext['mcpReq']['id'];\n authInfo?: NonNullable<ServerContext['http']>['authInfo'];\n /**\n * Raw notification sender.\n * @deprecated Use `context.mcp.log` / `context.mcp.progress`. A 2026-07-28 server throws when this is called.\n * Removed in the next core major.\n */\n sendNotification: ServerContext['mcpReq']['notify'];\n /**\n * Raw server-to-client request sender.\n * @deprecated 2026-07-28 removed server-initiated requests; a 2026-07-28 server throws when this is called.\n * Removed in the next core major.\n */\n sendRequest: ServerContext['mcpReq']['send'];\n /** Request metadata: trace headers, the log-level opt-in and the progress token. */\n _meta?: ServerContext['mcpReq']['_meta'];\n};\n\n/**\n * MCP tool execution context - properties specific when tools are executed via a Model Context Protocol server.\n *\n * `@mastra/mcp` 1.x and 2.x servers both provide it. `extra` (minus the deprecated senders), `log` and `progress`\n * behave the same on either; the deprecated members throw on a 2026-07-28 server with a message pointing at the\n * replacement.\n */\nexport interface MCPToolExecutionContext {\n /** MCP protocol context passed by the server */\n extra: MCPServerContext;\n /**\n * Elicitation handler for interactive user input during tool execution.\n * @deprecated 2026-07-28 removed server-initiated elicitation: call `context.suspend(payload)` and read\n * `context.resumeData` instead. A 2026-07-28 server throws when this is called. Removed in the next core major.\n */\n elicitation: {\n sendRequest: (request: ElicitRequest['params']) => Promise<ElicitResult>;\n };\n /**\n * Sends a `notifications/message` log notification to the calling client.\n * Messages below the client's minimum level are dropped: 1.x reads it from `logging/setLevel`,\n * 2026-07-28 from the request's `_meta`.\n */\n log?: (level: MCPLoggingLevel, message: string, data?: Record<string, unknown>) => Promise<void>;\n /**\n * Sends a `notifications/progress` notification to the calling client.\n * No-op if the caller did not request progress tracking (no progressToken in `_meta`).\n */\n progress?: (params: { progress: number; total?: number; message?: string }) => Promise<void>;\n /** Set by 2026-07-28 servers. Absent on `@mastra/mcp` 1.x. */\n protocolVersion?: '2026-07-28';\n}\n\n/**\n * Extended version of ToolInvocationOptions that includes Mastra-specific properties\n * for suspend/resume functionality, stream writing, and tracing context.\n *\n * This is used by CoreTool/InternalCoreTool for AI SDK compatibility (AI SDK expects this signature).\n * Mastra v1.0 tools (ToolAction) use ToolExecutionContext instead.\n *\n * CoreToolBuilder acts as the adapter layer:\n * - Receives: AI SDK calls with MastraToolInvocationOptions\n * - Converts to: ToolExecutionContext for Mastra tool execution\n * - Returns: Results back to AI SDK\n */\nexport type MastraToolInvocationOptions = ToolInvocationOptions &\n Partial<ObservabilityContext> & {\n suspend?: (suspendPayload: any, suspendOptions?: SuspendOptions) => Promise<any>;\n resumeData?: any;\n /** Framework-resolved delegated run ID recovered from persisted suspension state. */\n suspendedToolRunId?: string;\n /** The payload the tool previously suspended with, when resuming. */\n suspendPayload?: any;\n outputWriter?: OutputWriter;\n /**\n * Optional MCP-specific context passed when tool is executed in MCP server.\n * This is populated by the MCP server and passed through to the tool's execution context.\n */\n mcp?: MCPToolExecutionContext;\n /**\n * Skip the TOOL_CALL span for this execution. Set by the MCP server, which\n * already wraps the call in an MCP_SERVER_REQUEST span. Nested agent and\n * workflow runs still attach to `tracingContext.currentSpan`.\n */\n skipToolSpan?: boolean;\n /**\n * Workspace for tool execution. When provided at execution time, this overrides\n * any workspace configured at tool build time. Allows dynamic workspace selection\n * per-step via prepareStep.\n */\n workspace?: Workspace;\n /**\n * Request context for tool execution. When provided at execution time, this overrides\n * any requestContext configured at tool build time. Allows workflow steps to forward\n * their requestContext (e.g., authenticated API clients, feature flags) to tools.\n */\n requestContext?: RequestContext;\n /** Trusted server-side signal for this tool FGA check. */\n actor?: ActorSignal;\n /**\n * Flushes the parent stream's pending messages to persistent storage.\n *\n * The agent stream batches message saves through a `SaveQueueManager`\n * (100ms debounce). Tools that read the thread's persisted history\n * mid-stream (e.g. cloning the thread, exporting it, handing off to a\n * sibling agent) must call this first, otherwise the store will be\n * missing the latest user / assistant messages.\n *\n * Populated automatically by the agent tool-call step. No-op when the\n * stream is not memory-backed.\n */\n flushMessages?: () => Promise<void>;\n /** Live conversation reader supplied by the agent loop. Never serialized in workflow state. */\n getMessages?: AgentToolExecutionContext<unknown, unknown>['getMessages'];\n /** Observability helper to expose on the final tool execution context. */\n observe?: ToolObserve;\n /** Set by the agent tool-call step when the tool runs as a background task. */\n isBackgroundTask?: boolean;\n /** Process-local lifecycle bridge for an operation adopted by the background task. */\n background?: BackgroundTaskAdoptionContext;\n };\n\n/**\n * The type of tool registered with the MCP server.\n * This is used to categorize tools in the MCP Server playground.\n * If not specified, it defaults to a regular tool.\n */\nexport type MCPToolType = 'agent' | 'workflow';\n\n/**\n * Metadata identifying a tool as originating from an MCP server.\n * Set automatically by the MCP client when creating tools.\n * Used by CoreToolBuilder to create MCP_TOOL_CALL spans instead of TOOL_CALL spans.\n */\nexport interface McpMetadata {\n serverName: string;\n serverVersion?: string;\n /** Instructions advertised by the MCP server during initialize. */\n serverInstructions?: string;\n /** Whether the agent should append these instructions to its system prompt. Defaults to false (opt-in). */\n forwardInstructions?: boolean;\n /** Maximum number of characters to forward into the agent system prompt. */\n instructionsMaxLength?: number;\n}\n\n/**\n * MCP Tool Annotations for describing tool behavior and UI presentation.\n * These annotations are part of the MCP protocol and are used by clients\n * like OpenAI Apps SDK to control tool card display and permission hints.\n *\n * @see https://spec.modelcontextprotocol.io/specification/2025-03-26/server/tools/#tool-annotations\n */\nexport interface ToolAnnotations {\n /**\n * A human-readable title for the tool.\n * Used for display purposes in UI components.\n */\n title?: string;\n /**\n * If true, the tool does not modify its environment.\n * This hint indicates the tool only reads data and has no side effects.\n * @default false\n */\n readOnlyHint?: boolean;\n /**\n * If true, the tool may perform destructive updates to its environment.\n * If false, the tool performs only additive updates.\n * This hint helps clients determine if confirmation should be required.\n * @default true\n */\n destructiveHint?: boolean;\n /**\n * If true, calling the tool repeatedly with the same arguments\n * will have no additional effect on its environment.\n * This hint indicates idempotent behavior.\n * @default false\n */\n idempotentHint?: boolean;\n /**\n * If true, this tool may interact with an \"open world\" of external\n * entities (e.g., web search, external APIs).\n * If false, the tool's domain is closed and fully defined.\n * @default true\n */\n openWorldHint?: boolean;\n}\n\n// MCP-specific properties for tools\nexport interface MCPToolProperties {\n /**\n * The type of tool registered with the MCP server.\n * This is used to categorize tools in the MCP Server playground.\n * If not specified, it defaults to a regular tool.\n */\n toolType?: MCPToolType;\n /**\n * MCP tool annotations for describing tool behavior and UI presentation.\n * These are exposed via MCP protocol and used by clients like OpenAI Apps SDK.\n * @see https://spec.modelcontextprotocol.io/specification/2025-03-26/server/tools/#tool-annotations\n */\n annotations?: ToolAnnotations;\n /**\n * Arbitrary metadata that will be passed through to MCP clients.\n * This field allows custom metadata to be attached to tools for\n * client-specific functionality.\n */\n _meta?: Record<string, unknown>;\n}\n\n/**\n * CoreTool is the AI SDK-compatible tool format used when passing tools to the AI SDK.\n * This matches the AI SDK's Tool interface.\n *\n * CoreToolBuilder converts Mastra tools (ToolAction) to this format and handles the\n * signature transformation from Mastra's (inputData, context) to AI SDK format (params, options).\n *\n * Key differences from ToolAction:\n * - Uses 'parameters' instead of 'inputSchema' (AI SDK naming)\n * - Execute signature: (params, options: MastraToolInvocationOptions) (AI SDK format)\n * - Supports FlexibleSchema | Schema for broader AI SDK compatibility\n */\nexport type CoreTool = {\n title?: string;\n description?: string;\n parameters: FlexibleSchema<any> | Schema;\n outputSchema?: FlexibleSchema<any> | Schema;\n execute?: (params: any, options: MastraToolInvocationOptions) => Promise<any>;\n /**\n * Enables strict tool input generation for providers that support it.\n */\n strict?: boolean;\n /**\n * Provider-specific options passed to the model when this tool is used.\n */\n providerOptions?: Record<string, Record<string, unknown>>;\n /**\n * Optional MCP-specific properties.\n * Only populated when the tool is being used in an MCP context.\n */\n mcp?: MCPToolProperties;\n /**\n * Optional function to transform tool output before returning to the model.\n * Receives the raw tool output and returns a transformed representation.\n * Passed through from the original tool definition.\n */\n toModelOutput?: (output: unknown) => unknown;\n transform?: ToolPayloadTransform;\n /**\n * Examples of valid tool inputs. Each example contains an `input` object\n * showing what valid arguments look like.\n * Passed through to the AI SDK which forwards them to model providers\n * that support input examples (e.g., Anthropic's `input_examples` beta feature).\n */\n inputExamples?: Array<{ input: Record<string, unknown> }>;\n onInputStart?: (options: ToolCallOptions) => void | PromiseLike<void>;\n onInputDelta?: (options: { inputTextDelta: string } & ToolCallOptions) => void | PromiseLike<void>;\n onInputAvailable?: (options: { input: any } & ToolCallOptions) => void | PromiseLike<void>;\n onOutput?: (\n options: { output: any; toolName: string } & Omit<ToolCallOptions, 'messages'>,\n ) => void | PromiseLike<void>;\n /** Background task configuration for this tool. */\n background?: ToolBackgroundConfig;\n} & (\n | {\n type?: 'function' | undefined;\n id?: string;\n }\n | {\n type: 'provider-defined';\n id: `${string}.${string}`;\n args: Record<string, unknown>;\n }\n);\n\n/**\n * InternalCoreTool is identical to CoreTool but with stricter typing.\n * Used internally where we know the schema has already been converted to AI SDK Schema format.\n *\n * The only difference: parameters must be Schema (not FlexibleSchema | Schema)\n */\nexport type InternalCoreTool = {\n title?: string;\n description?: string;\n parameters: Schema;\n outputSchema?: Schema;\n execute?: (params: any, options: MastraToolInvocationOptions) => Promise<any>;\n /**\n * Enables strict tool input generation for providers that support it.\n */\n strict?: boolean;\n /**\n * Provider-specific options passed to the model when this tool is used.\n */\n providerOptions?: Record<string, Record<string, unknown>>;\n /**\n * Optional MCP-specific properties.\n * Only populated when the tool is being used in an MCP context.\n */\n mcp?: MCPToolProperties;\n /**\n * Optional function to transform tool output before returning to the model.\n * Receives the raw tool output and returns a transformed representation.\n * Passed through from the original tool definition.\n */\n toModelOutput?: (output: unknown) => unknown;\n transform?: ToolPayloadTransform;\n /**\n * Examples of valid tool inputs. Each example contains an `input` object\n * showing what valid arguments look like.\n * Passed through to the AI SDK which forwards them to model providers\n * that support input examples (e.g., Anthropic's `input_examples` beta feature).\n */\n inputExamples?: Array<{ input: Record<string, unknown> }>;\n onInputStart?: (options: ToolCallOptions) => void | PromiseLike<void>;\n onInputDelta?: (options: { inputTextDelta: string } & ToolCallOptions) => void | PromiseLike<void>;\n onInputAvailable?: (options: { input: any } & ToolCallOptions) => void | PromiseLike<void>;\n onOutput?: (\n options: { output: any; toolName: string } & Omit<ToolCallOptions, 'messages'>,\n ) => void | PromiseLike<void>;\n /** Background task configuration for this tool. */\n background?: ToolBackgroundConfig;\n} & (\n | {\n type?: 'function' | undefined;\n id?: string;\n }\n | {\n type: 'provider-defined';\n id: `${string}.${string}`;\n args: Record<string, unknown>;\n }\n);\n\n// Unified tool execution context that works for all scenarios\nexport interface ToolExecutionContext<\n TSuspend = unknown,\n TResume = unknown,\n TRequestContext extends Record<string, any> | unknown = unknown,\n> extends Partial<ObservabilityContext> {\n // ============ Common properties (available in all contexts) ============\n mastra?: MastraUnion;\n requestContext?: RequestContext<TRequestContext>;\n abortSignal?: AbortSignal;\n /** Trusted server-side signal forwarded for nested FGA checks. */\n actor?: ActorSignal;\n\n /**\n * Workspace available for tool execution. When provided, tools can access:\n * - workspace.filesystem - for file operations (read, write, list, etc.)\n * - workspace.sandbox - for command execution\n *\n * This allows tools to work with the agent's configured workspace.\n */\n workspace?: Workspace;\n\n /**\n * Browser available for tool execution. When provided, tools can access\n * browser capabilities for web automation, screenshots, and data extraction.\n *\n * The browser is lazily initialized - it will be launched on first use.\n */\n browser?: MastraBrowser;\n\n // Writer is created by Mastra for ALL contexts (agent, workflow, direct execution)\n // Wraps chunks with metadata (toolCallId, toolName, runId) before passing to underlying stream\n writer?: ToolStream;\n\n // ============ Context-specific nested properties ============\n\n // Agent-specific properties\n agent?: AgentToolExecutionContext<TSuspend, TResume>;\n\n // Workflow-specific properties\n workflow?: WorkflowToolExecutionContext<TSuspend, TResume>;\n\n // MCP (Model Context Protocol) specific context\n mcp?: MCPToolExecutionContext;\n\n /**\n * Process-local lifecycle bridge exposed only during native background\n * execution. Acknowledgement-returning tools can adopt their existing\n * operation so the native task remains running until it settles.\n */\n background?: BackgroundTaskAdoptionContext;\n\n // ============ Suspend/resume for direct and MCP 2.x execution ============\n // Agents and workflows nest these under `agent` / `workflow` until the next core major.\n\n /** Suspends the tool with a payload validated against `suspendSchema`. On an MCP 2.x server this ends the request as `input_required`. */\n suspend?: (suspendPayload: TSuspend, suspendOptions?: SuspendOptions) => Promise<void>;\n /** The answer to the last suspension, validated against `resumeSchema`. Present only when resuming. */\n resumeData?: TResume;\n /** The payload the tool last suspended with. Present only when resuming. */\n suspendPayload?: TSuspend;\n\n /**\n * Observability helpers for recording child spans and structured logs\n * from inside a tool's execute function. Always provided to the tool's\n * `execute` callback (callers of `tool.execute()` may omit it) — when no\n * tracing context is active, `span` runs the function directly and\n * `log` is a no-op. No null-checking needed.\n *\n * ```ts\n * execute: async ({ userId }, { observe }) => {\n * observe.log('info', 'fetching user', { userId })\n * return observe.span('fetch user', () => fetch(`/api/users/${userId}`))\n * }\n * ```\n */\n observe: ToolObserve;\n}\n\n/**\n * Context accepted when calling `tool.execute(input, context)` directly. `observe`\n * is optional here because the tool runtime fills it in (a no-op implementation\n * when no tracing span is active); the tool's own `execute` callback always\n * receives it.\n */\nexport type ToolExecuteCallContext<TContext> = Omit<TContext, 'observe'> & {\n observe?: ToolObserve;\n};\n\n/**\n * Context received by a tool's `execute` callback. The runtime always provides\n * `requestContext` (an empty one is created if the caller passed none), so it\n * is non-optional here — like `observe`. No null-checking needed.\n */\nexport type ToolExecuteContext<TContext, TRequestContext extends Record<string, any> | unknown = unknown> = Omit<\n TContext,\n 'requestContext'\n> & {\n requestContext: RequestContext<TRequestContext>;\n};\n\n/** The `execute` callback signature used by `createTool` and `new Tool(...)`. */\nexport type ToolExecuteFunction<\n TSchemaIn,\n TSchemaOut,\n TContext,\n TRequestContext extends Record<string, any> | unknown = unknown,\n> = (\n inputData: TSchemaIn,\n context: ToolExecuteContext<TContext, TRequestContext>,\n) => Promise<TSchemaOut | ValidationError | void>;\n\nexport interface ToolAction<\n TSchemaIn,\n TSchemaOut,\n TSuspend = unknown,\n TResume = unknown,\n TContext extends ToolExecutionContext<TSuspend, TResume, any> = ToolExecutionContext<TSuspend, TResume>,\n TId extends string = string,\n TRequestContext extends Record<string, any> | unknown = unknown,\n> {\n id: TId;\n /** Display name for UIs and MCP clients. Never sent to the model. */\n title?: string;\n description: string;\n inputSchema?: PublicSchema<TSchemaIn>;\n outputSchema?: PublicSchema<TSchemaOut>;\n suspendSchema?: PublicSchema<TSuspend>;\n resumeSchema?: PublicSchema<TResume>;\n /**\n * Optional schema for validating request context values.\n * When provided, the request context will be validated against this schema before tool execution.\n * If validation fails, a validation error is returned instead of executing the tool.\n */\n requestContextSchema?: PublicSchema<TRequestContext, any>;\n /**\n * Optional MCP-specific properties.\n * Only populated when the tool is being used in an MCP context.\n */\n mcp?: MCPToolProperties;\n /**\n * Optional function to transform tool output before returning to the model.\n * Receives the raw tool output and returns a transformed representation.\n * Passed through from the original tool definition.\n */\n toModelOutput?: (output: TSchemaOut) => unknown;\n /**\n * Optional target-aware transform for tool payloads that leave runtime.\n *\n * Runtime execution still receives raw inputs and outputs. These transforms\n * are used by display and transcript serializers to avoid exposing internal\n * payload fields.\n */\n transform?: ToolPayloadTransform<TSchemaIn, TSchemaOut>;\n // Execute signature with unified context type\n // First parameter: raw input data (validated against inputSchema)\n // Second parameter: unified execution context with all metadata\n // Returns: The expected output, a validation error, or void when the tool\n // suspends via `context.agent?.suspend?.(...)` / `context.workflow?.suspend?.(...)`.\n // When `suspend` has been called, the tool runtime skips output validation\n // (see `Tool.execute` in tool.ts), so returning `undefined` after `suspend`\n // is the supported idiom (e.g. `return await suspend(...)`).\n // Note: When no outputSchema is provided, returns any to allow property access\n // Note: For outputSchema, we use the input type because Zod transforms are applied during validation\n // Note: { error?: never } enables inline type narrowing with 'error' in result checks\n execute?: (inputData: TSchemaIn, context: TContext) => Promise<TSchemaOut | ValidationError | void>;\n /**\n * Display-only tool: stream the call to the client, return `{ acknowledged: true }`\n * from the server, and continue the model loop without waiting for a browser result.\n * Cannot be combined with `execute`.\n */\n renderOnly?: boolean;\n mastra?: Mastra;\n /**\n * Whether the tool requires explicit user approval before execution.\n * Pass `true` to always require approval, or a function evaluated per-call\n * with the tool input (and optional request context/workspace) to require\n * approval conditionally.\n */\n requireApproval?:\n | boolean\n | ((\n input: TSchemaIn,\n ctx?: { requestContext?: Record<string, unknown>; workspace?: Workspace },\n ) => boolean | Promise<boolean>);\n /**\n * Runs before the approval gate for calls that require approval. Use it to validate a\n * call (e.g. check that referenced records exist) so invalid calls are never shown to a\n * human. Return `{ proceed: false, output }` to reject: the run does not suspend, the\n * tool does not execute, and `output` is returned to the model as the tool result.\n * Not run on resume, so keep validating inside `execute` if state can change while paused.\n * If the hook throws, the error is logged and the call continues to the approval gate.\n */\n beforeApproval?: BeforeApprovalFn<TSchemaIn>;\n /**\n * Enables strict tool input generation for providers that support it.\n * When enabled, supported providers will attempt to generate arguments\n * that exactly match the tool schema.\n */\n strict?: boolean;\n /**\n * How a result that fails `outputSchema` validation is handled.\n * - `'strict'` (default): the result is replaced with a validation error object, so the\n * model is told the call failed.\n * - `'warn'`: the failure is logged and the tool's actual result is returned unchanged.\n * Use this for tools whose side effects have already happened when the result is\n * produced (an order was placed, a message was sent), so the model does not retry them.\n */\n outputValidation?: 'strict' | 'warn';\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 * Metadata identifying this tool as originating from an MCP server.\n * Set automatically by the MCP client when creating tools.\n * Used by CoreToolBuilder to create MCP_TOOL_CALL spans instead of TOOL_CALL spans.\n */\n mcpMetadata?: McpMetadata;\n /**\n * Examples of valid tool inputs. Each example contains an `input` object\n * showing what valid arguments look like.\n * Passed through to the AI SDK which forwards them to model providers\n * that support input examples (e.g., Anthropic's `input_examples` beta feature).\n */\n inputExamples?: Array<{ input: Record<string, unknown> }>;\n onInputStart?: (options: ToolCallOptions) => void | PromiseLike<void>;\n onInputDelta?: (\n options: {\n inputTextDelta: string;\n } & ToolCallOptions,\n ) => void | PromiseLike<void>;\n onInputAvailable?: (\n options: {\n input: TSchemaIn;\n } & ToolCallOptions,\n ) => void | PromiseLike<void>;\n onOutput?: (\n options: {\n output: TSchemaOut;\n toolName: string;\n } & Omit<ToolCallOptions, 'messages'>,\n ) => void | PromiseLike<void>;\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","import { createObservabilityContext, SpanType } from '../observability';\nimport type { AnySpan, AIBaseAttributes } from '../observability';\nimport { executeWithContext } from '../observability/utils';\nimport type { ToolObserve } from './types';\nimport { noopObserve } from './types';\n\nexport function createToolObserve(span?: AnySpan): ToolObserve {\n if (!span?.isValid) {\n return noopObserve;\n }\n\n const logger = createObservabilityContext({ currentSpan: span }).loggerVNext;\n\n return {\n log(level, message, data) {\n logger[level](message, data);\n },\n async span(name, fn, attributes) {\n const childSpan = span.createChildSpan({\n type: SpanType.GENERIC,\n name,\n attributes: attributes as AIBaseAttributes,\n });\n\n try {\n const result = await executeWithContext({\n span: childSpan,\n fn: async () => fn(),\n });\n childSpan.end({ output: result });\n return result;\n } catch (error) {\n childSpan.error({ error: error instanceof Error ? error : new Error(String(error)), endSpan: true });\n throw error;\n }\n },\n };\n}\n","import type { JSONSchema7, JSONSchema7Definition } from 'json-schema';\nimport 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 =\n typeof tool.outputSchema === 'function' && !isStandardSchemaWithJSON(tool.outputSchema)\n ? tool.outputSchema()\n : 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 * What the model may see of a validation error when a tool's `toModelOutput` is skipped for it:\n * the failing field paths and a generic issue kind per field. It never quotes issue messages,\n * arguments, tool output, request context or suspend data, because `toModelOutput` is where a\n * tool keeps those out of the prompt.\n */\nexport interface ModelFacingValidationError {\n error: true;\n message: string;\n validationErrors?: FormattedValidationErrors;\n}\n\n// Global so @mastra/client-js can read it without importing this module at runtime.\nconst MODEL_FACING_VALIDATION_ERROR: unique symbol = Symbol.for('mastra.tool.modelFacingValidationError');\n\nfunction markModelFacing<T>(error: ValidationError<T>, modelFacing: ModelFacingValidationError): ValidationError<T> {\n Object.defineProperty(error, MODEL_FACING_VALIDATION_ERROR, { value: modelFacing, enumerable: false });\n return error;\n}\n\nfunction isModelFacingValidationError(value: unknown): value is ModelFacingValidationError {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'error' in value &&\n value.error === true &&\n 'message' in value &&\n typeof value.message === 'string'\n );\n}\n\n/**\n * Returns the model-facing form of a validation error that Mastra's own validation produced, or\n * `undefined` for any other value, including one that only has a validation error's fields.\n *\n * The marker is a non-enumerable symbol property set where the error is created. JSON, spreads\n * and structured clones drop it, so tool output, results a client sent over HTTP, and anything\n * that crossed a serialization boundary never carry it. Read it in the process that ran the tool.\n */\nexport function getModelFacingValidationError(value: unknown): ModelFacingValidationError | undefined {\n if (value === null || typeof value !== 'object') return undefined;\n const marked: unknown = Object.getOwnPropertyDescriptor(value, MODEL_FACING_VALIDATION_ERROR)?.value;\n return isModelFacingValidationError(marked) ? marked : undefined;\n}\n\n/**\n * Issue kinds that may reach the model: Zod v3/v4 `code`s, Valibot schema and action `type`s and\n * ArkType `code`s. A fixed list, because issue metadata is not value-free: a custom check can set\n * `code`, `type` or `expected` to anything, including the rejected value.\n */\nconst MODEL_FACING_ISSUE_KINDS: ReadonlySet<string> = new Set([\n // Zod v3 and v4\n 'invalid_type',\n 'invalid_literal',\n 'invalid_value',\n 'invalid_enum_value',\n 'invalid_union',\n 'invalid_union_discriminator',\n 'invalid_intersection_types',\n 'invalid_arguments',\n 'invalid_return_type',\n 'invalid_date',\n 'invalid_string',\n 'invalid_format',\n 'invalid_key',\n 'invalid_element',\n 'unrecognized_keys',\n 'too_small',\n 'too_big',\n 'not_multiple_of',\n 'not_finite',\n 'custom',\n // Valibot action types (schema types are covered by MODEL_FACING_TYPE_NAMES)\n 'email',\n 'url',\n 'uuid',\n 'regex',\n 'check',\n 'length',\n 'min_length',\n 'max_length',\n 'non_empty',\n 'min_value',\n 'max_value',\n 'iso_date',\n 'iso_date_time',\n 'iso_timestamp',\n // ArkType\n 'domain',\n 'required',\n 'predicate',\n 'pattern',\n 'divisor',\n 'min',\n 'max',\n 'minLength',\n 'maxLength',\n 'exactLength',\n 'unit',\n 'proto',\n 'after',\n 'before',\n]);\n\n/** Plain type names that may reach the model as an issue's expected type (or Valibot's schema `type`). */\nconst MODEL_FACING_TYPE_NAMES: ReadonlySet<string> = new Set([\n 'string',\n 'number',\n 'bigint',\n 'boolean',\n 'symbol',\n 'undefined',\n 'null',\n 'object',\n 'array',\n 'tuple',\n 'record',\n 'map',\n 'set',\n 'date',\n 'function',\n 'integer',\n 'int',\n 'nan',\n 'literal',\n 'enum',\n 'picklist',\n 'union',\n 'variant',\n 'never',\n 'nonoptional',\n 'nonnullable',\n 'nonnullish',\n]);\n\n/**\n * Generic, value-free description of one issue for the model: the schema library's issue kind\n * (Zod's `code`, Valibot's `type`, ArkType's `code`) and the expected type, each only when it is\n * on a fixed list, else `invalid`. Issue messages are left out: custom refinements can quote\n * anything, including values an input transform resolved, and built-in messages can quote the\n * rejected value.\n */\nfunction describeIssueForModel(issue: StandardSchemaIssue): string {\n const listed = (key: string, allowed: ReadonlySet<string>): string | undefined => {\n const value: unknown = Reflect.get(issue, key);\n return typeof value === 'string' && allowed.has(value) ? value : undefined;\n };\n const kind =\n listed('code', MODEL_FACING_ISSUE_KINDS) ??\n listed('type', MODEL_FACING_ISSUE_KINDS) ??\n listed('type', MODEL_FACING_TYPE_NAMES) ??\n 'invalid';\n const expected = listed('expected', MODEL_FACING_TYPE_NAMES);\n return expected ? `${kind} (expected ${expected})` : kind;\n}\n\n/**\n * Model-facing form of a validation error, used when a tool's `toModelOutput` is skipped for it:\n * each failing field path, sanitized like {@link getValidationIssuePaths}, with a generic issue\n * kind. It never carries issue messages, received values or excerpts of the validated data.\n */\nfunction modelFacingError(params: {\n issues: readonly StandardSchemaIssue[];\n schema: PublicSchema | undefined;\n io: 'input' | 'output';\n heading: string;\n}): ModelFacingValidationError {\n const sanitizePath = createIssuePathSanitizer(params.schema, params.io);\n const issues = params.issues.map(issue => ({\n path: sanitizePath((issue.path ?? []).map(segment => getPathKey(segment))),\n message: describeIssueForModel(issue),\n }));\n const lines = issues.map(issue => `- ${issue.path.join('.') || 'root'}: ${issue.message}`).join('\\n');\n return {\n error: true,\n message: `${params.heading}\\n${lines}`,\n validationErrors: buildFormattedErrors(issues),\n };\n}\n\ntype JSONSchemaNode = JSONSchema7Definition | undefined;\n\n/**\n * Returns a function that keeps only the path segments `schema` declares: property names and array\n * indexes. Any other segment (a record key, or anything under a schema that can't be resolved)\n * came from the validated data and becomes `*`.\n */\nfunction createIssuePathSanitizer(\n schema: PublicSchema | undefined,\n io: 'input' | 'output',\n): (path: readonly string[]) => string[] {\n let root: JSONSchemaNode;\n try {\n root = schema ? standardSchemaToJSONSchema(toStandardSchema(schema), { io }) : undefined;\n } catch {\n root = undefined;\n }\n\n const resolve = (node: JSONSchemaNode, seen = new Set<string>()): JSONSchema7[] => {\n if (!node || typeof node !== 'object') return [];\n if (node.$ref?.startsWith('#/') && typeof root === 'object' && !seen.has(node.$ref)) {\n seen.add(node.$ref);\n const target = node.$ref\n .slice(2)\n .split('/')\n .reduce<unknown>((at, key) => (at as Record<string, unknown> | undefined)?.[key], root);\n return resolve(target as JSONSchemaNode, seen);\n }\n return [\n node,\n ...[...(node.anyOf ?? []), ...(node.oneOf ?? []), ...(node.allOf ?? [])].flatMap(branch => resolve(branch, seen)),\n ];\n };\n\n const child = (nodes: JSONSchema7[], key: string): { segment: string; nodes: JSONSchema7[] } => {\n const declared = nodes.filter(node => node.properties && Object.hasOwn(node.properties, key));\n if (declared.length > 0) return { segment: key, nodes: declared.flatMap(node => resolve(node.properties![key])) };\n if (/^\\d+$/.test(key)) {\n const items = nodes.flatMap(node =>\n Array.isArray(node.items) ? resolve(node.items[Number(key)]) : resolve(node.items),\n );\n if (items.length > 0 || nodes.some(node => node.type === 'array')) return { segment: key, nodes: items };\n }\n return {\n segment: '*',\n nodes: nodes.flatMap(node => [\n ...resolve(node.additionalProperties),\n ...Object.values(node.patternProperties ?? {}).flatMap(pattern => resolve(pattern)),\n ]),\n };\n };\n\n const rootNodes = resolve(root);\n return path => {\n let nodes = rootNodes;\n return path.map(key => {\n const next = child(nodes, key);\n nodes = next.nodes;\n return next.segment;\n });\n };\n}\n\n/**\n * Lists the dotted paths that failed validation (`root` for top-level issues), for log lines.\n * `message` echoes the submitted values back to the caller, so logs carry these paths instead.\n * Only property names declared by `schema` and array indexes are kept; any other segment (a record\n * key, or anything under a schema that can't be resolved) came from the submitted data and is logged as `*`.\n */\nexport function getValidationIssuePaths(\n error: ValidationError,\n schema: PublicSchema | undefined,\n io: 'input' | 'output' = 'input',\n): string[] {\n const sanitizePath = createIssuePathSanitizer(schema, io);\n const paths: string[] = [];\n const walk = (node: { errors: string[]; fields: unknown }, path: string[]) => {\n if (node.errors.length > 0) paths.push(sanitizePath(path).join('.') || 'root');\n for (const [key, field] of Object.entries((node.fields ?? {}) as Record<string, typeof node>)) {\n walk(field, [...path, key]);\n }\n };\n walk(error.validationErrors, []);\n return [...new Set(paths)];\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 * Builds a path-aware Error from Standard Schema issues.\n * The `errors` array lets consumers (e.g. the @mastra/mcp 1.x tools/call handler) report one line per field.\n */\nexport function createStandardSchemaIssuesError(issues: ReadonlyArray<StandardSchemaIssue>): Error & {\n errors: { path: string[]; message: string }[];\n} {\n const errors = issues.map(issue => ({\n path: (issue.path ?? []).map(segment => getPathKey(segment)),\n message: issue.message,\n }));\n const message = errors.map(e => `- ${e.path.join('.') || 'root'}: ${e.message}`).join('\\n');\n return Object.assign(new Error(message), { errors });\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>(\n issues: readonly Pick<StandardSchemaIssue, 'message' | 'path'>[],\n): 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 {\n error: markModelFacing(\n error,\n modelFacingError({\n issues: validation.issues,\n schema,\n io: 'input',\n heading: `Tool suspension data validation failed${toolId ? ` for ${toolId}` : ''}. The tool suspended with data that does not match its suspend schema:`,\n }),\n ),\n };\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 //\n // Each fallback builds on the previous one's output so inputs needing several\n // corrections (e.g. stringified JSON plus null optional fields) still validate\n // (GitHub #25825).\n let currentInput = normalizedInput;\n let currentIssues = validation.issues;\n\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 currentInput = coercedInput;\n currentIssues = coercedValidation.issues;\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 currentIssues\n .filter(issue => {\n if (!issue.path || issue.path.length === 0) return false;\n const value = getValueAtPath(currentInput, 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\n ? stripNullishValuesAtPaths(currentInput, failingNullPaths)\n : stripNullishValues(coercedInput !== normalizedInput ? coercedInput : 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 if (failingNullPaths.size > 0) {\n currentInput = normalizedStripped;\n }\n\n let aliasIssues: typeof validation.issues | undefined;\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 (schemaExpectsPrompt && currentInput != null && typeof currentInput === 'object' && !Array.isArray(currentInput)) {\n const obj = currentInput 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 aliasIssues = coercedPromptValidation.issues;\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. A failed prompt-alias retry\n // builds on all prior corrections, so its issues take precedence.\n const finalIssues = aliasIssues ?? (failingNullPaths.size > 0 ? retryValidation.issues : currentIssues);\n const errorMessages = finalIssues\n .map(e => `- ${e.path?.map(p => getPathKey(p)).join('.') || 'root'}: ${e.message}`)\n .join('\\n');\n\n const heading = `Tool input validation failed${toolId ? ` for ${toolId}` : ''}. Please fix the following errors and try again:`;\n const error: ValidationError<T> = {\n error: true,\n message: `${heading}\\n${errorMessages}\\n\\nProvided arguments: ${truncateForLogging(input)}`,\n validationErrors: buildFormattedErrors<T>(finalIssues),\n };\n\n // After an input transform, messages and record keys can carry values the model never sent.\n return { error: markModelFacing(error, modelFacingError({ issues: finalIssues, schema, io: 'input', heading })) };\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(redactSensitiveKeys(output))}`,\n validationErrors: buildFormattedErrors<T>(validation.issues),\n };\n\n return {\n error: markModelFacing(\n error,\n modelFacingError({\n issues: validation.issues,\n schema,\n io: 'output',\n heading: `Tool output validation failed${toolId ? ` for ${toolId}` : ''}. The tool returned output that does not match its output schema:`,\n }),\n ),\n };\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, ancestors: WeakSet<object> = new WeakSet()): unknown {\n // Objects with toJSON (e.g. Date) serialize themselves; walking their own keys would drop them to `{}`.\n if (obj === null || typeof obj !== 'object' || typeof (obj as { toJSON?: unknown }).toJSON === 'function') {\n return obj;\n }\n\n // Leave circular references in place so serialization fails the same way it would without redaction.\n if (ancestors.has(obj)) {\n return obj;\n }\n ancestors.add(obj);\n\n let result: unknown;\n if (Array.isArray(obj)) {\n result = obj.map(item => redactSensitiveKeys(item, ancestors));\n } else {\n const redacted: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (SENSITIVE_KEYS.some(sensitive => key.toLowerCase().includes(sensitive.toLowerCase()))) {\n redacted[key] = '[REDACTED]';\n } else {\n redacted[key] = redactSensitiveKeys(value, ancestors);\n }\n }\n result = redacted;\n }\n\n ancestors.delete(obj);\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 const modelFacing = modelFacingError({\n issues: validation.issues,\n schema,\n io: 'input',\n heading: `Request context validation failed${identifier ? ` for ${identifier}` : ''}. The request context is missing values or has invalid ones:`,\n });\n return { data: contextValues as T, error: markModelFacing(error, modelFacing) };\n}\n","import type { ToolBackgroundConfig } from '../background-tasks';\nimport type { Mastra } from '../mastra';\nimport { resolveCurrentSpan } from '../observability/utils';\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 { createToolObserve } from './observe';\nimport type {\n McpMetadata,\n MCPToolProperties,\n NeedsApprovalFn,\n ToolAction,\n ToolExecuteCallContext,\n ToolExecuteFunction,\n ToolExecutionContext,\n ToolPayloadTransform,\n} from './types';\nimport {\n getValidationIssuePaths,\n validateToolInput,\n validateToolOutput,\n validateToolSuspendData,\n validateRequestContext,\n} from './validation';\nimport type { ValidationError } 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/** Own property descriptors of `target`, with accessors bound to it so they still read it when copied. */\nfunction bindAccessors(target: object): PropertyDescriptorMap {\n const descriptors: PropertyDescriptorMap = Object.getOwnPropertyDescriptors(target);\n for (const descriptor of Object.values(descriptors)) {\n if (descriptor.get) descriptor.get = descriptor.get.bind(target);\n if (descriptor.set) descriptor.set = descriptor.set.bind(target);\n }\n return descriptors;\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, any>;\n\n /**\n * Tool execution function\n * @param inputData - The raw, validated input data\n * @param context - Optional execution context with metadata. `observe` may be omitted;\n * the runtime provides one (a no-op when no tracing span is active). When `context` is\n * omitted (for example when calling a tool directly from a test or script), the tool\n * receives an empty `requestContext` and the default `observe`, but no `mastra`, writer,\n * memory, `threadId`, `resourceId`, or `runId`. Pass a context if the tool relies on any\n * of those.\n * @returns Promise resolving to tool output or a ValidationError if input validation fails\n */\n execute?: {\n (inputData: TSchemaIn, context?: ToolExecuteCallContext<TContext>): Promise<TSchemaOut | ValidationError | void>;\n // Calls always match the signature above. This one is last so that\n // `Parameters<Tool['execute']>[1]` stays the context type without `undefined`.\n (inputData: TSchemaIn, context: ToolExecuteCallContext<TContext>): Promise<TSchemaOut | ValidationError | void>;\n };\n\n /** Whether this tool only displays its call and receives a server acknowledgement. */\n renderOnly?: boolean;\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 * Runs before the approval gate for calls that require approval and can reject the call\n * with `{ proceed: false, output }`, returning `output` to the model without suspending\n * or executing.\n * @example\n * ```typescript\n * beforeApproval: async ({ orderId }) => {\n * if (!(await orderExists(orderId))) {\n * return { proceed: false, output: { error: `Order ${orderId} not found` } };\n * }\n * }\n * ```\n */\n beforeApproval?: NonNullable<\n ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext>['beforeApproval']\n >;\n\n /**\n * Enables strict tool input generation for providers that support it.\n */\n strict?: boolean;\n\n /**\n * How a result that fails `outputSchema` validation is handled: replaced with a\n * validation error (`'strict'`, the default) or logged and returned as-is (`'warn'`).\n */\n outputValidation?: 'strict' | 'warn';\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 * Not called when input, request context or output validation fails: the model receives a validation error that names\n * the failing fields and the kind of each issue, without issue messages or the arguments, output or request context.\n * With `outputValidation: 'warn'`, a failed output check keeps the real result, so this still runs on it.\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.renderOnly = opts.renderOnly;\n this.mastra = opts.mastra;\n this.requireApproval = opts.requireApproval || false;\n this.beforeApproval = opts.beforeApproval;\n this.strict = opts.strict;\n this.outputValidation = opts.outputValidation;\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.renderOnly && opts.execute) {\n throw new Error('A render-only tool cannot also define execute');\n }\n const originalExecute = opts.renderOnly ? async () => ({ acknowledged: true }) : opts.execute;\n if (originalExecute) {\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, updateState, suspend, resumeData, suspendPayload, ...rest } =\n baseContext;\n organizedContext = {\n ...rest,\n workflow: {\n workflowId,\n runId,\n state,\n setState,\n updateState,\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 // Copies descriptors, not values: a workflow's `state` may be a getter that throws.\n workflow: baseContext.workflow\n ? Object.defineProperties(\n {},\n {\n ...bindAccessors(baseContext.workflow),\n suspend: {\n enumerable: true,\n configurable: true,\n writable: true,\n value: (args: any, suspendOptions?: SuspendOptions) => {\n suspendData = args;\n return baseContext.workflow?.suspend?.(args, suspendOptions);\n },\n },\n },\n )\n : baseContext.workflow,\n requestContext: executionRequestContext ?? new RequestContext(),\n };\n }\n }\n\n // Agent tool calls inject `observe` in the tool builder. Direct `tool.execute()` calls and\n // `createStep(tool)` workflow steps do not, so default it here from the caller's span,\n // falling back to the ambient span (e.g. a direct call from inside a traced workflow step).\n if (!organizedContext.observe) {\n organizedContext = {\n ...organizedContext,\n observe: createToolObserve(\n organizedContext.tracingContext?.currentSpan ??\n organizedContext.tracing?.currentSpan ??\n resolveCurrentSpan(),\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 const logger = organizedContext.mastra?.getLogger?.() ?? this.mastra?.getLogger?.();\n logger?.warn('Tool output validation failed', {\n toolId: this.id,\n issuePaths: getValidationIssuePaths(outputValidation.error, this.outputSchema, 'output'),\n });\n if (this.outputValidation === 'warn') {\n // The tool already ran, so keep its real result and only report the mismatch.\n return output;\n }\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;;;;;;;;ACuNA,MAA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