Skip to main content

工具

🌐 Tools

工具执行签名已更新为使用独立的输入和上下文参数,并重新组织了上下文属性。

🌐 Tool execution signatures have been updated to use separate input and context parameters with reorganized context properties.

已更改
Direct link to 已更改

🌐 Changed

createTool 执行签名到 (inputData, context) 格式
Direct link to createtool-execute-signature-to-inputdata-context-format

🌐 createTool execute signature to (inputData, context) format

所有 createTool 执行函数现在使用新的签名,采用单独的 inputDatacontext 参数,而不是单个解构对象。此更改可以更清晰地分隔工具输入和执行上下文。

🌐 All createTool execute functions now use a new signature with separate inputData and context parameters instead of a single destructured object. This change provides clearer separation between tool inputs and execution context.

注意: 此更改仅适用于 createTool。如果你在工作流中使用 createStep,签名仍然是 async (inputData, context),无需更改。

要进行迁移,请更新 createTool 签名,使其使用 inputData 作为第一个参数(类型为 inputSchema),context 作为第二个参数。

🌐 To migrate, update createTool signatures to use inputData as the first parameter (typed from inputSchema) and context as the second parameter.

  createTool({
id: 'weather-tool',
- execute: async ({ context, requestContext, mastra }) => {
- const location = context.location;
- const userTier = requestContext.get('userTier');
- return getWeather(location, userTier);
- },
+ execute: async (inputData, context) => {
+ const location = inputData.location;
+ const userTier = context?.requestContext?.get('userTier');
+ return getWeather(location, userTier);
+ },
});

createTool 上下文属性组织
Direct link to createtool-context-properties-organization

🌐 createTool context properties organization

createTool 中的上下文属性现在已组织到命名空间中。特定于代理的属性位于 context.agent 下,特定于工作流的属性位于 context.workflow 下,特定于 MCP 的属性位于 context.mcp 下。这一更改提供了更好的组织结构和更清晰的 API 接口。

🌐 Context properties in createTool are now organized into namespaces. Agent-specific properties are under context.agent, workflow-specific properties are under context.workflow, and MCP-specific properties are under context.mcp. This change provides better organization and clearer API surface.

对于在代理内执行的工具,通过 context.agent 访问代理特定的属性。

🌐 For tools that are executed inside an agent, access agent-specific properties through context.agent.

  createTool({
id: 'suspendable-tool',
suspendSchema: z.object({ message: z.string() }),
resumeSchema: z.object({ approval: z.boolean() }),
- execute: async ({ context, suspend, resumeData }) => {
- if (!resumeData) {
- return await suspend({ message: 'Waiting for approval' });
- }
- if (resumeData.approval) {
- return { success: true };
- }
- },
+ execute: async (inputData, context) => {
+ if (!context?.agent?.resumeData) {
+ return await context?.agent?.suspend({
+ message: 'Waiting for approval',
+ });
+ }
+ if (context.agent.resumeData.approval) {
+ return { success: true };
+ }
+ },
});

对于在工作流中执行的工具,通过 context.workflow 访问工作流特定的属性。

🌐 For tools that are executed inside a workflow, access workflow-specific properties through context.workflow.

  createTool({
id: 'workflow-tool',
- execute: async ({ workflowId, runId, state, setState }) => {
- const currentState = state;
- setState({ step: 'completed' });
- return { result: 'done' };
- },
+ execute: async (inputData, context) => {
+ const currentState = context?.workflow?.state;
+ context?.workflow?.setState({ step: 'completed' });
+ return { result: 'done' };
+ },
});

当工具执行时,suspendPayload 会针对 suspendSchema 进行验证。如果 suspendPayload 与 suspendSchema 不匹配,会记录警告并将错误作为工具输出返回,但挂起操作会继续。 此外,当工具恢复时,resumeData 会针对 resumeSchema 进行验证。如果 resumeData 与 resumeSchema 不匹配,工具将返回 ValidationError,从而阻止工具恢复。

🌐 The suspendPayload gets validated against the suspendSchema when the tool is executed. If the suspendPayload doesn't match the suspendSchema, a warning is logged and the error is returned as tool output, but suspension continues. Also, when the tool is resumed, the resumeData gets validated against the resumeSchema. If the resumeData doesn't match the resumeSchema, the tool will return a ValidationError, preventing the tool resumption.

