跳到主要内容

createTool()

createTool() 函数用于定义 Mastra Agent 可运行的自订 Tool。Tool 能让 Agent 与外部系统交互、运行计算或访问特定数据,借此扩充 Agent 的能力。

使用范例
使用范例的直接链接

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

string
Tool 的唯一识别码。

description:

string
Tool 功能的说明。Agent 会使用此说明判断何时使用 Tool。

inputSchema?:

StandardJSONSchemaV1
Standard JSON Schema,用于定义 Tool execute 函数预期的输入参数。

outputSchema?:

StandardJSONSchemaV1
Standard JSON Schema,用于定义 Tool execute 函数预期的输出结构。

strict?:

boolean
设为 true 时,Mastra 会在支持的 model adapter 上激活严格 Tool 输入产生功能,协助支持此功能的 Provider 回传更符合 Tool schema 的参数。

toModelOutput?:

(output: TSchemaOut) => unknown
选填函数,在 Tool 的 execute 输出传回模型前进行转换。可用来将 textjsoncontent 结构的输出(包括图片/文件等多模态部分)回传给模型,同时在应用代码中保留完整原始输出。

transform?:

ToolPayloadTransform
选填的目标感知 transform,会在 Tool payload 离开 runtime、进入显示串流或用户可见的 transcript 消息前进行转换。可为 inputinputDeltaoutputerrorapprovalsuspendresume 等阶段设置 displaytranscript transform。

suspendSchema?:

StandardJSONSchemaV1
Standard JSON Schema,用于定义传给 suspend() 的 payload 结构。Tool 暂停运行时会将此 payload 回传给 client。

resumeSchema?:

StandardJSONSchemaV1
Standard JSON Schema,用于定义 Tool 继续运行时预期的 resumeData 结构。激活 autoResumeSuspendedTools 时,Agent 会使用此 schema 从用户消息截取数据。

requireApproval?:

boolean
设为 true 时,Tool 在运行前需要明确核准。Agent 会发出 tool-call-approval 区块并暂停,直到核准或拒绝为止。

mcp?:

MCPToolProperties
通过 Model Context Protocol 公开之 Tool 的 MCP 特定属性。包含 annotations(例如 titlereadOnlyHintdestructiveHintidempotentHintopenWorldHint 等 Tool 行为提示)与 _meta(原样传给 MCP client 的任意中继数据)。

requestContextSchema?:

StandardJSONSchemaV1
用于验证 request context 值的 Standard JSON Schema。提供此值时,系统会在 execute() 运行前验证 context;若验证失败,则回传错误对象。

providerOptions?:

Record<string, Record<string, unknown>>
使用此 Tool 时传给模型的 Provider 特定选项。Key 是 anthropicopenai 等 Provider 名称,值则是 Provider 特定设置对象。

inputExamples?:

Array<{ input: Record<string, unknown> }>
有效 Tool 输入的范例,支持此功能的模型 Provider 可将其用作输入范例。

background?:

ToolBackgroundConfig
此 Tool 的背景任务设置。激活后,Agent 对话继续进行时,Tool 可在背景运行。

execute?:

function
包含 Tool 逻辑的函数。一般自订 Tool 通常会提供 execute,但对于在其他位置运行或调整的 Tool 定义,此类型允许省略。它接受两个参数:根据 inputSchema 验证的输入数据(第一个参数),以及包含 requestContextabortSignal 与其他运行中继数据的 execution context 对象(第二个参数)。

input:

z.infer<TInput>
根据 inputSchema 验证的输入数据

context?:

ToolExecutionContext
包含中继数据的选填 execution context
ToolExecutionContext

requestContext?:

RequestContext
用于访问共用状态与相依项目的 Request Context

abortSignal?:

AbortSignal
用于中止 Tool 运行的 signal

agent?:

AgentToolExecutionContext
Agent 特定 context,在 Agent 运行 Tool 时可用。
string
string
CoreMessage[]
(payload, options?) => Promise<void>
TResume
string
string
WritableStream<any>

workflow?:

WorkflowToolExecutionContext
Workflow 特定 context(state、setState、suspend 等)

mcp?:

MCPToolExecutionContext
MCP 特定 context(elicitation 等)

observe:

