Tools
A file-based agent discovers tools from .ts and .js files directly under its tools/ directory. Each discovered file is imported at build time, the file must default-export a createTool() result, and the filename without its extension becomes the tool key the model can call.
Use this page for the file-based convention. For tool schemas, execution options, output shaping, and approval options, see the createTool() reference.
QuickstartQuickstart的直接链接
Place one tool per file under tools/. This file is exposed to the agent as get_weather.
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' }
},
})
Organizing toolsOrganizing tools的直接链接
Use one file per tool. Name the file after the action the model should take:
- Use
get_weather.ts,search_docs.ts, orcreate_ticket.ts. - Avoid vague names like
helper.ts,api.ts, orutils.ts. - Co-locate tests next to the tool as
*.test.tsor*.spec.ts. Discovery ignores those files. - Keep shared helper code outside
tools/or in files that don't match the discovered extensions undertools/.
Because nested directories aren't discovered as tools, group related tools with clear filename prefixes instead of subfolders, such as calendar_create_event.ts and calendar_list_events.ts.
Tool optionsTool options的直接链接
The file-based convention only controls where the tool lives and how it's registered. The tool API still comes from createTool():
- Use
descriptionto tell the model when to call the tool. - Use
inputSchemaandoutputSchemafor structured inputs and outputs. - Use
toModelOutputwhen the model should see a different shape than the raw value returned fromexecute. - Use
requireApprovalwhen a tool needs human confirmation before execution.
See the createTool() reference for all options and tool approval for the approval flow.
Runtime boundaryRuntime boundary的直接链接
Tool code runs in your app/server runtime when the agent calls the tool. If a tool needs filesystem or shell isolation, call workspace or sandbox APIs explicitly.
Precedence with configPrecedence with config的直接链接
Discovered tools merge with any tools in config.ts. On a key collision, config.tools wins and a warning is logged.
If config.tools is a function, discovered tools are ignored with a warning because function-valued tools can't be statically merged.