createTool()
The createTool()
function is used to define custom tools that your Mastra agents can execute. Tools extend an agent’s capabilities by allowing it to interact with external systems, perform calculations, or access specific data.
Basic Usage
Here is a basic example of creating a tool that fetches weather information:
src/mastra/tools/weatherInfo.ts
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export const weatherInfo = createTool({
id: "Get Weather Information",
inputSchema: z.object({
city: z.string(),
}),
description: `Fetches the current weather information for a given city`,
execute: async ({ context: { city } }) => {
// Tool logic here (e.g., API call)
console.log("Using tool to fetch weather information for", city);
return { temperature: 20, conditions: "Sunny" }; // Example return
},
});
Parameters
The createTool()
function accepts an object with the following parameters:
id:
string
A unique identifier for the tool.
description:
string
A description of what the tool does. This is used by the agent to decide when to use the tool.
inputSchema?:
Zod schema
A Zod schema defining the expected input parameters for the tool's `execute` function.
outputSchema?:
Zod schema
A Zod schema defining the expected output structure of the tool's `execute` function.
execute:
function
The function that contains the tool's logic. It receives an object with `context` (the parsed input based on `inputSchema`), `runtimeContext`, and an object containing `abortSignal`.
Returns
The createTool()
function returns a Tool
object.
Tool:
object
An object representing the defined tool, ready to be added to an agent.
Tool Details
The Tool
object returned by createTool()
has the following key properties:
- ID: The unique identifier provided in the
id
parameter. - Description: The description provided in the
description
parameter. - Parameters: Derived from the
inputSchema
, defining the structure of inputs the tool expects. - Execute Function: The logic defined in the
execute
parameter, which is called when the agent decides to use the tool.