createTool()
createTool() 函数用于定义 Mastra 代理可以执行的自定义工具。工具通过允许代理与外部系统交互、执行计算或访问特定数据,从而扩展代理的能力。
🌐 The createTool() function is used to define custom tools that your Mastra agents can execute. Tools extend an agent's capabilities by allowing it to interact with external systems, perform calculations, or access specific data.
使用示例Direct link to 使用示例
🌐 Usage example
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export const tool = createTool({
id: "test-tool",
description: "Reverse the input string",
inputSchema: z.object({
input: z.string(),
}),
outputSchema: z.object({
output: z.string(),
}),
execute: async (inputData) => {
const reversed = inputData.input.split("").reverse().join("");
return {
output: reversed,
};
},
});
带有 MCP 注释的示例Direct link to 带有 MCP 注释的示例
🌐 Example with MCP Annotations
在通过 MCP(模型上下文协议)公开工具时,你可以添加注释来描述工具的行为,并自定义客户端显示工具的方式。这些特定于 MCP 的属性被归类在 mcp 属性下:
🌐 When exposing tools via MCP (Model Context Protocol), you can add annotations to describe tool behavior and customize how clients display the tool. These MCP-specific properties are grouped under the mcp property:
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export const weatherTool = createTool({
id: "get-weather",
description: "Get current weather for a location",
inputSchema: z.object({
location: z.string().describe("City name or coordinates"),
}),
// MCP-specific properties
mcp: {
// Annotations for client behavior hints
annotations: {
title: "Weather Lookup", // Human-readable display name
readOnlyHint: true, // Tool doesn't modify environment
destructiveHint: false, // Tool doesn't perform destructive updates
idempotentHint: true, // Same args = same result
openWorldHint: true, // Interacts with external API
},
// Custom metadata for client-specific functionality
_meta: {
version: "1.0.0",
category: "weather",
},
},
execute: async (inputData) => {
const weather = await fetchWeather(inputData.location);
return { weather };
},
});
参数Direct link to 参数
🌐 Parameters
id:
description:
inputSchema?:
outputSchema?:
suspendSchema?:
resumeSchema?:
requireApproval?:
mcp?:
execute:
input:
context?:
onInputStart?:
onInputDelta?:
onInputAvailable?:
onOutput?:
返回Direct link to 返回
🌐 Returns
createTool() 函数返回一个 Tool 对象。
🌐 The createTool() function returns a Tool object.
Tool:
工具生命周期钩子Direct link to 工具生命周期钩子
🌐 Tool Lifecycle Hooks
工具支持生命周期钩子,允许你监控并响应工具执行的不同阶段。这些钩子对于日志记录、分析、验证以及流式传输期间的实时更新特别有用。
🌐 Tools support lifecycle hooks that allow you to monitor and react to different stages of tool execution. These hooks are particularly useful for logging, analytics, validation, and real-time updates during streaming.
可用钩子Direct link to 可用钩子
🌐 Available Hooks
onInputStartDirect link to onInputStart
在工具调用输入流开始时调用,在接收到任何输入数据之前。
🌐 Called when tool call input streaming begins, before any input data is received.
export const tool = createTool({
id: "example-tool",
description: "Example tool with hooks",
onInputStart: ({ toolCallId, messages, abortSignal }) => {
console.log(`Tool ${toolCallId} input streaming started`);
},
});
onInputDeltaDirect link to onInputDelta
在输入文本逐步流入时,为每个增量块调用。对显示实时进度或解析部分 JSON 很有用。
🌐 Called for each incremental chunk of input text as it streams in. Useful for showing real-time progress or parsing partial JSON.
export const tool = createTool({
id: "example-tool",
description: "Example tool with hooks",
onInputDelta: ({ inputTextDelta, toolCallId, messages, abortSignal }) => {
console.log(`Received input chunk: ${inputTextDelta}`);
},
});
onInputAvailableDirect link to onInputAvailable
在完整的工具输入可用且已根据 inputSchema 解析和验证后调用。
🌐 Called when the complete tool input is available and has been parsed and validated against the inputSchema.
export const tool = createTool({
id: "example-tool",
description: "Example tool with hooks",
inputSchema: z.object({
city: z.string(),
}),
onInputAvailable: ({ input, toolCallId, messages, abortSignal }) => {
console.log(`Tool received complete input:`, input);
// input is fully typed based on inputSchema
},
});
onOutputDirect link to onOutput
在工具成功执行并返回输出后调用。可用于记录结果、触发后续操作或进行分析。
🌐 Called after the tool has successfully executed and returned output. Useful for logging results, triggering follow-up actions, or analytics.
export const tool = createTool({
id: "example-tool",
description: "Example tool with hooks",
outputSchema: z.object({
result: z.string(),
}),
execute: async (input) => {
return { result: "Success" };
},
onOutput: ({ output, toolCallId, toolName, abortSignal }) => {
console.log(`${toolName} execution completed:`, output);
// output is fully typed based on outputSchema
},
});
钩子执行顺序Direct link to 钩子执行顺序
🌐 Hook Execution Order
对于典型的流式工具调用,钩子的调用顺序如下:
🌐 For a typical streaming tool call, the hooks are invoked in this order:
- onInputStart - 输入流开始
- onInputDelta - 当数据块到达时会被多次调用
- onInputAvailable - 已完成的输入已被解析和验证
- 工具的执行功能运行
- onOutput - 工具已成功完成
钩子参数Direct link to 钩子参数
🌐 Hook Parameters
所有钩子都会接收一个包含以下常用属性的参数对象:
🌐 All hooks receive a parameter object with these common properties:
toolCallId(字符串):此特定工具调用的唯一标识符abortSignal(AbortSignal):用于检测操作是否应被取消的信号
此外:
🌐 Additionally:
onInputStart、onInputDelta和onInputAvailable接收messages(数组):工具调用时的对话消息onInputDelta接收inputTextDelta(字符串):增量文本片段onInputAvailable接收input:经过验证的输入数据(按照inputSchema类型)onOutput接收output:工具的返回值(根据outputSchema类型)和toolName(字符串):工具的名称
错误处理Direct link to 错误处理
🌐 Error Handling
钩子错误会被自动捕获并记录,但不会阻止工具执行继续。如果钩子抛出错误,它会被记录到控制台,但不会导致工具调用失败。
🌐 Hook errors are caught and logged automatically, but do not prevent tool execution from continuing. If a hook throws an error, it will be logged to the console but will not fail the tool call.
MCP 工具注释Direct link to MCP 工具注释
🌐 MCP Tool Annotations
在通过模型上下文协议(MCP)暴露工具时,你可以提供描述工具行为的注释。这些注释可以帮助 MCP 客户端,如 OpenAI Apps SDK,理解如何展示和处理你的工具。
🌐 When exposing tools via the Model Context Protocol (MCP), you can provide annotations that describe tool behavior. These annotations help MCP clients like OpenAI Apps SDK understand how to present and handle your tools.
MCP 特定的属性被归类在 mcp 属性下,其中包括 annotations 和 _meta:
🌐 MCP-specific properties are grouped under the mcp property, which includes annotations and _meta:
mcp: {
annotations: { /* behavior hints */ },
_meta: { /* custom metadata */ },
}
工具注释属性Direct link to 工具注释属性
🌐 ToolAnnotations Properties
title?:
readOnlyHint?:
destructiveHint?:
idempotentHint?:
openWorldHint?:
这些注释遵循 MCP 规范,并且在通过 MCP 列出工具时会被传递。
🌐 These annotations follow the MCP specification and are passed through when tools are listed via MCP.
相关Direct link to 相关
🌐 Related