Adding a tool
When building AI agents, you often need to extend their capabilities with external data or functionality. Mastra lets you pass tools to an agent using the tools
parameter. Tools give agents a way to call specific functions, such as fetching data or performing calculations, to help answer a user’s query.
Prerequisites
This example uses the openai
model. Make sure to add OPENAI_API_KEY
to your .env
file.
OPENAI_API_KEY=<your-api-key>
Creating a tool
This tool provides historical weather data for London, returning arrays of daily temperature, precipitation, wind speed, snowfall, and weather conditions from January 1st of the current year up to today. This structure makes it easy for agents to access and reason about recent weather trends.
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export const londonWeatherTool = createTool({
id: "london-weather-tool",
description: "Returns year-to-date historical weather data for London",
outputSchema: z.object({
date: z.array(z.string()),
temp_max: z.array(z.number()),
temp_min: z.array(z.number()),
rainfall: z.array(z.number()),
windspeed: z.array(z.number()),
snowfall: z.array(z.number())
}),
execute: async () => {
const startDate = `${new Date().getFullYear()}-01-01`;
const endDate = new Date().toISOString().split("T")[0];
const response = await fetch(
`https://archive-api.open-meteo.com/v1/archive?latitude=51.5072&longitude=-0.1276&start_date=${startDate}&end_date=${endDate}&daily=temperature_2m_max,temperature_2m_min,precipitation_sum,windspeed_10m_max,snowfall_sum&timezone=auto`
);
const { daily } = await response.json();
return {
date: daily.time,
temp_max: daily.temperature_2m_max,
temp_min: daily.temperature_2m_min,
rainfall: daily.precipitation_sum,
windspeed: daily.windspeed_10m_max,
snowfall: daily.snowfall_sum
};
}
});
Adding a tool to an agent
This agent uses the londonWeatherTool
to answer questions about historical weather in London. It has clear instructions that guide it to use the tool for every query and limit its responses to data available for the current calendar year.
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { londonWeatherTool } from "../tools/example-london-weather-tool";
export const londonWeatherAgent = new Agent({
name: "london-weather-agent",
description: "Provides historical information about London weather",
instructions: `You are a helpful assistant with access to historical weather data for London.
- The data is limited to the current calendar year, from January 1st up to today's date.
- Use the provided tool (londonWeatherTool) to retrieve relevant data.
- Answer the user's question using that data.
- Keep responses concise, factual, and informative.
- If the question cannot be answered with available data, say so clearly.`,
model: openai("gpt-4o"),
tools: { londonWeatherTool }
});
Example usage
Use getAgent()
to retrieve a reference to the agent, then call generate()
with a prompt.
import "dotenv/config";
import { mastra } from "./mastra";
const agent = mastra.getAgent("londonWeatherAgent");
const response = await agent.generate("How many times has it rained this year?");
console.log(response.text);