Defining Steps in a Workflow

When you build a workflow, you typically break down operations into smaller tasks that can be linked and reused. Steps provide a structured way to manage these tasks by defining inputs, outputs, and execution logic.

The code below shows how to define these steps inline or separately.

Inline Step Creation

You can create steps directly within your workflow using .step() and .then(). This code shows how to define, link, and execute two steps in sequence.

src/mastra/workflows/index.ts
import { Step, Workflow } from "@mastra/core";
import { z } from "zod";
 
export const myWorkflow = new Workflow({
  name: "my-workflow",
  triggerSchema: z.object({
    inputValue: z.number(),
  }),
});
 
myWorkflow
  .step(
    new Step({
      id: "stepOne",
      outputSchema: z.object({
        doubledValue: z.number(),
      }),
      execute: async ({ context: { machineContext } }) => ({
        doubledValue: machineContext.triggerData.inputValue * 2,
      }),
    }),
  )
  .then(
    new Step({
      id: "stepTwo",
      outputSchema: z.object({
        incrementedValue: z.number(),
      }),
      execute: async ({ context: { machineContext } }) => ({
        incrementedValue: machineContext.stepResults.stepOne.payload.doubledValue + 1,
      }),
    }),
  );

Creating Steps Separately

If you prefer to manage your step logic in separate entities, you can define steps outside and then add them to your workflow. This code shows how to define steps independently and link them afterward.

src/mastra/workflows/index.ts
import { Step, Workflow } from "@mastra/core";
import { z } from "zod";
 
// Define steps separately
const stepOne = new Step({
  id: "stepOne",
  outputSchema: z.object({
    doubledValue: z.number(),
  }),
  execute: async ({ context: { machineContext } }) => ({
    doubledValue: machineContext.triggerData.inputValue * 2,
  }),
});
 
const stepTwo = new Step({
  id: "stepTwo",
  outputSchema: z.object({
    incrementedValue: z.number(),
  }),
  execute: async ({ context: { machineContext } }) => ({
    incrementedValue: machineContext.stepResults.stepOne.payload.doubledValue + 1,
  }),
});
 
// Build the workflow
const myWorkflow = new Workflow({
  name: "my-workflow",
  triggerSchema: z.object({
    inputValue: z.number(),
  }),
});
 
myWorkflow.step(stepOne).then(stepTwo);
myWorkflow.commit();

MIT 2025 © Nextra.