Tools
File-based Agent 会从其 tools/ 直属目录下的 .ts 和 .js 文件中发现 Tool。每个发现的文件都会在构建时导入,且必须默认导出一个 createTool() 结果;不含扩展名的文件名将成为模型可调用的 Tool 键。
本页介绍基于文件的约定。有关 Tool schema、执行选项、输出调整和审批选项,请参阅 createTool() 参考。
快速开始快速开始的直接链接
在 tools/ 下每个文件放置一个 Tool。此文件会以 get_weather 名称向 Agent 公开。
src/mastra/agents/weather/tools/get_weather.ts
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export default createTool({
id: 'get_weather',
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' }
},
})
组织 Tool组织 Tool的直接链接
每个文件放置一个 Tool。以模型应执行的操作命名文件:
- 使用
get_weather.ts、search_docs.ts或create_ticket.ts。 - 避免使用
helper.ts、api.ts或utils.ts等含糊名称。 - 以
*.test.ts或*.spec.ts的形式将测试放在 Tool 旁边。发现过程会忽略这些文件。 - 将共享的辅助代码放在
tools/之外,或放在tools/下扩展名不符合发现规则的文件中。
嵌套目录不会被发现为 Tool,因此请使用清晰的文件名前缀(例如 calendar_create_event.ts 和 calendar_list_events.ts)来组织相关 Tool,而不是使用子文件夹。
Tool 选项Tool 选项的直接链接
基于文件的约定只控制 Tool 的存放位置及其注册方式。Tool API 仍由 createTool() 提供:
- 使用
description告诉模型何时调用 Tool。 - 使用
inputSchema和outputSchema定义结构化输入和输出。 - 当模型应看到与
execute返回的原始值不同的结构时,使用toModelOutput。 - 当 Tool 在执行前需要人工确认时,使用
requireApproval。
有关所有选项,请参阅 createTool() 参考;有关审批流程,请参阅 Tool 审批。
运行时边界运行时边界的直接链接
Agent 调用 Tool 时,Tool 代码会在你的应用/server 运行时中执行。如果 Tool 需要文件系统或 shell 隔离,请显式调用 workspace 或 sandbox API。
与 config 的优先级与 config 的优先级的直接链接
发现的 Tool 会与 config.ts 中的所有 tools 合并。如果键冲突,config.tools 优先,并会记录警告。
如果 config.tools 是函数,Mastra 会忽略发现的 Tool 并发出警告,因为值为函数的 Tool 无法进行静态合并。