要跳过 suspendSchemaresumeSchema 验证,请在创建工具时不要定义 suspendSchemaresumeSchema

🌐 To skip the suspendSchema or resumeSchema validation, do not define suspendSchema or resumeSchema in the tool creation.

note

有关 MCP 特定工具上下文的更改,请参阅 MCP 迁移指南

RuntimeContextRequestContext
Direct link to runtimecontext-to-requestcontext

🌐 RuntimeContext to RequestContext

RuntimeContext 类在整个工具执行上下文中已重命名为 RequestContext。此更改提供了更清晰的命名,更好地描述了其作为请求特定数据的用途。

🌐 The RuntimeContext class has been renamed to RequestContext throughout the tool execution context. This change provides clearer naming that better describes its purpose as request-specific data.

要迁移,请在工具执行函数中将引用从 runtimeContext 更新为 requestContext

🌐 To migrate, update references from runtimeContext to requestContext in tool execution functions.

  createTool({
id: 'my-tool',
execute: async (inputData, context) => {
- const userTier = context?.runtimeContext?.get('userTier');
+ const userTier = context?.requestContext?.get('userTier');
return { result: userTier };
},
});
Codemod

你可以使用 Mastra 的 codemod CLI 来自动更新你的导入:

🌐 You can use Mastra's codemod CLI to update your imports automatically:

npx @mastra/codemod@latest v1/runtime-context .

这适用于所有工具执行,无论是直接调用还是通过代理和工作流调用。类型缩小确保你能够正确处理验证错误,并在访问输出属性时防止运行时错误。

🌐 This applies to all tool executions, whether called directly or through agents and workflows. The type narrowing ensures you handle validation errors appropriately and prevents runtime errors when accessing output properties.

使用 outputSchema 进行工具输出验证
Direct link to tool-output-validation-with-outputschema

🌐 Tool output validation with outputSchema

带有 outputSchema 的工具现在会在运行时验证其返回值。之前,outputSchema 仅用于类型推断——输出从未被验证过。

🌐 Tools with an outputSchema now validate their return values at runtime. Previously, outputSchema was only used for type inference - the output was never validated.

如果你的工具返回的数据与其 outputSchema 不匹配,它现在将返回 ValidationError,而不是无效数据。

🌐 If your tool returns data that doesn't match its outputSchema, it will now return a ValidationError instead of the invalid data.

要修复验证错误,请确保工具的输出与模式定义一致:

🌐 To fix validation errors, ensure the tool's output matches the schema definition:

  const getUserTool = createTool({
id: "get-user",
outputSchema: z.object({
id: z.string(),
name: z.string(),
email: z.string().email(),
}),
execute: async (inputData) => {
- return { id: "123", name: "John" }; // Missing email
+ return { id: "123", name: "John", email: "john@example.com" };
},
});

当验证失败时,该工具会返回 ValidationError

🌐 When validation fails, the tool returns a ValidationError:

+ // Before v1 - invalid output would silently pass through
await getUserTool.execute({});
- // { id: "123", name: "John" } - missing email
+ // {
+ // error: true,
+ // message: "Tool output validation failed for get-user. The tool returned invalid output:\n- email: Required\n\nReturned output: {...}",
+ // validationErrors: { ... }
+ // }

tool.execute 返回类型包括 ValidationError
Direct link to toolexecute-return-type-includes-validationerror

🌐 tool.execute return type includes ValidationError

tool.execute 的返回类型现在包括 ValidationError 以处理验证失败。在访问输出模式属性之前,必须先缩小结果类型,以满足 TypeScript 的类型检查。

🌐 The return type of tool.execute now includes ValidationError to handle validation failures. You must narrow the result type before accessing output schema properties to satisfy TypeScript's type checking.

在调用 tool.execute 时,先检查结果是否包含错误,然后再访问输出属性:

🌐 When calling tool.execute, check if the result contains an error before accessing output properties:

const result = await getUserTool.execute({});

// Type-safe check for validation errors
if ('error' in result && result.error) {
console.error('Validation failed:', result.message);
console.error('Details:', result.validationErrors);
return;
}

// TypeScript knows result is valid here
console.log(result.id, result.name, result.email);

或者,将 outputSchema 更新为与你的实际输出匹配,或者如果不需要验证,可以完全删除 outputSchema

🌐 Alternatively, update the outputSchema to match your actual output, or remove outputSchema entirely if you don't need validation.