ToolObserve
Observability helper,可从 Tool 的 execute 函数内记录 child span 与结构化 log。此值一律提供;没有作用中的 tracing context 时,span 会直接运行函数,而 log 不会运行任何操作。
(name: string, fn: () => Promise<T> | T, attributes?: Record<string, unknown>) => Promise<T>
(level: 'debug' | 'info' | 'warn' | 'error' | 'fatal', message: string, data?: Record<string, unknown>) => void

onInputStart?:

function
Tool 调用的输入串流开始时叫用的选填 callback。Signature:(options: ToolCallOptions) => void | PromiseLike<void>

onInputDelta?:

function
输入文本串流传入时,为每个增量区块叫用的选填 callback。Signature:({ inputTextDelta, ...options }: { inputTextDelta: string } & ToolCallOptions) => void | PromiseLike<void>

onInputAvailable?:

function
完整 Tool 输入可用且已解析时叫用的选填 callback。Signature:({ input, ...options }: { input: TSchemaIn } & ToolCallOptions) => void | PromiseLike<void>

onOutput?:

function
Tool 成功运行并回传输出后叫用的选填 callback。Signature:({ output, toolName, ...options }: { output: TSchemaOut; toolName: string } & Omit<ToolCallOptions, 'messages'>) => void | PromiseLike<void>

mastramcpMetadata 等由 runtime 填入的字段会出现在来源类型中,但由 Mastra 或 MCP adapter 设置。一般使用 createTool() 时不需要设置这些字段。

回传值
回传值的直接链接

createTool() 函数会回传 Tool 对象。

Tool:

object
代表已定义 Tool 的对象,可直接加入 Agent。

定义 schema
定义 schema的直接链接

你可以使用任何支持 Standard JSON Schema 的函数库定义 Tool 的 inputSchemaoutputSchema,包括 ZodValibotArkType

src/mastra/tools/weather-tool.ts
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' }
},
})

使用严格 Tool 输入的范例
使用严格 Tool 输入的范例的直接链接

若要让 Mastra 要求支持此功能的模型 Provider 产生完全符合 Tool schema 的参数,请设置 strict: true

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

src/mastra/tools/weather-tool.ts
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',并包含 textimage-urlimage-datafile-urlfile-datafile-idimage-file-idcustom 等部分

使用 transform 的范例
example-with-transform的直接链接

若 Tool 应保留原始输入或输出供 runtime 行为使用,但显示串流或 transcript 消息应接收更小或更安全的结构,请使用 transform

src/mastra/tools/customer-tool.ts
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 属性下:

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

src/mastra/tools/weather-tool.ts
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的直接链接

onInputStart
oninputstart的直接链接

Tool 调用的输入串流开始、但尚未收到任何输入数据时叫用。

export const tool = createTool({
id: 'example-tool',
description: 'Example tool with hooks',
onInputStart: ({ toolCallId, messages, abortSignal }) => {
console.log(`Tool ${toolCallId} input streaming started`)
},
})

onInputDelta
oninputdelta的直接链接

输入文本串流传入时,针对每个增量区块叫用。适合用来显示即时进度或解析部分 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
oninputavailable的直接链接

完整 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
},
})

onOutput
onoutput的直接链接

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:

  1. onInputStart:输入串流开始
  2. onInputDelta:区块抵达时叫用多次
  3. onInputAvailable:解析并验证完整输入
  4. 运行 Tool 的 execute 函数
  5. onOutput:Tool 已成功完成

Hook 参数
Hook 参数的直接链接

Hook callback 会收到下列由来源类型支持的参数结构:

  • onInputStart:接收 ToolCallOptions,包括 toolCallIdmessagesabortSignal 等字段。
  • 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?:

string
便于阅读的 Tool 标题,用于 UI 组件中的显示用途。

readOnlyHint?:

boolean
若为 true,Tool 不会修改环境。此提示表示 Tool 只会读取数据,且没有副作用。缺省为 false。

destructiveHint?:

boolean
若为 true,Tool 可能对环境运行破坏性更新。若为 false,Tool 只会运行附加式更新。此提示可协助 client 判断是否应要求确认。缺省为 true。

idempotentHint?:

boolean
若为 true,使用相同参数重复调用 Tool 不会对环境产生额外影响。此提示表示等幂行为。缺省为 false。

openWorldHint?:

boolean
若为 true,此 Tool 可能与外部实体的「开放世界」(例如网页搜索、外部 API)交互。若为 false,Tool 的作用域封闭且已完整定义。缺省为 true。

这些 annotation 遵循 MCP 规范,并会在通过 MCP 列出 Tool 时原样传递。