Tools
Trust: ★★★☆☆ (0.90) · 0 validations · developer_reference
Published: 2026-05-10 · Source: crawler_authoritative
Tình huống
Mastra agent SDK documentation for configuring and using tools that extend agent capabilities beyond language generation through structured API calls, database queries, and custom functions.
Insight
Tools in Mastra are created using the createTool function from @mastra/core/tools. Each tool requires an id (unique identifier), description (helps agent decide when to use), inputSchema (defines required input structure), outputSchema (defines return structure), and an execute async function. Input data is accessed via the inputData parameter in the execute function. Schema definitions support any Standard JSON Schema-compatible library including Zod, Valibot, and ArkType. Zod uses z.object() directly, while Valibot requires toStandardJsonSchema() from @valibot/to-json-schema, and ArkType uses type() from ‘arktype’. Multiple tools can be assigned to a single agent via the tools property on the Agent class. Subagents are added through the agents configuration and converted to tools named agent-<key>. Workflows are added through workflows configuration and converted to tools named workflow-<key>. The toModelOutput function shapes rich structured data into a smaller or multimodal representation for the model while preserving full results in the application. The transform function shapes payloads for display and transcript targets separately from toModelOutput. Runtime tool control is available via toolChoice and activeTools parameters on .generate() or .stream(). The toolName in stream responses is determined by the object key used, not the tool’s id property. Descriptive schema names and concise descriptions focusing on primary use cases help guide agent behavior.
Hành động
- Import
createToolfrom@mastra/core/toolsand schema library (z, valibot, or arktype). 2. Define tool withid,description,inputSchema,outputSchema, andexecutefunction. 3. UsetoModelOutputto shape output for the model if returning rich structured data. 4. Usetransformto shape payloads for UI/transcripts. 5. Add tool to agent viatoolsproperty on Agent class. 6. Mention tools in agent’s system prompt to guide tool selection. 7. For runtime control, passtoolChoice: 'required'andactiveTools: ['toolName']to.generate()or.stream(). 8. For custom stream tool names, use object key syntax:{ 'my-custom-name': weatherTool }results intoolName: "my-custom-name".
Kết quả
Agents use tools to fetch live data, call APIs, query databases, or run custom functions. The toolName in stream responses reflects the object key used. Subagents and workflows become callable tools with prefixed names (agent- and workflow-). toModelOutput shapes data for the model while preserving full results in the application. transform shapes payloads for display/transcript targets without fallback to raw data if it fails.
Nội dung gốc (Original)
Tools
Agents use tools to call APIs, query databases, or run custom functions from your codebase. Tools give agents capabilities beyond language generation by providing structured access to data and performing clearly defined operations. You can also load tools from remote MCP servers to expand an agent’s capabilities.
When to use tools
Use tools when an agent needs additional context or information from remote resources, or when it needs to run code that performs a specific operation. This includes tasks a model can’t reliably handle on its own, such as fetching live data or returning consistent, well-defined outputs.
Quickstart
Import createTool from @mastra/core/tools and define a tool with an id, description, inputSchema, outputSchema, and execute function.
This example shows how to create a tool that fetches weather data from an API. When the agent calls the tool, it provides the required input as defined by the tool’s inputSchema. The tool accesses this data through its inputData parameter, which in this example includes the location used in the weather API query.
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({
weather: z.string(),
}),
execute: async inputData => {
const { location } = inputData
const response = await fetch(`https://wttr.in/${location}?format=3`)
const weather = await response.text()
return { weather }
},
})When creating tools, keep descriptions concise and focused on what the tool does, emphasizing its primary use case. Descriptive schema names can also help guide the agent on how to use the tool.
Note: Visit the
createToolreference for more information on available properties, configurations, and examples.
To make a tool available to an agent, add it to the tools property on the Agent class. Mentioning available tools and their general purpose in the agent’s system prompt helps the agent decide when to call a tool and when not to.
import { Agent } from '@mastra/core/agent'
import { weatherTool } from '../tools/weather-tool'
export const weatherAgent = new Agent({
id: 'weather-agent',
name: 'Weather Agent',
instructions: `
You are a helpful weather assistant.
Use the weatherTool to fetch current weather data.`,
model: 'openai/gpt-5.4',
tools: { weatherTool },
})Define schemas
You can define the tool’s inputSchema and outputSchema with any library that supports Standard JSON Schema. This includes libraries like Zod, Valibot, and ArkType.
Zod:
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({
weather: z.string(),
}),
execute: async inputData => {
// Fetch weather data
},
})Valibot:
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({
weather: v.string(),
}),
),
execute: async inputData => {
// Fetch weather data
},
})ArkType:
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({
weather: 'string',
}),
execute: async inputData => {
// Fetch weather data
},
})Multiple tools
An agent can use multiple tools to handle more complex tasks by delegating specific parts to individual tools. The agent decides which tools to use based on the user’s message, the agent’s instructions, and the tool descriptions and schemas.
import { Agent } from '@mastra/core/agent'
import { weatherTool } from '../tools/weather-tool'
import { hazardsTool } from '../tools/hazards-tool'
export const weatherAgent = new Agent({
id: 'weather-agent',
name: 'Weather Agent',
instructions: `
You are a helpful weather assistant.
Use the weatherTool to fetch current weather data.
Use the hazardsTool to provide information about potential weather hazards.`,
model: 'openai/gpt-5.4',
tools: { weatherTool, hazardsTool },
})Agents as tools
Add subagents through the agents configuration to create a supervisor. Mastra converts each subagent to a tool named agent-<key>. Include a description on each subagent so the supervisor knows when to delegate.
import { Agent } from '@mastra/core/agent'
const writer = new Agent({
id: 'writer',
name: 'Writer',
description: 'Drafts and edits written content',
instructions: 'You are a skilled writer.',
model: 'openai/gpt-5.4',
})
export const supervisor = new Agent({
id: 'supervisor',
name: 'Supervisor',
instructions: 'Coordinate the writer to produce content.',
model: 'openai/gpt-5.4',
agents: { writer },
})Workflows as tools
Add workflows through the workflows configuration. Mastra converts each workflow to a tool named workflow-<key>, using the workflow’s inputSchema and outputSchema. Include a description on the workflow so the agent knows when to trigger it.
import { Agent } from '@mastra/core/agent'
import { researchWorkflow } from '../workflows/research-workflow'
export const researchAgent = new Agent({
id: 'research-agent',
name: 'Research Agent',
instructions: 'You are a research assistant.',
model: 'openai/gpt-5.4',
workflows: { researchWorkflow },
})Shape output for the model
Use toModelOutput when your tool returns rich structured data for your application, but you want the model to receive a smaller or multimodal representation. This keeps model context focused while preserving the full tool result in your app.
export const weatherTool = createTool({
execute: async ({ location }) => {
const response = await fetch(`https://wttr.in/${location}?format=j1`)
const data = await response.json()
return {
location,
temperature: data.current_condition[0].temp_F,
condition: data.current_condition[0].weatherDesc[0].value,
weatherIconUrl: data.current_condition[0].weatherIconUrl[0].value,
source: data,
}
},
toModelOutput: output => {
return {
type: 'content',
value: [
{
type: 'text',
text: `${output.location}: ${output.temperature}F and ${output.condition}`,
},
{ type: 'image-url', url: output.weatherIconUrl },
],
}
},
})Transform tool payloads for UI and transcripts
Use transform when a tool returns raw data your application needs, but browser-facing streams or user-visible transcript messages should receive a smaller or safer shape. transform is separate from toModelOutput: toModelOutput shapes the payload sent back to the model, while transform shapes tool input, output, errors, approval payloads, and suspension payloads for display and transcript targets.
If a transform is configured and it fails, Mastra does not fall back to the raw payload for display or transcript targets. Input deltas are suppressed when no safe inputDelta transform is available.
See the createTool() reference for a transform example. For shared rules across several tools, configure the agent-level transform policy in the Agent constructor.
Control tool selection
Pass toolChoice or activeTools to .generate() or .stream() to control which tools the agent uses at runtime.
await agent.generate('Check the forecast', {
toolChoice: 'required',
activeTools: ['weatherTool'],
})Note: See the
Agent.generate()reference for all runtime options includingtoolsets,clientTools, andprepareStep.
Control toolName in stream responses
The toolName in stream responses is determined by the object key you use, not the id property of the tool, agent, or workflow.
export const weatherTool = createTool({
id: 'weather-tool',
})
// Using the variable name as the key
tools: { weatherTool }
// Stream returns: toolName: "weatherTool"
// Using the tool's id as the key
tools: { [weatherTool.id]: weatherTool }
// Stream returns: toolName: "weather-tool"
// Using a custom key
tools: { "my-custom-name": weatherTool }
// Stream returns: toolName: "my-custom-name"This lets you specify how tools are identified in the stream. If you want the toolName to match the tool’s id, use the tool’s id as the object key.
Subagents and workflows as tools
Subagents and workflows follow the same pattern. They’re converted to tools with a prefix followed by your object key:
| Property | Prefix | Example key | toolName |
|---|---|---|---|
agents | agent- | weather | agent-weather |
workflows | workflow- | research | workflow-research |
const orchestrator = new Agent({
agents: {
weather: weatherAgent, // toolName: "agent-weather"
},
workflows: {
research: researchWorkflow, // toolName: "workflow-research"
},
})Note that for subagents, you’ll see two different identifiers in stream responses:
toolName: "agent-weather"in tool call events — the generated tool wrapper nameid: "weather-agent"indata-tool-agentchunks — the subagent’s actualidproperty
Related
createToolreferenceAgent.generate()reference: Runtime options for tool selection, steps, and callbacks- Background tasks: Run long-running tools without blocking the agent loop
- MCP overview
- Dynamic tool search: Load tools on demand for agents with large tool libraries
- Tools with structured output: Model compatibility when combining tools and structured output
- Agent approval
- Request context
Liên kết
- Nền tảng: Dev Framework · Mastra
- Nguồn: https://mastra.ai/docs/agents/using-tools
Xem thêm: