Skip to main content

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.

Usage example

src/mastra/tools/reverse-tool.ts
import { createTool } from "@mastra/core/tools";
import { z } from "zod";

export const tool = createTool({
id: "test-tool",
description: "Reverse the input string",
inputSchema: z.object({
input: z.string(),
}),
outputSchema: z.object({
output: z.string(),
}),
execute: async (inputData) => {
const reversed = inputData.input.split("").reverse().join("");

return {
output: reversed,
};
},
});

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 two parameters: the validated input data (first parameter) and an optional execution context object (second parameter) containing `requestContext`, `tracingContext`, `abortSignal`, and other execution metadata.

input:

z.infer<TInput>
The validated input data based on inputSchema

context?:

ToolExecutionContext
Optional execution context containing metadata

Returns

The createTool() function returns a Tool object.

Tool:

object
An object representing the defined tool, ready to be added to an agent.

On this page