Skip to Content

Defining Steps in a Workflow (Legacy)

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 { Mastra } from "@mastra/core"; import { LegacyStep, LegacyWorkflow } from '@mastra/core/workflows/legacy' import { z } from "zod"; export const myWorkflow = new LegacyWorkflow({ name: "my-workflow", triggerSchema: z.object({ inputValue: z.number(), }), }); myWorkflow .step( new LegacyStep({ id: "stepOne", outputSchema: z.object({ doubledValue: z.number(), }), execute: async ({ context }) => ({ doubledValue: context.triggerData.inputValue * 2, }), }), ) .then( new LegacyStep({ id: "stepTwo", outputSchema: z.object({ incrementedValue: z.number(), }), execute: async ({ context }) => { if (context.steps.stepOne.status !== "success") { return { incrementedValue: 0 }; } return { incrementedValue: context.steps.stepOne.output.doubledValue + 1, }; }, }), ) .commit(); // Register the workflow with Mastra export const mastra = new Mastra({ legacy_workflows: { myWorkflow }, });

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 { Mastra } from "@mastra/core"; import { LegacyStep, LegacyWorkflow } from '@mastra/core/workflows/legacy' import { z } from "zod"; // Define steps separately const stepOne = new LegacyStep({ id: "stepOne", outputSchema: z.object({ doubledValue: z.number(), }), execute: async ({ context }) => ({ doubledValue: context.triggerData.inputValue * 2, }), }); const stepTwo = new LegacyStep({ id: "stepTwo", outputSchema: z.object({ incrementedValue: z.number(), }), execute: async ({ context }) => { if (context.steps.stepOne.status !== "success") { return { incrementedValue: 0 }; } return { incrementedValue: context.steps.stepOne.output.doubledValue + 1 }; }, }); // Build the workflow const myWorkflow = new LegacyWorkflow({ name: "my-workflow", triggerSchema: z.object({ inputValue: z.number(), }), }); myWorkflow.step(stepOne).then(stepTwo); myWorkflow.commit(); // Register the workflow with Mastra export const mastra = new Mastra({ legacy_workflows: { myWorkflow }, });