Adding Tools
Tools are typed functions that can be executed by agents or workflows, with built-in integration access and parameter validation. Each tool has a schema that defines its inputs, an executor function that implements its logic, and access to configured integrations.
Creating Tools
Let’s use a public API to get the last day’s closing stock price for a given symbol.
import { Agent, createTool } from '@mastra/core';
import { z } from 'zod';
const getStockPrice = async (symbol) => {
const data = await fetch(`https://mastra-stock-data.vercel.app/api/stock-data?symbol=${symbol}`).then(r => r.json());
return data.prices['4. close'];
};
const stockPrices = createTool({
label: 'Get Stock Price',
schema: z.object({
symbol: z.string()
}),
description: `Fetches the last day's closing stock price for a given symbol`,
executor: async ({ data: { symbol } }) => {
return {
symbol,
currentPrice: await getStockPrice(symbol)
};
}
});
Adding Tools to an Agent
Now we’ll add the tool to an agent. We do this by creating an agent and then passing the tool function to the agent.
import { stockPrices } from '../tools';
export const stockAgent = new Agent({
name: 'Stock Agent',
instructions: "You are a helpful assistant that provides current stock prices. When asked about a stock, use the stock price tool to fetch the stock price.',
model: {
provider: 'OPEN_AI',
name: 'gpt-4o',
toolChoice: 'required'
},
enabledTools: { stockPrices: true },
});
Then, we add both the agent and the tool to the global Mastra instance. This makes the tool available to all agents, as well as workflows (which we’ll cover in the next section).
import * as tools from './tools';
import { stockAgent } from '../agents';
import { Mastra } from '@mastra/core';
export const mastra = new Mastra({
tools,
agents: [stockAgent],
});
Calling an Agent with a Tool
Now we can call the agent, and it will use the tool to fetch the stock price.
import { stockAgent } from './agents';
async function main() {
const response = await stockAgent.text({
messages: ["What is the current stock price of Apple (AAPL)?"]
});
console.log(response.text);
}
main()
Tool Configuration
A tool requires:
label
: Name of the tool (e.g., “Get Stock Prices”)schema
: Zod schema for validating inputs like stock symbols and timeframesdescription
: Clear explanation of what market data the tool providesexecutor
: Async function that fetches the requested market data
The executor receives:
data
: The validated input data (in this case, stock symbol and timeframe)getIntegration
: Function to access market data providers