@mastra/core
Version:
1,213 lines (1,212 loc) • 46.9 kB
JavaScript
import { f as resolveCurrentSpan, t as executeWithContext } from "./utils-DU_pU5SK.js";
import { u as RequestContext } from "./request-context-COnZHt2-.js";
import { isStandardSchemaWithJSON, standardSchemaToJSONSchema, toStandardSchema } from "./schema/index.js";
import { x as createObservabilityContext } from "./observability-D3dpuDDk.js";
import { a as isZodObject, i as isZodArray, r as getZodTypeName, s as unwrapZodType } from "./zod-utils-BDDS_mxU.js";
// src/request-context/input-source.ts
/** @internal */
const REQUEST_CONTEXT_INPUT_SOURCE = Symbol.for("mastra.core.request-context.input-source");
/**
* Returns the input-form context that schema validation should consume.
*
* Schema-transformed execution views retain their source through a global
* symbol so forwarding a view across tools or duplicated module instances does
* not validate already-decoded values again.
*
* @internal
*/
function getRequestContextInputSource(requestContext) {
let current = requestContext;
const seen = /* @__PURE__ */ new Set();
while (current && !seen.has(current)) {
seen.add(current);
const source = current[REQUEST_CONTEXT_INPUT_SOURCE];
if (!source) return current;
current = source;
}
return current;
}
/** @internal */
function getRequestContextInputValues(requestContext) {
return getRequestContextInputSource(requestContext)?.all ?? {};
}
// src/tools/builder-validation-context.ts
const builderValidatedContexts = /* @__PURE__ */ new WeakSet();
function markBuilderValidatedInput(context) {
builderValidatedContexts.add(context);
}
function consumeBuilderValidatedInput(context) {
if (typeof context !== "object" || context === null || !builderValidatedContexts.has(context)) return false;
builderValidatedContexts.delete(context);
return true;
}
// src/tools/types.ts
/**
* A no-op ToolObserve implementation. `span` runs the function
* directly; `log` does nothing. Used as the default when no
* collector/tracing context is active, so user code never needs to
* null-check `observe`.
*/
const noopObserve = {
async span(_name, fn) {
return fn();
},
log() {}
};
// src/tools/observe.ts
function createToolObserve(span) {
if (!span?.isValid) return noopObserve;
const logger = createObservabilityContext({ currentSpan: span }).loggerVNext;
return {
log(level, message, data) {
logger[level](message, data);
},
async span(name, fn, attributes) {
const childSpan = span.createChildSpan({
type: "generic",
name,
attributes
});
try {
const result = await executeWithContext({
span: childSpan,
fn: async () => fn()
});
childSpan.end({ output: result });
return result;
} catch (error) {
childSpan.error({
error: error instanceof Error ? error : new Error(String(error)),
endSpan: true
});
throw error;
}
}
};
}
// src/tools/validation.ts
const TOOL_OUTPUT_VALIDATION_SCHEMA = Symbol.for("mastra.tool.outputValidationSchema");
function registerToolOutputValidationSchema(tool, schema) {
if (!isStandardSchemaWithJSON(schema)) return;
Object.defineProperty(tool, TOOL_OUTPUT_VALIDATION_SCHEMA, {
configurable: true,
enumerable: true,
value: schema
});
}
function resolveToolOutputValidationSchema(tool) {
const outputSchema = typeof tool.outputSchema === "function" && !isStandardSchemaWithJSON(tool.outputSchema) ? tool.outputSchema() : tool.outputSchema;
if (isStandardSchemaWithJSON(outputSchema)) return outputSchema;
return tool[TOOL_OUTPUT_VALIDATION_SCHEMA];
}
/**
* Safely validates data against a Standard Schema.
* Catches internal Zod errors (like undefined union options) and provides better error messages.
*
* @param schema The Standard Schema to validate against
* @param data The data to validate
* @returns The validation result or throws with a descriptive error
*/
function safeValidate(schema, data) {
try {
const result = schema["~standard"].validate(data);
if (result instanceof Promise) throw new Error("Your schema is async, which is not supported. Please use a sync schema.");
if ("issues" in result && Array.isArray(result.issues) && result.issues.length > 0) return { issues: result.issues };
return result;
} catch (err) {
if (err instanceof TypeError && err.message.includes("Cannot read properties of undefined")) throw new Error(`Schema validation failed due to an invalid schema definition. This often happens when a union schema (z.union or z.or) has undefined options. Please check that all schema options are properly defined. Original error: ${err.message}`);
throw err;
}
}
function isValidationError(value) {
return value !== null && typeof value === "object" && "error" in value && value.error === true && "validationErrors" in value;
}
const MODEL_FACING_VALIDATION_ERROR = Symbol.for("mastra.tool.modelFacingValidationError");
function markModelFacing(error, modelFacing) {
Object.defineProperty(error, MODEL_FACING_VALIDATION_ERROR, {
value: modelFacing,
enumerable: false
});
return error;
}
function isModelFacingValidationError(value) {
return value !== null && typeof value === "object" && "error" in value && value.error === true && "message" in value && typeof value.message === "string";
}
/**
* Returns the model-facing form of a validation error that Mastra's own validation produced, or
* `undefined` for any other value, including one that only has a validation error's fields.
*
* The marker is a non-enumerable symbol property set where the error is created. JSON, spreads
* and structured clones drop it, so tool output, results a client sent over HTTP, and anything
* that crossed a serialization boundary never carry it. Read it in the process that ran the tool.
*/
function getModelFacingValidationError(value) {
if (value === null || typeof value !== "object") return void 0;
const marked = Object.getOwnPropertyDescriptor(value, MODEL_FACING_VALIDATION_ERROR)?.value;
return isModelFacingValidationError(marked) ? marked : void 0;
}
/**
* Issue kinds that may reach the model: Zod v3/v4 `code`s, Valibot schema and action `type`s and
* ArkType `code`s. A fixed list, because issue metadata is not value-free: a custom check can set
* `code`, `type` or `expected` to anything, including the rejected value.
*/
const MODEL_FACING_ISSUE_KINDS = /* @__PURE__ */ new Set([
"invalid_type",
"invalid_literal",
"invalid_value",
"invalid_enum_value",
"invalid_union",
"invalid_union_discriminator",
"invalid_intersection_types",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"invalid_format",
"invalid_key",
"invalid_element",
"unrecognized_keys",
"too_small",
"too_big",
"not_multiple_of",
"not_finite",
"custom",
"email",
"url",
"uuid",
"regex",
"check",
"length",
"min_length",
"max_length",
"non_empty",
"min_value",
"max_value",
"iso_date",
"iso_date_time",
"iso_timestamp",
"domain",
"required",
"predicate",
"pattern",
"divisor",
"min",
"max",
"minLength",
"maxLength",
"exactLength",
"unit",
"proto",
"after",
"before"
]);
/** Plain type names that may reach the model as an issue's expected type (or Valibot's schema `type`). */
const MODEL_FACING_TYPE_NAMES = /* @__PURE__ */ new Set([
"string",
"number",
"bigint",
"boolean",
"symbol",
"undefined",
"null",
"object",
"array",
"tuple",
"record",
"map",
"set",
"date",
"function",
"integer",
"int",
"nan",
"literal",
"enum",
"picklist",
"union",
"variant",
"never",
"nonoptional",
"nonnullable",
"nonnullish"
]);
/**
* Generic, value-free description of one issue for the model: the schema library's issue kind
* (Zod's `code`, Valibot's `type`, ArkType's `code`) and the expected type, each only when it is
* on a fixed list, else `invalid`. Issue messages are left out: custom refinements can quote
* anything, including values an input transform resolved, and built-in messages can quote the
* rejected value.
*/
function describeIssueForModel(issue) {
const listed = (key, allowed) => {
const value = Reflect.get(issue, key);
return typeof value === "string" && allowed.has(value) ? value : void 0;
};
const kind = listed("code", MODEL_FACING_ISSUE_KINDS) ?? listed("type", MODEL_FACING_ISSUE_KINDS) ?? listed("type", MODEL_FACING_TYPE_NAMES) ?? "invalid";
const expected = listed("expected", MODEL_FACING_TYPE_NAMES);
return expected ? `${kind} (expected ${expected})` : kind;
}
/**
* Model-facing form of a validation error, used when a tool's `toModelOutput` is skipped for it:
* each failing field path, sanitized like {@link getValidationIssuePaths}, with a generic issue
* kind. It never carries issue messages, received values or excerpts of the validated data.
*/
function modelFacingError(params) {
const sanitizePath = createIssuePathSanitizer(params.schema, params.io);
const issues = params.issues.map((issue) => ({
path: sanitizePath((issue.path ?? []).map((segment) => getPathKey(segment))),
message: describeIssueForModel(issue)
}));
const lines = issues.map((issue) => `- ${issue.path.join(".") || "root"}: ${issue.message}`).join("\n");
return {
error: true,
message: `${params.heading}\n${lines}`,
validationErrors: buildFormattedErrors(issues)
};
}
/**
* Returns a function that keeps only the path segments `schema` declares: property names and array
* indexes. Any other segment (a record key, or anything under a schema that can't be resolved)
* came from the validated data and becomes `*`.
*/
function createIssuePathSanitizer(schema, io) {
let root;
try {
root = schema ? standardSchemaToJSONSchema(toStandardSchema(schema), { io }) : void 0;
} catch {
root = void 0;
}
const resolve = (node, seen = /* @__PURE__ */ new Set()) => {
if (!node || typeof node !== "object") return [];
if (node.$ref?.startsWith("#/") && typeof root === "object" && !seen.has(node.$ref)) {
seen.add(node.$ref);
const target = node.$ref.slice(2).split("/").reduce((at, key) => at?.[key], root);
return resolve(target, seen);
}
return [node, ...[
...node.anyOf ?? [],
...node.oneOf ?? [],
...node.allOf ?? []
].flatMap((branch) => resolve(branch, seen))];
};
const child = (nodes, key) => {
const declared = nodes.filter((node) => node.properties && Object.hasOwn(node.properties, key));
if (declared.length > 0) return {
segment: key,
nodes: declared.flatMap((node) => resolve(node.properties[key]))
};
if (/^\d+$/.test(key)) {
const items = nodes.flatMap((node) => Array.isArray(node.items) ? resolve(node.items[Number(key)]) : resolve(node.items));
if (items.length > 0 || nodes.some((node) => node.type === "array")) return {
segment: key,
nodes: items
};
}
return {
segment: "*",
nodes: nodes.flatMap((node) => [...resolve(node.additionalProperties), ...Object.values(node.patternProperties ?? {}).flatMap((pattern) => resolve(pattern))])
};
};
const rootNodes = resolve(root);
return (path) => {
let nodes = rootNodes;
return path.map((key) => {
const next = child(nodes, key);
nodes = next.nodes;
return next.segment;
});
};
}
/**
* Lists the dotted paths that failed validation (`root` for top-level issues), for log lines.
* `message` echoes the submitted values back to the caller, so logs carry these paths instead.
* Only property names declared by `schema` and array indexes are kept; any other segment (a record
* key, or anything under a schema that can't be resolved) came from the submitted data and is logged as `*`.
*/
function getValidationIssuePaths(error, schema, io = "input") {
const sanitizePath = createIssuePathSanitizer(schema, io);
const paths = [];
const walk = (node, path) => {
if (node.errors.length > 0) paths.push(sanitizePath(path).join(".") || "root");
for (const [key, field] of Object.entries(node.fields ?? {})) walk(field, [...path, key]);
};
walk(error.validationErrors, []);
return [...new Set(paths)];
}
/**
* Extracts a string key from a path segment (handles both PropertyKey and PathSegment objects).
*/
function getPathKey(segment) {
if (typeof segment === "object" && segment !== null && "key" in segment) return String(segment.key);
return String(segment);
}
/**
* Builds a path-aware Error from Standard Schema issues.
* The `errors` array lets consumers (e.g. the @mastra/mcp 1.x tools/call handler) report one line per field.
*/
function createStandardSchemaIssuesError(issues) {
const errors = issues.map((issue) => ({
path: (issue.path ?? []).map((segment) => getPathKey(segment)),
message: issue.message
}));
const message = errors.map((e) => `- ${e.path.join(".") || "root"}: ${e.message}`).join("\n");
return Object.assign(new Error(message), { errors });
}
/**
* Creates an empty FormattedValidationErrors object.
*/
function createEmptyErrors() {
return {
errors: [],
fields: {}
};
}
/**
* Builds a formatted errors object from standard schema validation issues.
*
* @param issues Array of validation issues from standard schema validation
* @returns Formatted errors object with nested structure based on paths
*/
function buildFormattedErrors(issues) {
const result = createEmptyErrors();
for (const issue of issues) if (!issue.path || issue.path.length === 0) result.errors.push(issue.message);
else {
let current = result;
for (let i = 0; i < issue.path.length; i++) {
const key = getPathKey(issue.path[i]);
if (i === issue.path.length - 1) {
if (!current.fields[key]) current.fields[key] = createEmptyErrors();
current.fields[key].errors.push(issue.message);
} else {
if (!current.fields[key]) current.fields[key] = createEmptyErrors();
current = current.fields[key];
}
}
}
return result;
}
/**
* Safely truncates data for error messages to avoid exposing sensitive information.
* @param data The data to truncate
* @param maxLength Maximum length of the truncated string (default: 200)
* @returns Truncated string representation
*/
function truncateForLogging(data, maxLength = 200) {
try {
const stringified = JSON.stringify(data, null, 2);
if (stringified.length <= maxLength) return stringified;
return stringified.slice(0, maxLength) + "... (truncated)";
} catch {
return "[Unable to serialize data]";
}
}
/**
* Validates raw suspend data against a schema.
*
* @param schema The schema to validate against
* @param suspendData The raw suspend data to validate
* @param toolId Optional tool ID for better error messages
* @returns The validated data or a validation error
*/
function validateToolSuspendData(schema, suspendData, toolId) {
if (!schema || !("~standard" in schema)) return { data: suspendData };
const validation = safeValidate(schema, suspendData);
if ("value" in validation) return { data: validation.value };
const errorMessages = validation.issues.map((e) => `- ${e.path?.map((p) => getPathKey(p)).join(".") || "root"}: ${e.message}`).join("\n");
return { error: markModelFacing({
error: true,
message: `Tool suspension data validation failed${toolId ? ` for ${toolId}` : ""}. Please fix the following errors and try again:\n${errorMessages}\n\nProvided arguments: ${truncateForLogging(suspendData)}`,
validationErrors: buildFormattedErrors(validation.issues)
}, modelFacingError({
issues: validation.issues,
schema,
io: "input",
heading: `Tool suspension data validation failed${toolId ? ` for ${toolId}` : ""}. The tool suspended with data that does not match its suspend schema:`
})) };
}
/**
* Normalizes undefined/null input to an appropriate default value based on schema type.
* This handles LLMs (Claude Sonnet 4.5, Gemini 2.4, etc.) that send undefined/null
* instead of {} or [] when all parameters are optional.
*
* @param schema The Zod schema to check
* @param input The input to normalize
* @returns The normalized input (original value, {}, or [])
*/
function normalizeNullishInput(schema, input) {
if (typeof input !== "undefined" && input !== null) return input;
const jsonSchema = standardSchemaToJSONSchema(schema, { io: "input" });
if (jsonSchema.type === "array") return [];
if (jsonSchema.type === "object") return {};
return input;
}
/**
* Checks if a value is a plain object (created by {} or new Object()).
* This excludes class instances, built-in objects like Date/Map/URL, etc.
*
* @param value The value to check
* @returns true if the value is a plain object
*/
function isPlainObject(value) {
if (value === null || typeof value !== "object") return false;
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
/**
* Recursively converts undefined values to null in an object.
* This is needed for OpenAI compat layers which convert .optional() to .nullable()
* for strict mode compliance. When fields are omitted (undefined), we convert them
* to null so the schema validation passes, and the transform then converts null back
* to undefined. (GitHub #11457)
*
* Only recurses into plain objects to preserve class instances and built-in objects
* like Date, Map, URL, etc. (GitHub #11502)
*
* @param input The input to process
* @returns The processed input with undefined values converted to null
*/
function convertUndefinedToNull(input) {
if (input === void 0) return null;
if (input === null || typeof input !== "object") return input;
if (Array.isArray(input)) return input.map(convertUndefinedToNull);
if (!isPlainObject(input)) return input;
const result = {};
for (const [key, value] of Object.entries(input)) result[key] = convertUndefinedToNull(value);
return result;
}
/**
* Recursively strips null/undefined values from object properties.
* This handles LLMs (e.g. Gemini) that send null for .optional() fields,
* where Zod expects undefined, not null. By stripping nullish values,
* we let Zod treat them as "not provided" which matches .optional() semantics.
* (GitHub #12362)
*
* @param input The input to process
* @returns The processed input with null/undefined values stripped from objects
*/
function stripNullishValues(input) {
if (input === null || input === void 0) return;
if (typeof input !== "object") return input;
if (Array.isArray(input)) return input.map((item) => item === null ? null : stripNullishValues(item));
if (!isPlainObject(input)) return input;
const result = {};
for (const [key, value] of Object.entries(input)) {
if (value === null || value === void 0) continue;
result[key] = stripNullishValues(value);
}
return result;
}
/**
* Strip null/undefined values only at specific paths that caused validation errors.
* Preserves null for .nullable() fields that are valid.
*/
function stripNullishValuesAtPaths(input, paths, currentPath = "") {
if (input === null || input === void 0) return paths.has(currentPath) ? void 0 : input;
if (typeof input !== "object") return input;
if (Array.isArray(input)) return input.map((item, i) => stripNullishValuesAtPaths(item, paths, currentPath ? `${currentPath}.${i}` : String(i)));
if (!isPlainObject(input)) return input;
const result = {};
for (const [key, value] of Object.entries(input)) {
const fieldPath = currentPath ? `${currentPath}.${key}` : key;
if ((value === null || value === void 0) && paths.has(fieldPath)) continue;
result[key] = stripNullishValuesAtPaths(value, paths, fieldPath);
}
return result;
}
/**
* Gets the value at a path in a nested object, using the same path segment format
* as Standard Schema validation issues.
*
* @param obj The object to traverse
* @param pathSegments Array of path segments from a validation issue
* @returns The value at the path, or a sentinel symbol if the path doesn't exist
*/
const PATH_NOT_FOUND = Symbol("PATH_NOT_FOUND");
function getValueAtPath(obj, pathSegments) {
let current = obj;
for (const segment of pathSegments) {
if (current === null || current === void 0 || typeof current !== "object") return PATH_NOT_FOUND;
const key = typeof segment === "object" && segment !== null && "key" in segment ? String(segment.key) : String(segment);
current = current[key];
}
return current;
}
/**
* Coerces stringified JSON values in object properties when the schema expects
* an array or object but the LLM returned a JSON string.
*
* Some LLMs (e.g., GLM4.7) return stringified JSON for array/object parameters:
* { "args": "[\"parse_excel.py\"]" }
* instead of:
* { "args": ["parse_excel.py"] }
*
* This function walks the top-level properties of a plain object and attempts
* to JSON.parse string values when the schema expects a non-string type.
* (GitHub #12757)
*
* @param schema The Zod schema to check field types against
* @param input The input to process
* @returns The input with stringified JSON values coerced, or the original input
*/
function coerceStringifiedJsonValues(schema, input) {
if (!isPlainObject(input)) return input;
const unwrapped = unwrapZodType(schema);
if (!isZodObject(unwrapped)) return input;
const shape = unwrapped.shape;
if (!shape || typeof shape !== "object") return input;
let changed = false;
const result = { ...input };
for (const [key, value] of Object.entries(input)) {
if (typeof value !== "string") continue;
const fieldSchema = shape[key];
if (!fieldSchema) continue;
const baseFieldSchema = unwrapZodType(fieldSchema);
if (getZodTypeName(baseFieldSchema) === "ZodString") continue;
const trimmed = value.trim();
if (isZodArray(baseFieldSchema) && trimmed.startsWith("[") || isZodObject(baseFieldSchema) && trimmed.startsWith("{")) try {
const parsed = JSON.parse(value);
if (isZodArray(baseFieldSchema) && Array.isArray(parsed) || isZodObject(baseFieldSchema) && isPlainObject(parsed)) {
result[key] = parsed;
changed = true;
}
} catch {}
}
return changed ? result : input;
}
/**
* Validates raw input data against a schema.
*
* @param schema The schema to validate against (or undefined to skip validation)
* @param input The raw input data to validate
* @param toolId Optional tool ID for better error messages
* @returns The validated data or a validation error
*/
function validateToolInput(schema, input, toolId) {
if (!schema || !("~standard" in schema)) return { data: input };
schema = toStandardSchema(schema);
let normalizedInput = normalizeNullishInput(schema, input);
normalizedInput = convertUndefinedToNull(normalizedInput);
const validation = safeValidate(schema, normalizedInput);
if ("value" in validation) return { data: validation.value };
let currentInput = normalizedInput;
let currentIssues = validation.issues;
const coercedInput = coerceStringifiedJsonValues(schema, normalizedInput);
if (coercedInput !== normalizedInput) {
const coercedValidation = safeValidate(schema, coercedInput);
if ("value" in coercedValidation) return { data: coercedValidation.value };
currentInput = coercedInput;
currentIssues = coercedValidation.issues;
}
const failingNullPaths = new Set(currentIssues.filter((issue) => {
if (!issue.path || issue.path.length === 0) return false;
const value = getValueAtPath(currentInput, issue.path);
return value === null || value === void 0;
}).map((issue) => issue.path?.map((p) => typeof p === "object" && "key" in p ? String(p.key) : String(p)).join(".")).filter((p) => !!p));
const strippedInput = failingNullPaths.size > 0 ? stripNullishValuesAtPaths(currentInput, failingNullPaths) : stripNullishValues(coercedInput !== normalizedInput ? coercedInput : input);
const normalizedStripped = normalizeNullishInput(schema, strippedInput);
const retryValidation = safeValidate(schema, normalizedStripped);
if ("value" in retryValidation) return { data: retryValidation.value };
if (failingNullPaths.size > 0) currentInput = normalizedStripped;
let aliasIssues;
const promptJsonSchema = standardSchemaToJSONSchema(schema, { io: "input" });
if (promptJsonSchema.type === "object" && promptJsonSchema.properties != null && "prompt" in promptJsonSchema.properties && currentInput != null && typeof currentInput === "object" && !Array.isArray(currentInput)) {
const obj = currentInput;
if (obj.prompt == null) {
const alias = [
obj.query,
obj.message,
obj.input
].find((v) => typeof v === "string");
if (alias !== void 0) {
const coercedPromptInput = {
...obj,
prompt: alias
};
const coercedPromptValidation = safeValidate(schema, coercedPromptInput);
if ("value" in coercedPromptValidation) return { data: coercedPromptValidation.value };
aliasIssues = coercedPromptValidation.issues;
}
}
}
const finalIssues = aliasIssues ?? (failingNullPaths.size > 0 ? retryValidation.issues : currentIssues);
const errorMessages = finalIssues.map((e) => `- ${e.path?.map((p) => getPathKey(p)).join(".") || "root"}: ${e.message}`).join("\n");
const heading = `Tool input validation failed${toolId ? ` for ${toolId}` : ""}. Please fix the following errors and try again:`;
return { error: markModelFacing({
error: true,
message: `${heading}\n${errorMessages}\n\nProvided arguments: ${truncateForLogging(input)}`,
validationErrors: buildFormattedErrors(finalIssues)
}, modelFacingError({
issues: finalIssues,
schema,
io: "input",
heading
})) };
}
/**
* Validates tool output data against a schema.
*
* @param schema The schema to validate against
* @param output The output data to validate
* @param toolId Optional tool ID for better error messages
* @returns The validated data or a validation error
*/
function validateToolOutput(schema, output, toolId, suspendCalled) {
if (!schema || !("~standard" in schema) || suspendCalled) return { data: output };
const validation = safeValidate(schema, output);
if ("value" in validation) return { data: validation.value };
const errorMessages = validation.issues.map((e) => `- ${e.path?.map((p) => getPathKey(p)).join(".") || "root"}: ${e.message}`).join("\n");
return { error: markModelFacing({
error: true,
message: `Tool output validation failed${toolId ? ` for ${toolId}` : ""}. The tool returned invalid output:\n${errorMessages}\n\nReturned output: ${truncateForLogging(redactSensitiveKeys(output))}`,
validationErrors: buildFormattedErrors(validation.issues)
}, modelFacingError({
issues: validation.issues,
schema,
io: "output",
heading: `Tool output validation failed${toolId ? ` for ${toolId}` : ""}. The tool returned output that does not match its output schema:`
})) };
}
/**
* Keys that are considered sensitive and should be redacted in error messages.
*/
const SENSITIVE_KEYS = [
"password",
"secret",
"token",
"apiKey",
"api_key",
"auth",
"credential"
];
/**
* Redacts sensitive keys from an object for safe logging.
* @param obj The object to redact
* @returns A new object with sensitive values replaced with '[REDACTED]'
*/
function redactSensitiveKeys(obj, ancestors = /* @__PURE__ */ new WeakSet()) {
if (obj === null || typeof obj !== "object" || typeof obj.toJSON === "function") return obj;
if (ancestors.has(obj)) return obj;
ancestors.add(obj);
let result;
if (Array.isArray(obj)) result = obj.map((item) => redactSensitiveKeys(item, ancestors));
else {
const redacted = {};
for (const [key, value] of Object.entries(obj)) if (SENSITIVE_KEYS.some((sensitive) => key.toLowerCase().includes(sensitive.toLowerCase()))) redacted[key] = "[REDACTED]";
else redacted[key] = redactSensitiveKeys(value, ancestors);
result = redacted;
}
ancestors.delete(obj);
return result;
}
/**
* Validates request context data against a schema.
* This is used to validate the request context before tool execution.
*
* @param schema The schema to validate against (PublicSchema which accepts Zod, JSONSchema, etc.)
* @param requestContext The request context to validate
* @param identifier Optional identifier (tool/step ID) for better error messages
* @returns The validated data or a validation error
*/
function validateRequestContext(schema, requestContext, identifier) {
if (!schema) return { data: getRequestContextInputValues(requestContext) };
const contextValues = getRequestContextInputValues(requestContext);
const validation = safeValidate(toStandardSchema(schema), contextValues);
if ("value" in validation) return { data: validation.value };
const errorMessages = validation.issues.map((e) => `- ${e.path?.map((p) => getPathKey(p)).join(".") || "root"}: ${e.message}`).join("\n");
const redactedContext = redactSensitiveKeys(contextValues);
return {
data: contextValues,
error: markModelFacing({
error: true,
message: `Request context validation failed${identifier ? ` for ${identifier}` : ""}. Please fix the following errors and try again:\n${errorMessages}\n\nProvided request context: ${truncateForLogging(redactedContext)}`,
validationErrors: buildFormattedErrors(validation.issues)
}, modelFacingError({
issues: validation.issues,
schema,
io: "input",
heading: `Request context validation failed${identifier ? ` for ${identifier}` : ""}. The request context is missing values or has invalid ones:`
}))
};
}
// src/tools/tool.ts
/**
* Marker to identify Mastra tools even when `instanceof` fails.
* This can happen in environments like Vite SSR where the same module
* may be loaded multiple times, creating different class instances.
* Uses Symbol.for() so the same symbol is shared across module copies.
* Follows the naming convention: <org>.<product>.<category>.<className>
*/
const MASTRA_TOOL_MARKER = Symbol.for("mastra.core.tool.Tool");
function getRequestContextInputValidator(schema) {
const standardSchema = toStandardSchema(schema);
return (values) => {
try {
const result = standardSchema["~standard"].validate(values);
if (result instanceof Promise) throw new Error("Your schema is async, which is not supported. Please use a sync schema.");
return !("issues" in result) || !result.issues?.length;
} catch {
return false;
}
};
}
function getRequestContextEncoder(schema) {
if (!schema || typeof schema !== "object" && typeof schema !== "function") return;
const encodableSchema = schema;
if (encodableSchema["~standard"]?.vendor !== "zod" || typeof encodableSchema.safeEncode !== "function") return;
return (values) => {
try {
const result = encodableSchema.safeEncode(values);
if (result.success && result.data && typeof result.data === "object" && !Array.isArray(result.data)) return result.data;
} catch {}
};
}
/**
* Exposes schema-transformed values for one tool execution while keeping
* explicit mutations connected to the shared request context.
*/
var TransformedRequestContext = class extends RequestContext {
#source;
#acceptsInput;
#encode;
constructor(source, transformedValues, acceptsInput, encode) {
super(Object.entries({
...source.all,
...transformedValues
}));
this.#source = source;
this.#acceptsInput = acceptsInput;
this.#encode = encode;
Object.defineProperty(this, REQUEST_CONTEXT_INPUT_SOURCE, { value: source });
}
#getSourceValue(key, value) {
const nextSourceValues = {
...this.#source.all,
[key]: value
};
if (this.#acceptsInput(nextSourceValues)) return value;
const encodedValues = this.#encode?.({
...this.all,
[key]: value
});
if (encodedValues && Object.prototype.hasOwnProperty.call(encodedValues, key)) return encodedValues[key];
throw new Error(`Unable to persist request context key "${key}": the value is not valid schema input and cannot be encoded from the schema output.`);
}
set(key, value) {
const sourceValue = this.#getSourceValue(key, value);
this.#source.setRaw(key, sourceValue);
super.set(key, value);
}
setRaw(key, value) {
const sourceValue = this.#getSourceValue(key, value);
this.#source.setRaw(key, sourceValue);
super.setRaw(key, value);
}
delete(key) {
this.#source.deleteRaw(key);
return super.delete(key);
}
deleteRaw(key) {
this.#source.deleteRaw(key);
return super.deleteRaw(key);
}
clear() {
super.clear();
this.#source.clear();
}
};
/** Own property descriptors of `target`, with accessors bound to it so they still read it when copied. */
function bindAccessors(target) {
const descriptors = Object.getOwnPropertyDescriptors(target);
for (const descriptor of Object.values(descriptors)) {
if (descriptor.get) descriptor.get = descriptor.get.bind(target);
if (descriptor.set) descriptor.set = descriptor.set.bind(target);
}
return descriptors;
}
/**
* A type-safe tool that agents and workflows can call to perform specific actions.
*
* @template TSchemaIn - Input schema type
* @template TSchemaOut - Output schema type
* @template TSuspendSchema - Suspend operation schema type
* @template TResumeSchema - Resume operation schema type
* @template TContext - Execution context type
*
* @example Basic tool with validation
* ```typescript
* const weatherTool = createTool({
* id: 'get-weather',
* description: 'Get weather for a location',
* inputSchema: z.object({
* location: z.string(),
* units: z.enum(['celsius', 'fahrenheit']).optional()
* }),
* execute: async (inputData) => {
* return await fetchWeather(inputData.location, inputData.units);
* }
* });
* ```
*
* @example Tool requiring approval
* ```typescript
* const deleteFileTool = createTool({
* id: 'delete-file',
* description: 'Delete a file',
* requireApproval: true,
* inputSchema: z.object({ filepath: z.string() }),
* execute: async (inputData) => {
* await fs.unlink(inputData.filepath);
* return { deleted: true };
* }
* });
* ```
*
* @example Tool with Mastra integration
* ```typescript
* const saveTool = createTool({
* id: 'save-data',
* description: 'Save data to storage',
* inputSchema: z.object({ key: z.string(), value: z.any() }),
* execute: async (inputData, context) => {
* const storage = context?.mastra?.getStorage();
* await storage?.set(inputData.key, inputData.value);
* return { saved: true };
* }
* });
* ```
*/
var Tool = class {
/** Unique identifier for the tool */
id;
/** Display name for UIs and MCP clients. Never sent to the model. */
title;
/** Description of what the tool does */
description;
/** Schema for validating input parameters */
inputSchema;
/** Schema for validating output structure */
outputSchema;
/** Schema for suspend operation data */
suspendSchema;
/** Schema for resume operation data */
resumeSchema;
/**
* Schema for validating request context values.
* When provided, the request context will be validated against this schema before tool execution.
*/
requestContextSchema;
/**
* Tool execution function
* @param inputData - The raw, validated input data
* @param context - Optional execution context with metadata. `observe` may be omitted;
* the runtime provides one (a no-op when no tracing span is active). When `context` is
* omitted (for example when calling a tool directly from a test or script), the tool
* receives an empty `requestContext` and the default `observe`, but no `mastra`, writer,
* memory, `threadId`, `resourceId`, or `runId`. Pass a context if the tool relies on any
* of those.
* @returns Promise resolving to tool output or a ValidationError if input validation fails
*/
execute;
/** Whether this tool only displays its call and receives a server acknowledgement. */
renderOnly;
/** Parent Mastra instance for accessing shared resources */
mastra;
/**
* Whether the tool requires explicit user approval before execution.
* Accepts a boolean for static behavior, or a function evaluated per-call
* for conditional approval.
* @example
* ```typescript
* // Static
* requireApproval: true
*
* // Conditional — only require approval for non-dry-run calls
* requireApproval: async ({ isDryRun }) => !isDryRun
* ```
*/
requireApproval;
/**
* Runtime-resolved per-tool approval predicate, evaluated per call.
*
* This is set automatically when a tool's `requireApproval` is a function, or by the
* MCP client when wrapping a server-level `requireToolApproval` function — not something
* you normally set yourself (prefer the `requireApproval` option). When present it is the
* authoritative per-tool approval decision and is always evaluated by the agent runtime.
*/
needsApprovalFn;
/**
* Runs before the approval gate for calls that require approval and can reject the call
* with `{ proceed: false, output }`, returning `output` to the model without suspending
* or executing.
* @example
* ```typescript
* beforeApproval: async ({ orderId }) => {
* if (!(await orderExists(orderId))) {
* return { proceed: false, output: { error: `Order ${orderId} not found` } };
* }
* }
* ```
*/
beforeApproval;
/**
* Enables strict tool input generation for providers that support it.
*/
strict;
/**
* How a result that fails `outputSchema` validation is handled: replaced with a
* validation error (`'strict'`, the default) or logged and returned as-is (`'warn'`).
*/
outputValidation;
/**
* Provider-specific options passed to the model when this tool is used.
* Keys are provider names (e.g., 'anthropic', 'openai'), values are provider-specific configs.
* @example
* ```typescript
* providerOptions: {
* anthropic: {
* cacheControl: { type: 'ephemeral' }
* }
* }
* ```
*/
providerOptions;
/**
* Optional function to transform the tool's raw output before sending it to the model.
* The raw result is still available for application logic; only the model sees the transformed version.
* Not called when input, request context or output validation fails: the model receives a validation error that names
* the failing fields and the kind of each issue, without issue messages or the arguments, output or request context.
* With `outputValidation: 'warn'`, a failed output check keeps the real result, so this still runs on it.
*/
toModelOutput;
/**
* Optional target-aware transform for display and transcript payloads.
*/
transform;
/**
* Optional MCP-specific properties including annotations and metadata.
* Only relevant when the tool is being used in an MCP context.
* @example
* ```typescript
* mcp: {
* annotations: {
* title: 'Weather Lookup',
* readOnlyHint: true,
* destructiveHint: false
* },
* _meta: {
* version: '1.0.0',
* author: 'team@example.com'
* }
* }
* ```
*/
mcp;
onInputStart;
onInputDelta;
onInputAvailable;
onOutput;
/**
* Examples of valid tool inputs passed through to the AI SDK.
*/
inputExamples;
/**
* Metadata identifying this tool as originating from an MCP server.
* Set automatically by the MCP client when creating tools.
*/
mcpMetadata;
/**
* Background task configuration for this tool.
* When enabled, the tool can be executed in the background while the agent conversation continues.
*/
background;
/**
* Creates a new Tool instance with input validation wrapper.
*
* @param opts - Tool configuration and execute function
* @example
* ```typescript
* const tool = new Tool({
* id: 'my-tool',
* description: 'Does something useful',
* inputSchema: z.object({ name: z.string() }),
* execute: async (inputData) => ({ greeting: `Hello ${inputData.name}` })
* });
* ```
*/
constructor(opts) {
this[MASTRA_TOOL_MARKER] = true;
this.id = opts.id;
this.title = opts.title;
this.description = opts.description;
this.inputSchema = opts.inputSchema ? toStandardSchema(opts.inputSchema) : void 0;
this.outputSchema = opts.outputSchema ? toStandardSchema(opts.outputSchema) : void 0;
this.suspendSchema = opts.suspendSchema ? toStandardSchema(opts.suspendSchema) : void 0;
this.resumeSchema = opts.resumeSchema ? toStandardSchema(opts.resumeSchema) : void 0;
this.requestContextSchema = opts.requestContextSchema;
this.renderOnly = opts.renderOnly;
this.mastra = opts.mastra;
this.requireApproval = opts.requireApproval || false;
this.beforeApproval = opts.beforeApproval;
this.strict = opts.strict;
this.outputValidation = opts.outputValidation;
this.providerOptions = opts.providerOptions;
this.toModelOutput = opts.toModelOutput;
this.transform = opts.transform;
this.inputExamples = opts.inputExamples;
this.mcp = opts.mcp;
this.mcpMetadata = opts.mcpMetadata;
this.background = opts.background;
this.onInputStart = opts.onInputStart;
this.onInputDelta = opts.onInputDelta;
this.onInputAvailable = opts.onInputAvailable;
this.onOutput = opts.onOutput;
if (opts.renderOnly && opts.execute) throw new Error("A render-only tool cannot also define execute");
const originalExecute = opts.renderOnly ? async () => ({ acknowledged: true }) : opts.execute;
if (originalExecute) this.execute = async (inputData, context) => {
const isResuming = (context?.resumeData ?? context?.agent?.resumeData ?? context?.workflow?.resumeData) != null;
const wasBuilderValidated = consumeBuilderValidatedInput(context);
const skipInputValidation = isResuming || wasBuilderValidated;
let data = inputData;
if (!skipInputValidation) {
const validationResult = validateToolInput(this.inputSchema, inputData, this.id);
if (validationResult.error) return validationResult.error;
data = validationResult.data;
}
const sourceRequestContext = getRequestContextInputSource(context?.requestContext);
const { data: validatedRequestContext, error: requestContextError } = validateRequestContext(this.requestContextSchema, sourceRequestContext, this.id);
if (requestContextError) return requestContextError;
const executionRequestContext = this.requestContextSchema ? new TransformedRequestContext(sourceRequestContext ?? new RequestContext(), validatedRequestContext, getRequestContextInputValidator(this.requestContextSchema), getRequestContextEncoder(this.requestContextSchema)) : context?.requestContext;
let suspendData = null;
const baseContext = context ? {
...context,
...context.suspend ? { suspend: (args, suspendOptions) => {
suspendData = args;
return context.suspend?.(args, suspendOptions);
} } : {}
} : {};
let organizedContext = baseContext;
if (!context) organizedContext = {
requestContext: executionRequestContext ?? new RequestContext(),
mastra: void 0
};
else {
const isAgentExecution = baseContext.toolCallId && baseContext.messages;
const isWorkflowExecution = !isAgentExecution && (baseContext.workflow || baseContext.workflowId);
if (isAgentExecution && !baseContext.agent) {
const { agentId, toolCallId, messages, suspend, resumeData, suspendPayload, threadId, resourceId, writableStream, isBackgroundTask, background, ...rest } = baseContext;
organizedContext = {
...rest,
background,
agent: {
agentId: agentId || "",
toolCallId,
messages,
suspend,
resumeData,
suspendPayload,
threadId,
resourceId,
writableStream,
...isBackgroundTask ? { isBackgroundTask: true } : {}
},
requestContext: executionRequestContext ?? new RequestContext()
};
} else if (isWorkflowExecution && !baseContext.workflow) {
const { workflowId, runId, state, setState, updateState, suspend, resumeData, suspendPayload, ...rest } = baseContext;
organizedContext = {
...rest,
workflow: {
workflowId,
runId,
state,
setState,
updateState,
suspend,
resumeData,
suspendPayload
},
requestContext: executionRequestContext ?? new RequestContext()
};
} else organizedContext = {
...baseContext,
agent: baseContext.agent ? {
...baseContext.agent,
agentId: baseContext.agent.agentId ?? "",
suspend: (args, suspendOptions) => {
suspendData = args;
return baseContext.agent?.suspend?.(args, suspendOptions);
}
} : baseContext.agent,
workflow: baseContext.workflow ? Object.defineProperties({}, {
...bindAccessors(baseContext.workflow),
suspend: {
enumerable: true,
configurable: true,
writable: true,
value: (args, suspendOptions) => {
suspendData = args;
return baseContext.workflow?.suspend?.(args, suspendOptions);
}
}
}) : baseContext.workflow,
requestContext: executionRequestContext ?? new RequestContext()
};
}
if (!organizedContext.observe) organizedContext = {
...organizedContext,
observe: createToolObserve(organizedContext.tracingContext?.currentSpan ?? organizedContext.tracing?.currentSpan ?? resolveCurrentSpan())
};
const resumeData = organizedContext.agent?.resumeData ?? organizedContext.workflow?.resumeData ?? organizedContext?.resumeData;
if (resumeData != null) {
const resumeValidation = validateToolInput(this.resumeSchema, resumeData, this.id);
if (resumeValidation.error) return resumeValidation.error;
}
const output = await originalExecute(data, organizedContext);
if (suspendData) {
const suspendValidation = validateToolSuspendData(this.suspendSchema, suspendData, this.id);
if (suspendValidation.error) return suspendValidation.error;
}
const skiptOutputValidation = !!(typeof output === "undefined" && suspendData);
const outputValidation = validateToolOutput(this.outputSchema, output, this.id, skiptOutputValidation);
if (outputValidation.error) {
(organizedContext.mastra?.getLogger?.() ?? this.mastra?.getLogger?.())?.warn("Tool output validation failed", {
toolId: this.id,
issuePaths: getValidationIssuePaths(outputValidation.error, this.outputSchema, "output")
});
if (this.outputValidation === "warn") return output;
return outputValidation.error;
}
return outputValidation.data;
};
}
};
/**
* Defines a tool with a description, input/output schemas, and an execution function.
*
* @example
* ```typescript
* import { createTool } from '@mastra/core/tools';
* import { z } from 'zod';
*
* const greet = createTool({
* id: 'greet',
* description: 'Greet someone by name.',
* inputSchema: z.object({ name: z.string() }),
* outputSchema: z.string(),
* execute: async ({ name }) => `Hello, ${name}!`,
* });
* ```
*
* @see For documentation bundled with your installed package, locate
* `@mastra/core/package.json` with your project's resolver or package-manager
* tooling, then read `dist/docs/SKILL.md` from that package root and follow its
* reference links. Use package-manager tools for virtual or archived packages.
*
* @see [Tool documentation](https://mastra.ai/reference/tools/create-tool)
* if packaged docs are unavailable.
*/
function createTool(opts) {
return new Tool(opts);
}
export { getRequestContextInputValues as _, getModelFacingValidationError as a, registerToolOutputValidationSchema as c, validateToolOutput as d, validateToolSuspendData as f, getRequestContextInputSource as g, markBuilderValidatedInput as h, createStandardSchemaIssuesError as i, resolveToolOutputValidationSchema as l, noopObserve as m, Tool as n, getValidationIssuePaths as o, createToolObserve as p, createTool as r, isValidationError as s, MASTRA_TOOL_MARKER as t, validateToolInput as u };
//# sourceMappingURL=tool-CXFwLwlu.js.map