Workflows
Relevant source files
The following files were used as context for generating this wiki page:- packages/agent-builder/src/workflows/workflow-builder/prompts.ts
- packages/agent-builder/src/workflows/template-builder/template-builder.ts
- e2e-tests/kitchen-sink/template/src/mastra/workflows/complex-workflow.ts
- templates/template-deep-research/src/mastra/workflows/researchWorkflow.ts
- templates/template-pdf-questions/src/mastra/workflows/generate-questions-from-pdf-workflow.ts
- packages/server/src/server/handlers/workflows.test.ts
- examples/openapi-spec-writer/src/mastra/workflows/index.ts
- packages/agent-builder/src/workflows/workflow-builder/workflow-builder.ts
Workflows in Mastra provide a structured way to orchestrate multi-step processes, chain AI and non-AI operations, and manage complex data flows. They are built by composing individual, reusable Steps into a sequence of operations. The system supports sequential, parallel, conditional, and loop-based execution, as well as human-in-the-loop interactions through suspend and resume capabilities.
Workflows are defined using a fluent API, starting with createWorkflow and chaining steps using methods like .then(), .parallel(), and .branch(). Each step is created with createStep, defining its own typed inputs, outputs, and execution logic. This modular approach allows for building robust, maintainable, and observable automated processes.
Core Concepts
The foundation of Mastra Workflows is built upon two main factory functions: createWorkflow and createStep. Zod schemas are used extensively for strict input/output typing and validation.
Sources: packages/agent-builder/src/workflows/workflow-builder/prompts.ts:7-12
createWorkflow()
This is the main factory function for creating a new workflow instance. It takes a configuration object that defines the workflow's identity and its data contract.
Sources: packages/agent-builder/src/workflows/workflow-builder/prompts.ts:8
| Parameter | Type | Description | Required |
|---|---|---|---|
id | string | A unique identifier for the workflow. Kebab-case is recommended. | Yes |
description | string | An optional but recommended description of the workflow's purpose. | No |
inputSchema | Zod schema | A Zod schema defining the shape of the workflow's initial input. | Yes |
outputSchema | Zod schema | A Zod schema defining the shape of the workflow's final output. | Yes |
steps | Step[] | An array of step instances used in the workflow. | No |
Sources: packages/agent-builder/src/workflows/workflow-builder/prompts.ts:14-19, packages/server/src/server/handlers/workflows.test.ts:40-47
createStep()
This function creates an individual, executable unit of work within a workflow. Steps are self-contained and define their own logic and data schemas.
Sources: packages/agent-builder/src/workflows/workflow-builder/prompts.ts:8
| Parameter | Type | Description | Required |
|---|---|---|---|
id | string | A unique identifier for the step. | Yes |
description | string | A recommended description for clarity. | No |
inputSchema | Zod schema | A Zod schema for validating the step's input. | Yes |
outputSchema | Zod schema | A Zod schema for validating the step's output. | Yes |
execute | async function | The core logic of the step. | Yes |
suspendSchema | Zod schema | Schema for the payload when the workflow is suspended at this step. | No |
resumeSchema | Zod schema | Schema for the data required to resume the workflow from this step. | No |
Sources: packages/agent-builder/src/workflows/workflow-builder/prompts.ts:25-33, e2e-tests/kitchen-sink/template/src/mastra/workflows/complex-workflow.ts:63-70
.commit()
After defining all the steps and their sequence, the .commit() method must be called on the workflow instance. This finalizes the workflow definition and makes it executable.
Sources: packages/agent-builder/src/workflows/workflow-builder/prompts.ts:20
Basic Structure
The following diagram illustrates the relationship between createWorkflow and createStep.
Workflow Composition and Control Flow
Workflows are composed by chaining steps. The framework provides several methods to control the flow of execution.
Control Flow Methods
| Method | Description |
|---|---|
.then(step) | Executes steps sequentially, one after another. |
.parallel([step1, step2]) | Runs an array of steps simultaneously. The workflow waits for all to complete before proceeding. |
.branch([[condition, step], ...]) | Executes different steps based on conditions. Conditions are evaluated sequentially. |
.dountil(step, condition) | Repeats a step until a condition function returns true. |
.map(transformFn) | Transforms data between steps, useful when output/input schemas do not align. |
Sources: packages/agent-builder/src/workflows/workflow-builder/prompts.ts:42-59
Example of a Complex Workflow
The complexWorkflow demonstrates several control flow mechanisms, including sequential, parallel, conditional, and loop execution, as well as data mapping and nested workflows.
This diagram shows the control flow of the complexWorkflow.
Step Execution
The logic of a step is defined in its execute function, which receives an object with several properties to interact with the workflow's state and context.
execute Function Parameters
| Parameter | Description |
|---|---|
inputData | The validated input for the step, matching its inputSchema. |
mastra | The Mastra instance, providing access to agents, tools, etc. |
getStepResult(step) | A function to retrieve the output from a previously executed step. |
getInitData() | A function to access the original data passed to the workflow run. |
requestContext | A runtime context for dependency injection. |
runCount | The number of times the current step has been executed (for retries). |
suspend | A function to pause the workflow and wait for external input. |
resumeData | Data provided when resuming a suspended workflow. |
Sources: packages/agent-builder/src/workflows/workflow-builder/prompts.ts:35-40, templates/template-deep-research/src/mastra/workflows/researchWorkflow.ts:25-37
Suspend & Resume for Human-in-the-Loop
Workflows can be paused to wait for human input or an external event. This is achieved using the suspend function within a step's execute method and defining suspendSchema and resumeSchema.
suspendSchema: Defines the data structure sent to the client when the workflow pauses.resumeSchema: Defines the data structure the client must provide to resume the workflow.suspend(): A function called withinexecuteto pause the workflow. It takes a payload matchingsuspendSchema.resumeData: When a workflow is resumed, this property in theexecutefunction's context contains the payload matchingresumeSchema.
Sources: packages/agent-builder/src/workflows/workflow-builder/prompts.ts:63-77, e2e-tests/kitchen-sink/template/src/mastra/workflows/complex-workflow.ts:61-78
The following sequence diagram illustrates the suspend/resume flow.
Project Organization
A strict folder structure is mandated for organizing workflows to ensure maintainability and clarity. Each workflow must reside in its own dedicated, kebab-cased folder.
Sources: packages/agent-builder/src/workflows/workflow-builder/prompts.ts:113-116
This diagram shows the mandatory file structure for a Mastra workflow.
types.ts: Contains all Zod schemas and TypeScript type definitions for the workflow.steps.ts: Defines all individual steps usingcreateStep().workflow.ts: Composes the steps into a final workflow usingcreateWorkflow()and exports it.index.ts: The rootindex.tsin theworkflowsdirectory should export all workflows to be registered with the Mastra instance.
Sources: packages/agent-builder/src/workflows/workflow-builder/prompts.ts:129-133
Workflow Execution
Workflows can be executed in several ways, supporting both asynchronous execution and real-time streaming.
workflow.createRun(): Creates a new run instance for a workflow.run.start({ inputData }): Starts the workflow execution and returns the final result once completed or suspended.run.streamVNext({ inputData }): Returns a stream of events for real-time monitoring of the workflow's progress.run.resume({ step, resumeData }): Resumes a suspended workflow run.
Sources: packages/agent-builder/src/workflows/workflow-builder/prompts.ts:161-171, packages/server/src/server/handlers/workflows.test.ts:358-372
Workflow Statuses
A workflow run can have one of the following statuses:
"success": The workflow completed successfully."suspended": The workflow is paused and awaiting input."failed": The workflow encountered an unrecoverable error.
Sources: packages/agent-builder/src/workflows/workflow-builder/prompts.ts:173-176
Advanced Features
Nested Workflows
A powerful feature of Mastra is the ability to use an entire workflow as a step within another workflow. This allows for creating complex, hierarchical, and reusable process compositions.
// e2e-tests/kitchen-sink/template/src/mastra/workflows/complex-workflow.ts:135
// Nested workflow
.then(nestedTextProcessor)
Sources: e2e-tests/kitchen-sink/template/src/mastra/workflows/complex-workflow.ts:135, packages/agent-builder/src/workflows/workflow-builder/prompts.ts:180-182
Integrating Agents and Tools
Agents and Tools can be seamlessly integrated into workflow steps.
- As a Step: An agent or a tool can be passed directly to a
.then()method if its interface is compatible. - Within
execute: Theexecutefunction can call an agent's.generate()method or a tool's.execute()method to perform a specific task.
// templates/template-pdf-questions/src/mastra/workflows/generate-questions-from-pdf-workflow.ts:30-36
const result = await pdfFetcherTool.execute(
{ pdfUrl },
{
mastra,
requestContext: requestContext || new RequestContext(),
},
);
Sources: templates/template-pdf-questions/src/mastra/workflows/generate-questions-from-pdf-workflow.ts:30-36, packages/agent-builder/src/workflows/workflow-builder/prompts.ts:90-110
Streaming and Transformers
Workflow execution can be streamed. The WorkflowStreamToAISDKTransformer can be used to transform the native Mastra workflow stream into a format compatible with the Vercel AI SDK, allowing for seamless frontend integration. This transformer handles events like workflow-start, workflow-step-start, workflow-step-output, and workflow-finish, converting them into AI SDK-compliant chunks.
Sources: client-sdks/ai-sdk/src/tests/transformers.test.ts:5