Tool Runtime Context
Mastra provides RuntimeContext
, a dependency injection system that lets you configure tools with runtime variables. If you find yourself creating multiple tools that perform similar tasks, runtime context allows you to consolidate them into a single, more flexible tool.
Overview
The dependency injection system allows you to:
- Pass runtime configuration variables to tools through a type-safe
runtimeContext
. - Access these variables within tool execution context.
- Modify tool behavior without changing the underlying code.
- Share configuration across multiple tools within the same agent.
Note: RuntimeContext
is primarily used for passing data into tool
executions. It’s distinct from agent memory, which handles conversation
history and state persistence across multiple calls.
Accessing runtimeContext
in tools
Tools can access the same runtimeContext
used by their parent agent, allowing them to adjust behavior based on runtime configuration. In this example, the temperature-unit
is retrieved within the tool’s execute
function to ensure consistent formatting with the agent’s instructions.
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
type WeatherRuntimeContext = {
"temperature-unit": "celsius" | "fahrenheit";
};
export const testWeatherTool = createTool({
id: "getWeather",
description: "Get the current weather for a location",
inputSchema: z.object({
location: z.string().describe("The location to get weather for")
}),
execute: async ({ context, runtimeContext }) => {
const temperatureUnit = runtimeContext.get("temperature-unit") as WeatherRuntimeContext["temperature-unit"];
const weather = await fetchWeather(context.location, temperatureUnit);
return { result: weather };
}
});
async function fetchWeather(location: string, temperatureUnit: WeatherRuntimeContext["temperature-unit"]) {
// ...
}