Advanced Tool Usage
This page covers more advanced techniques and features related to using tools in Mastra.
Abort Signals
When you initiate an agent interaction using generate()
or stream()
, you can provide an AbortSignal
. Mastra automatically forwards this signal to any tool executions that occur during that interaction.
This allows you to cancel long-running operations within your tools, such as network requests or intensive computations, if the parent agent call is aborted.
You access the abortSignal
in the second parameter of the tool’s execute
function.
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export const longRunningTool = createTool({
id: "long-computation",
description: "Performs a potentially long computation",
inputSchema: z.object({ /* ... */ }),
execute: async ({ context }, { abortSignal }) => {
// Example: Forwarding signal to fetch
const response = await fetch("https://api.example.com/data", {
signal: abortSignal, // Pass the signal here
});
if (abortSignal?.aborted) {
console.log("Tool execution aborted.");
throw new Error("Aborted");
}
// Example: Checking signal during a loop
for (let i = 0; i < 1000000; i++) {
if (abortSignal?.aborted) {
console.log("Tool execution aborted during loop.");
throw new Error("Aborted");
}
// ... perform computation step ...
}
const data = await response.json();
return { result: data };
},\n});
To use this, provide an AbortController
’s signal when calling the agent:
import { Agent } from "@mastra/core/agent";
// Assume 'agent' is an Agent instance with longRunningTool configured
const controller = new AbortController();
// Start the agent call
const promise = agent.generate("Perform the long computation.", {
abortSignal: controller.signal,
});
// Sometime later, if needed:
// controller.abort();
try {
const result = await promise;
console.log(result.text);
} catch (error) {
if (error.name === 'AbortError') {
console.log("Agent generation was aborted.");
} else {
console.error("An error occurred:", error);
}
}
AI SDK Tool Format
Mastra maintains compatibility with the tool format used by the Vercel AI SDK (ai
package). You can define tools using the tool
function from the ai
package and use them directly within your Mastra agents alongside tools created with Mastra’s createTool
.
First, ensure you have the ai
package installed:
npm install ai
Here’s an example of a tool defined using the Vercel AI SDK format:
import { tool } from "ai";
import { z } from "zod";
export const vercelWeatherTool = tool({
description: "Fetches current weather using Vercel AI SDK format",
parameters: z.object({
city: z.string().describe("The city to get weather for"),
}),
execute: async ({ city }) => {
console.log(`Fetching weather for ${city} (Vercel format tool)`);
// Replace with actual API call
const data = await fetch(`https://api.example.com/weather?city=${city}`);
return data.json();
},
});
You can then add this tool to your Mastra agent just like any other tool:
import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";
import { vercelWeatherTool } from "../tools/vercelWeatherTool"; // Vercel AI SDK tool
import { mastraTool } from "../tools/mastraTool"; // Mastra createTool tool
export const mixedToolsAgent = new Agent({
name: "Mixed Tools Agent",
instructions:
"You can use tools defined in different formats.",
model: openai("gpt-4o-mini"),
tools: {
weatherVercel: vercelWeatherTool,
someMastraTool: mastraTool,
},
});
Mastra supports both tool formats, allowing you to mix and match as needed.