Dynamic Tools
Dynamic tools adapt their behavior and capabilities at runtime based on contextual input. Instead of relying on fixed configurations, they adjust to users, environments, or scenarios, enabling a single agent to serve personalized, context-aware responses.
Creating an tool
Create a tool that fetches exchange rate data using a dynamic value provided via runtimeContext.
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export const getExchangeRatesTool = createTool({
id: "get-exchange-rates-tool",
description: "Gets exchanges rates for a currency",
inputSchema: z.null(),
outputSchema: z.object({
base: z.string(),
date: z.string(),
rates: z.record(z.number()),
}),
execute: async ({ runtimeContext }) => {
const currency = runtimeContext.get("currency");
const response = await fetch(
`https://api.frankfurter.dev/v1/latest?base=${currency}`,
);
const { base, date, rates } = await response.json();
return { base, date, rates };
},
});
See createTool() for a full list of configuration options.
Example usage
Set RuntimeContext using set(), then call execute() passing in the runtimeContext.
import { RuntimeContext } from "@mastra/core/runtime-context";
import { getExchangeRatesTool } from "../src/mastra/tools/example-exchange-rates-tool";
const runtimeContext = new RuntimeContext();
runtimeContext.set("currency", "USD");
const result = await getExchangeRatesTool.execute({
context: null,
runtimeContext,
});
console.log(result);