Skip to main content

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

src/mastra/tools/reverse-tool.ts
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:

src/mastra/tools/weather-tool.ts
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:

string
A unique identifier for the tool.

description:

string
A description of what the tool does. This is used by the agent to decide when to use the tool.

inputSchema?:

Zod schema
A Zod schema defining the expected input parameters for the tool's `execute` function.

outputSchema?:

Zod schema
A Zod schema defining the expected output structure of the tool's `execute` function.

suspendSchema?:

Zod schema
A Zod schema defining the structure of the payload passed to `suspend()`. This payload is returned to the client when the tool suspends execution.

resumeSchema?:

Zod schema
A Zod schema defining the expected structure of `resumeData` when the tool is resumed. Used by the agent to extract data from user messages when `autoResumeSuspendedTools` is enabled.

requireApproval?:

boolean
When true, the tool requires explicit approval before execution. The agent will emit a `tool-call-approval` chunk and pause until approved or declined.

mcp?:

MCPToolProperties
MCP-specific properties for tools exposed via Model Context Protocol. Includes `annotations` (tool behavior hints like `title`, `readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`) and `_meta` (arbitrary metadata passed through to MCP clients).

execute:

function
The function that contains the tool's logic. It receives two parameters: the validated input data (first parameter) and an optional execution context object (second parameter) containing `requestContext`, `tracingContext`, `abortSignal`, and other execution metadata.

input:

z.infer<TInput>
The validated input data based on inputSchema

context?:

ToolExecutionContext
Optional execution context containing metadata

onInputStart?:

function
Optional callback invoked when the tool call input streaming begins. Receives `toolCallId`, `messages`, and `abortSignal`.

onInputDelta?:

function
Optional callback invoked for each incremental chunk of input text as it streams in. Receives `inputTextDelta`, `toolCallId`, `messages`, and `abortSignal`.

onInputAvailable?:

function
Optional callback invoked when the complete tool input is available and parsed. Receives the validated `input` object, `toolCallId`, `messages`, and `abortSignal`.

onOutput?:

function
Optional callback invoked after the tool has successfully executed and returned output. Receives the tool's `output`, `toolCallId`, `messages`, and `abortSignal`.

返回
Direct link to 返回

🌐 Returns

createTool() 函数返回一个 Tool 对象。

🌐 The createTool() function returns a Tool object.

Tool:

object
An object representing the defined tool, ready to be added to an agent.

工具生命周期钩子
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

onInputStart
Direct 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`);
},
});

onInputDelta
Direct 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}`);
},
});

onInputAvailable
Direct 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
},
});

onOutput
Direct 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:

  1. onInputStart - 输入流开始
  2. onInputDelta - 当数据块到达时会被多次调用
  3. onInputAvailable - 已完成的输入已被解析和验证
  4. 工具的执行功能运行
  5. onOutput - 工具已成功完成

钩子参数
Direct link to 钩子参数

🌐 Hook Parameters

所有钩子都会接收一个包含以下常用属性的参数对象:

🌐 All hooks receive a parameter object with these common properties:

  • toolCallId(字符串):此特定工具调用的唯一标识符
  • abortSignal (AbortSignal):用于检测操作是否应被取消的信号

此外:

🌐 Additionally:

  • onInputStartonInputDeltaonInputAvailable 接收 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?:

string
A human-readable title for the tool. Used for display purposes in UI components.

readOnlyHint?:

boolean
If true, the tool does not modify its environment. This hint indicates the tool only reads data and has no side effects. Defaults to false.

destructiveHint?:

boolean
If true, the tool may perform destructive updates to its environment. If false, the tool performs only additive updates. This hint helps clients determine if confirmation should be required. Defaults to true.

idempotentHint?:

boolean
If true, calling the tool repeatedly with the same arguments will have no additional effect on its environment. This hint indicates idempotent behavior. Defaults to false.

openWorldHint?:

boolean
If true, this tool may interact with an 'open world' of external entities (e.g., web search, external APIs). If false, the tool's domain is closed and fully defined. Defaults to true.

这些注释遵循 MCP 规范,并且在通过 MCP 列出工具时会被传递。

🌐 These annotations follow the MCP specification and are passed through when tools are listed via MCP.

🌐 Related