createTool()
createTool() 函数用于定义 Mastra Agent 可运行的自订 Tool。Tool 能让 Agent 与外部系统交互、运行计算或访问特定数据,借此扩充 Agent 的能力。
使用范例使用范例的直接链接
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const weatherTool = createTool({
id: 'weather-tool',
description: 'Get the current weather for a location',
inputSchema: z.object({
location: z.string(),
}),
outputSchema: z.object({
location: z.string(),
temperatureCelsius: z.number(),
conditions: z.string(),
}),
execute: async ({ location }) => {
return {
location,
temperatureCelsius: 21,
conditions: 'sunny',
}
},
})
execute 的第一个参数是经 inputSchema 验证的值。请直接在函数 signature 中解构 schema 字段,如 { location } 所示。选填的第二个参数包含 execution context。
参数参数的直接链接
id:
description:
inputSchema?:
execute 函数预期的输入参数。outputSchema?:
execute 函数预期的输出结构。strict?:
toModelOutput?:
execute 输出传回模型前进行转换。可用来将 text、json 或 content 结构的输出(包括图片/文件等多模态部分)回传给模型,同时在应用代码中保留完整原始输出。transform?:
input、inputDelta、output、error、approval、suspend 与 resume 等阶段设置 display 和 transcript transform。suspendSchema?:
suspend() 的 payload 结构。Tool 暂停运行时会将此 payload 回传给 client。resumeSchema?:
resumeData 结构。激活 autoResumeSuspendedTools 时,Agent 会使用此 schema 从用户消息截取数据。requireApproval?:
tool-call-approval 区块并暂停,直到核准或拒绝为止。mcp?:
annotations(例如 title、readOnlyHint、destructiveHint、idempotentHint、openWorldHint 等 Tool 行为提示)与 _meta(原样传给 MCP client 的任意中继数据)。requestContextSchema?:
providerOptions?:
anthropic 或 openai 等 Provider 名称,值则是 Provider 特定设置对象。inputExamples?:
background?:
execute?:
execute,但对于在其他位置运行或调整的 Tool 定义,此类型允许省略。它接受两个参数:根据 inputSchema 验证的输入数据(第一个参数),以及包含 requestContext、abortSignal 与其他运行中继数据的 execution context 对象(第二个参数)。input:
context?:
requestContext?:
abortSignal?:
agent?:
workflow?:
mcp?:
observe:
span 会直接运行函数,而 log 不会运行任何操作。onInputStart?:
(options: ToolCallOptions) => void | PromiseLike<void>。onInputDelta?:
({ inputTextDelta, ...options }: { inputTextDelta: string } & ToolCallOptions) => void | PromiseLike<void>。onInputAvailable?:
({ input, ...options }: { input: TSchemaIn } & ToolCallOptions) => void | PromiseLike<void>。onOutput?:
({ output, toolName, ...options }: { output: TSchemaOut; toolName: string } & Omit<ToolCallOptions, 'messages'>) => void | PromiseLike<void>。mastra 与 mcpMetadata 等由 runtime 填入的字段会出现在来源类型中,但由 Mastra 或 MCP adapter 设置。一般使用 createTool() 时不需要设置这些字段。
回传值回传值的直接链接
createTool() 函数会回传 Tool 对象。
Tool:
定义 schema定义 schema的直接链接
你可以使用任何支持 Standard JSON Schema 的函数库定义 Tool 的 inputSchema 与 outputSchema,包括 Zod、Valibot 与 ArkType。
- Zod
- Valibot
- ArkType
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const weatherTool = createTool({
id: 'weather-tool',
description: 'Fetches weather for a location',
inputSchema: z.object({
location: z.string(),
}),
outputSchema: z.object({
location: z.string(),
temperatureCelsius: z.number(),
conditions: z.string(),
}),
execute: async ({ location }) => {
return { location, temperatureCelsius: 21, conditions: 'sunny' }
},
})
import { createTool } from '@mastra/core/tools'
import * as v from 'valibot'
import { toStandardJsonSchema } from '@valibot/to-json-schema'
export const weatherTool = createTool({
id: 'weather-tool',
description: 'Fetches weather for a location',
inputSchema: toStandardJsonSchema(
v.object({
location: v.string(),
}),
),
outputSchema: toStandardJsonSchema(
v.object({
location: v.string(),
temperatureCelsius: v.number(),
conditions: v.string(),
}),
),
execute: async ({ location }) => {
return { location, temperatureCelsius: 21, conditions: 'sunny' }
},
})
import { createTool } from '@mastra/core/tools'
import { type } from 'arktype'
export const weatherTool = createTool({
id: 'weather-tool',
description: 'Fetches weather for a location',
inputSchema: type({
location: 'string',
}),
outputSchema: type({
location: 'string',
temperatureCelsius: 'number',
conditions: 'string',
}),
execute: async ({ location }) => {
return { location, temperatureCelsius: 21, conditions: 'sunny' }
},
})
使用严格 Tool 输入的范例使用严格 Tool 输入的范例的直接链接
若要让 Mastra 要求支持此功能的模型 Provider 产生完全符合 Tool schema 的参数,请设置 strict: true。
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const weatherTool = createTool({
id: 'weather-tool',
description: 'Get the current weather for a location',
strict: true,
inputSchema: z.object({
location: z.string(),
}),
outputSchema: z.object({
location: z.string(),
temperatureCelsius: z.number(),
conditions: z.string(),
}),
execute: async ({ location }) => {
return {
location,
temperatureCelsius: 21,
conditions: 'sunny',
}
},
})
Mastra 会将 strict: true 转送至支持严格 Tool 调用的 model adapter。不支持此功能的 adapter 会忽略此选项。
使用 toModelOutput 的范例example-with-tomodeloutput的直接链接
若 Tool 应向应用程序回传丰富的内部数据,但模型只应接收简化值或多模态内容,请使用 toModelOutput。
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const weatherTool = createTool({
id: 'weather-tool',
description: 'Get the current weather for a location',
inputSchema: z.object({
location: z.string(),
}),
outputSchema: z.object({
location: z.string(),
temperatureCelsius: z.number(),
conditions: z.string(),
radarImageUrl: z.string().url(),
}),
execute: async ({ location }) => ({
location,
temperatureCelsius: 21,
conditions: 'sunny',
radarImageUrl: 'https://example.com/radar/seattle.png',
}),
toModelOutput: output => {
return {
type: 'content',
value: [
{
type: 'text',
text: `${output.location}: ${output.temperatureCelsius}°C and ${output.conditions}`,
},
{ type: 'image-url', url: output.radarImageUrl },
],
}
},
})
Tool 仍会将完整的 execute 结果回传给应用程序,而模型会收到转换后的 toModelOutput 值。
toModelOutput 可回传:
type: 'text'type: 'json'type: 'content',并包含text、image-url、image-data、file-url、file-data、file-id、image-file-id或custom等部分
使用 transform 的范例example-with-transform的直接链接
若 Tool 应保留原始输入或输出供 runtime 行为使用,但显示串流或 transcript 消息应接收更小或更安全的结构,请使用 transform。
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const customerTool = createTool({
id: 'lookup-customer',
description: 'Looks up a customer',
inputSchema: z.object({
customerId: z.string(),
internalPath: z.string(),
}),
outputSchema: z.object({
displayName: z.string(),
apiKey: z.string(),
debugScore: z.number(),
}),
execute: async () => {
return {
displayName: 'Acme',
apiKey: 'secret-value',
debugScore: 0.97,
}
},
transform: {
display: {
input: ({ input }) => ({ customerId: input?.customerId }),
output: ({ output }) => ({ displayName: output?.displayName }),
error: () => ({ message: 'Customer lookup failed' }),
},
transcript: {
input: ({ input }) => ({ customerId: input?.customerId }),
output: ({ output }) => ({ displayName: output?.displayName }),
error: () => ({ message: 'Customer lookup failed' }),
},
},
})
Tool 仍会接收原始 inputSchema 值并回传原始 execute 结果。Mastra 会对串流 UI payload 套用 display transform,并对用户可见的 transcript 消息套用 transcript transform。
使用 MCP annotation 的范例使用 MCP annotation 的范例的直接链接
通过 MCP(Model Context Protocol)公开 Tool 时,你可以加入 annotation 来说明 Tool 行为,并自订 client 显示 Tool 的方式。这些 MCP 特定属性会集中在 mcp 属性下:
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const weatherTool = createTool({
id: 'weather-tool',
description: 'Get the current weather for a location',
inputSchema: z.object({
location: z.string().describe('City name or coordinates'),
}),
outputSchema: z.object({
location: z.string(),
temperatureCelsius: z.number(),
conditions: z.string(),
}),
// 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 ({ location }) => {
return {
location,
temperatureCelsius: 21,
conditions: 'sunny',
}
},
})
Tool lifecycle hook(生命周期钩子)Tool lifecycle hook(生命周期钩子)的直接链接
Tool 支持 lifecycle hook,让你监控 Tool 运行的不同阶段并做出回应。这些 hook 特别适合用于 logging、分析、验证与串流期间的即时更新。
下列范例示范设置所有 lifecycle hook 的 Tool:
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const weatherTool = createTool({
id: 'weather-tool',
description: 'Get the current weather for a location',
inputSchema: z.object({
location: z.string(),
}),
outputSchema: z.object({
location: z.string(),
temperatureCelsius: z.number(),
conditions: z.string(),
}),
execute: async ({ location }) => {
return {
location,
temperatureCelsius: 21,
conditions: 'sunny',
}
},
onInputStart: ({ toolCallId }) => {
console.log(`Tool call ${toolCallId} input started`)
},
onInputDelta: ({ inputTextDelta, toolCallId }) => {
console.log(`Tool call ${toolCallId} received input chunk: ${inputTextDelta}`)
},
onInputAvailable: ({ input, toolCallId }) => {
console.log(`Tool call ${toolCallId} received location: ${input.location}`)
},
onOutput: ({ output, toolCallId, toolName }) => {
console.log(`Tool ${toolName} call ${toolCallId} returned conditions: ${output.conditions}`)
},
})
可用的 hook可用的 hook的直接链接
onInputStartoninputstart的直接链接
Tool 调用的输入串流开始、但尚未收到任何输入数据时叫用。
export const tool = createTool({
id: 'example-tool',
description: 'Example tool with hooks',
onInputStart: ({ toolCallId, messages, abortSignal }) => {
console.log(`Tool ${toolCallId} input streaming started`)
},
})
onInputDeltaoninputdelta的直接链接
输入文本串流传入时,针对每个增量区块叫用。适合用来显示即时进度或解析部分 JSON。
export const tool = createTool({
id: 'example-tool',
description: 'Example tool with hooks',
onInputDelta: ({ inputTextDelta, toolCallId, messages, abortSignal }) => {
console.log(`Received input chunk: ${inputTextDelta}`)
},
})
onInputAvailableoninputavailable的直接链接
完整 Tool 输入可用,且已根据 inputSchema 解析与验证时叫用。
export const tool = createTool({
id: 'example-tool',
description: 'Example tool with hooks',
inputSchema: z.object({
location: z.string(),
}),
onInputAvailable: ({ input, toolCallId, messages, abortSignal }) => {
console.log(`Tool received complete input:`, input)
// input is fully typed based on inputSchema
},
})
onOutputonoutput的直接链接
Tool 成功运行并回传输出后叫用。适合用于记录结果、触发后续动作或分析。
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
},
})
Hook 运行顺序Hook 运行顺序的直接链接
一般串流 Tool 调用会依下列顺序叫用 hook:
- onInputStart:输入串流开始
- onInputDelta:区块抵达时叫用多次
- onInputAvailable:解析并验证完整输入
- 运行 Tool 的 execute 函数
- onOutput:Tool 已成功完成
Hook 参数Hook 参数的直接链接
Hook callback 会收到下列由来源类型支持的参数结构:
onInputStart:接收ToolCallOptions,包括toolCallId、messages与abortSignal等字段。onInputDelta:接收{ inputTextDelta: string } & ToolCallOptions。onInputAvailable:接收{ input: TSchemaIn } & ToolCallOptions,其中input的类型来自inputSchema。onOutput:接收{ output: TSchemaOut; toolName: string } & Omit<ToolCallOptions, 'messages'>,其中output的类型来自outputSchema。此 hook 不会接收messages。
错误处理错误处理的直接链接
系统会自动拦截并记录 hook 错误,但不会阻止 Tool 继续运行。若 hook 掷回错误,系统会将其记录到主控台,但 Tool 调用不会失败。
MCP Tool annotation(注解)MCP Tool annotation(注解)的直接链接
通过 Model Context Protocol(MCP)公开 Tool 时,你可以提供描述 Tool 行为的 annotation。这些 annotation 可协助 OpenAI Apps SDK 等 MCP client 了解如何呈现与处理 Tool。
MCP 特定属性会集中在 mcp 属性下,其中包括 annotations 与 _meta:
mcp: {
annotations: { /* behavior hints */ },
_meta: { /* custom metadata */ },
}
ToolAnnotations 属性toolannotations-properties的直接链接
title?:
readOnlyHint?:
destructiveHint?:
idempotentHint?:
openWorldHint?:
这些 annotation 遵循 MCP 规范,并会在通过 MCP 列出 Tool 时原样传递。