createTool()

The createTool() function creates typed tools that can be executed by agents or workflows. Tools have built-in schema validation, execution context, and integration with the Mastra ecosystem.

Overview

Tools are a fundamental building block in Mastra that allow agents to interact with external systems, perform computations, and access data. Each tool has:

  • A unique identifier
  • A description that helps the AI understand when and how to use the tool
  • Optional input and output schemas for validation
  • An execution function that implements the tool’s logic

Example Usage

src/tools/stock-tools.ts
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
 
// Helper function to fetch stock data
const getStockPrice = async (symbol: string) => {
  const response = await fetch(
    `https://mastra-stock-data.vercel.app/api/stock-data?symbol=${symbol}`
  );
  const data = await response.json();
  return data.prices["4. close"];
};
 
// Create a tool to get stock prices
export const stockPriceTool = createTool({
  id: "getStockPrice",
  description: "Fetches the current stock price for a given ticker symbol",
  inputSchema: z.object({
    symbol: z.string().describe("The stock ticker symbol (e.g., AAPL, MSFT)")
  }),
  outputSchema: z.object({
    symbol: z.string(),
    price: z.number(),
    currency: z.string(),
    timestamp: z.string()
  }),
  execute: async ({ context }) => {
    const price = await getStockPrice(context.symbol);
    
    return {
      symbol: context.symbol,
      price: parseFloat(price),
      currency: "USD",
      timestamp: new Date().toISOString()
    };
  }
});
 
// Create a tool that uses the thread context
export const threadInfoTool = createTool({
  id: "getThreadInfo",
  description: "Returns information about the current conversation thread",
  inputSchema: z.object({
    includeResource: z.boolean().optional().default(false)
  }),
  execute: async ({ context, threadId, resourceId }) => {
    return {
      threadId,
      resourceId: context.includeResource ? resourceId : undefined,
      timestamp: new Date().toISOString()
    };
  }
});

API Reference

Parameters

createTool() accepts a single object with the following properties:

id:

string
Unique identifier for the tool. This should be descriptive of the tool's function.

description:

string
Detailed description of what the tool does, when it should be used, and what inputs it requires. This helps the AI understand how to use the tool effectively.

execute:

(context: ToolExecutionContext, options?: any) => Promise<any>
Async function that implements the tool's logic. Receives the execution context and optional configuration.
ToolExecutionContext

context:

object
The validated input data that matches the inputSchema

threadId?:

string
Identifier for the conversation thread, if available

resourceId?:

string
Identifier for the user or resource interacting with the tool

mastra?:

Mastra
Reference to the Mastra instance, if available
ToolOptions

toolCallId:

string
The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.

messages:

CoreMessage[]
Messages that were sent to the language model to initiate the response that contained the tool call. The messages do not include the system prompt nor the assistant response that contained the tool call.

abortSignal?:

AbortSignal
An optional abort signal that indicates that the overall operation should be aborted.

inputSchema:

ZodSchema
Zod schema that defines and validates the tool's input parameters. If not provided, the tool will accept any input.

outputSchema:

ZodSchema
Zod schema that defines and validates the tool's output. Helps ensure the tool returns data in the expected format.

Returns

Tool:

Tool<TSchemaIn, TSchemaOut>
A Tool instance that can be used with agents, workflows, or directly executed.
Tool

id:

string
The tool's unique identifier

description:

string
Description of the tool's functionality

inputSchema:

ZodSchema | undefined
Schema for validating inputs

outputSchema:

ZodSchema | undefined
Schema for validating outputs

execute:

Function
The tool's execution function

Type Safety

The createTool() function provides full type safety through TypeScript generics:

  • Input types are inferred from the inputSchema
  • Output types are inferred from the outputSchema
  • The execution context is properly typed based on the input schema

This ensures that your tools are type-safe throughout your application.

Best Practices

  1. Descriptive IDs: Use clear, action-oriented IDs like getWeatherForecast or searchDatabase
  2. Detailed Descriptions: Provide comprehensive descriptions that explain when and how to use the tool
  3. Input Validation: Use Zod schemas to validate inputs and provide helpful error messages
  4. Error Handling: Implement proper error handling in your execute function
  5. Idempotency: When possible, make your tools idempotent (same input always produces same output)
  6. Performance: Keep tools lightweight and fast to execute