UNPKG

@mastra/core

Version:
1 lines 31.8 kB
{"version":3,"file":"types-CepZ83u8.cjs","names":["WritableStream"],"sources":["../src/tools/stream.ts","../src/tools/types.ts"],"sourcesContent":["import { WritableStream } from 'node:stream/web';\nimport type { DataChunkType } from '../stream/types';\nimport type { OutputWriter } from '../workflows';\n\nexport class ToolStream extends WritableStream<unknown> {\n private prefix: string;\n private callId: string;\n private name: string;\n private runId: string;\n private writeFn?: OutputWriter;\n\n constructor(\n {\n prefix,\n callId,\n name,\n runId,\n }: {\n prefix: string;\n callId: string;\n name: string;\n runId: string;\n },\n writeFn?: OutputWriter,\n ) {\n super({\n async write(chunk: any) {\n await getInstance()._write(chunk);\n },\n });\n\n const self = this;\n function getInstance() {\n return self;\n }\n\n this.prefix = prefix;\n this.callId = callId;\n this.name = name;\n this.runId = runId;\n this.writeFn = writeFn;\n }\n\n private async _write(data: any) {\n if (this.writeFn) {\n await this.writeFn({\n type: `${this.prefix}-output`,\n runId: this.runId,\n from: 'USER',\n payload: {\n output: data,\n ...(this.prefix === 'workflow-step'\n ? {\n runId: this.runId,\n stepName: this.name,\n }\n : {\n [`${this.prefix}CallId`]: this.callId,\n [`${this.prefix}Name`]: this.name,\n }),\n },\n });\n }\n }\n\n async write(data: any) {\n await this._write(data);\n }\n\n async custom<T extends { type: string }>(data: T extends { type: `data-${string}` } ? DataChunkType : T) {\n if (this.writeFn) {\n await this.writeFn(data);\n }\n }\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 { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { ElicitRequest, ElicitResult } from '@modelcontextprotocol/sdk/types.js';\n\nimport type { MastraPrimitives, MastraUnion } from '../action';\nexport type { MastraPrimitives, MastraUnion };\nimport type { ActorSignal } from '../auth/ee';\nimport type { 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 { 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\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 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\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// 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 setState: (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}\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// MCP tool execution context - properties specific when tools are executed via Model Context Protocol\nexport interface MCPToolExecutionContext {\n /** MCP protocol context passed by the server */\n extra: RequestHandlerExtra<any, any>;\n /** Elicitation handler for interactive user input during tool execution */\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 (set via `logging/setLevel`) are dropped.\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}\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 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 * 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 /** Observability helper to expose on the final tool execution context. */\n observe?: ToolObserve;\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 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 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 * Observability helpers for recording child spans and structured logs\n * from inside a tool's execute function. Always provided — 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 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 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>;\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 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 * 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 * 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"],"mappings":";;AAIA,IAAa,aAAb,cAAgCA,WAAAA,eAAwB;CACtD;CACA;CACA;CACA;CACA;CAEA,YACE,EACE,QACA,QACA,MACA,SAOF,SACA;EACA,MAAM,EACJ,MAAM,MAAM,OAAY;GACtB,MAAM,YAAY,CAAC,CAAC,OAAO,KAAK;EAClC,EACF,CAAC;EAED,MAAM,OAAO;EACb,SAAS,cAAc;GACrB,OAAO;EACT;EAEA,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,OAAO;EACZ,KAAK,QAAQ;EACb,KAAK,UAAU;CACjB;CAEA,MAAc,OAAO,MAAW;EAC9B,IAAI,KAAK,SACP,MAAM,KAAK,QAAQ;GACjB,MAAM,GAAG,KAAK,OAAO;GACrB,OAAO,KAAK;GACZ,MAAM;GACN,SAAS;IACP,QAAQ;IACR,GAAI,KAAK,WAAW,kBAChB;KACE,OAAO,KAAK;KACZ,UAAU,KAAK;IACjB,IACA;MACG,GAAG,KAAK,OAAO,UAAU,KAAK;MAC9B,GAAG,KAAK,OAAO,QAAQ,KAAK;IAC/B;GACN;EACF,CAAC;CAEL;CAEA,MAAM,MAAM,MAAW;EACrB,MAAM,KAAK,OAAO,IAAI;CACxB;CAEA,MAAM,OAAmC,MAAgE;EACvG,IAAI,KAAK,SACP,MAAM,KAAK,QAAQ,IAAI;CAE3B;AACF;;;;;;;;;AC2HA,MAAa,cAA2B;CACtC,MAAM,KAAQ,OAAe,IAAsC;EACjE,OAAO,GAAG;CACZ;CACA,MAAY,CAAC;AACf"}