---
title: "Reference: Workflow Class | Workflows"
description: Documentation for the `Workflow` class in Mastra, which enables you to create state machines for complex sequences of operations with conditional branching and data validation.
packages:
  - "@mastra/core"
---

# Workflow Class

The `Workflow` class enables you to create state machines for complex sequences of operations with conditional branching and data validation.

## Usage example

```typescript title="src/mastra/workflows/test-workflow.ts"
import { createWorkflow } from "@mastra/core/workflows";
import { z } from "zod";

export const workflow = createWorkflow({
  id: "test-workflow",
  inputSchema: z.object({
    value: z.string(),
  }),
  outputSchema: z.object({
    value: z.string(),
  }),
});
```

## Constructor parameters

<PropertiesTable
  content={[
    {
      name: "id",
      type: "string",
      description: "Unique identifier for the workflow",
    },
    {
      name: "inputSchema",
      type: "z.ZodType<any>",
      description: "Zod schema defining the input structure for the workflow",
    },
    {
      name: "outputSchema",
      type: "z.ZodType<any>",
      description: "Zod schema defining the output structure for the workflow",
    },
    {
      name: "stateSchema",
      type: "z.ZodObject<any>",
      description:
        "Optional Zod schema for the workflow state. Automatically injected when using Mastra's state system. If not specified, type is 'any'.",
      isOptional: true,
    },
    {
      name: "options",
      type: "WorkflowOptions",
      description: "Optional options for the workflow",
      isOptional: true,
    },
  ]}
/>

### WorkflowOptions

<PropertiesTable
  content={[
    {
      name: "tracingPolicy",
      type: "TracingPolicy",
      description: "Optional tracing policy for the workflow",
      isOptional: true,
    },
    {
      name: "validateInputs",
      type: "boolean",
      description:
        "Optional flag to determine whether to validate the workflow inputs. This also applies default values from zodSchemas on the workflow/step input/resume data. If input/resume data validation fails on start/resume, the workflow will not start/resume, it throws an error instead. If input data validation fails on a step execution, the step fails, causing the workflow to fail and the error is returned.",
      isOptional: true,
      defaultValue: "true",
    },
    {
      name: "shouldPersistSnapshot",
      type: "(params: { stepResults: Record<string, StepResult<any, any, any, any>>; workflowStatus: WorkflowRunStatus }) => boolean",
      description:
        "Optional flag to determine whether to persist the workflow snapshot",
      isOptional: true,
      defaultValue: "() => true",
    },
    {
      name: "onFinish",
      type: "(result: WorkflowFinishCallbackResult) => void | Promise<void>",
      description:
        "Callback invoked when workflow completes with any status (success, failed, suspended, tripwire). Receives the workflow result including status, output, error, and step results. Errors thrown in this callback are caught and logged, not propagated.",
      isOptional: true,
    },
    {
      name: "onError",
      type: "(errorInfo: WorkflowErrorCallbackInfo) => void | Promise<void>",
      description:
        "Callback invoked only when workflow fails (failed or tripwire status). Receives error details and step results. Errors thrown in this callback are caught and logged, not propagated.",
      isOptional: true,
    },
  ]}
/>

### WorkflowFinishCallbackResult

The result object passed to `onFinish` callbacks.

<PropertiesTable
  content={[
    {
      name: "status",
      type: "WorkflowRunStatus",
      description: "The workflow status: 'success', 'failed', 'suspended', or 'tripwire'",
    },
    {
      name: "result",
      type: "any",
      description: "The workflow output (when status is 'success')",
      isOptional: true,
    },
    {
      name: "error",
      type: "SerializedError",
      description: "Error details (when status is 'failed')",
      isOptional: true,
    },
    {
      name: "steps",
      type: "Record<string, StepResult>",
      description: "Individual step results with their status and output",
    },
    {
      name: "tripwire",
      type: "StepTripwireInfo",
      description: "Tripwire information (when status is 'tripwire')",
      isOptional: true,
    },
    {
      name: "runId",
      type: "string",
      description: "The unique identifier for this workflow run",
    },
    {
      name: "workflowId",
      type: "string",
      description: "The workflow's identifier",
    },
    {
      name: "resourceId",
      type: "string",
      description: "Optional resource identifier (if provided when creating the run)",
      isOptional: true,
    },
    {
      name: "getInitData",
      type: "() => any",
      description: "Function that returns the initial input data passed to the workflow",
    },
    {
      name: "mastra",
      type: "Mastra",
      description: "The Mastra instance (if workflow is registered with Mastra)",
      isOptional: true,
    },
    {
      name: "requestContext",
      type: "RequestContext",
      description: "Request-scoped context data",
    },
    {
      name: "logger",
      type: "IMastraLogger",
      description: "The workflow's logger instance",
    },
    {
      name: "state",
      type: "Record<string, any>",
      description: "The workflow's current state object",
    },
  ]}
/>

### WorkflowErrorCallbackInfo

The error info object passed to `onError` callbacks.

<PropertiesTable
  content={[
    {
      name: "status",
      type: "'failed' | 'tripwire'",
      description: "The workflow status (either 'failed' or 'tripwire')",
    },
    {
      name: "error",
      type: "SerializedError",
      description: "Error details",
      isOptional: true,
    },
    {
      name: "steps",
      type: "Record<string, StepResult>",
      description: "Individual step results with their status and output",
    },
    {
      name: "tripwire",
      type: "StepTripwireInfo",
      description: "Tripwire information (when status is 'tripwire')",
      isOptional: true,
    },
    {
      name: "runId",
      type: "string",
      description: "The unique identifier for this workflow run",
    },
    {
      name: "workflowId",
      type: "string",
      description: "The workflow's identifier",
    },
    {
      name: "resourceId",
      type: "string",
      description: "Optional resource identifier (if provided when creating the run)",
      isOptional: true,
    },
    {
      name: "getInitData",
      type: "() => any",
      description: "Function that returns the initial input data passed to the workflow",
    },
    {
      name: "mastra",
      type: "Mastra",
      description: "The Mastra instance (if workflow is registered with Mastra)",
      isOptional: true,
    },
    {
      name: "requestContext",
      type: "RequestContext",
      description: "Request-scoped context data",
    },
    {
      name: "logger",
      type: "IMastraLogger",
      description: "The workflow's logger instance",
    },
    {
      name: "state",
      type: "Record<string, any>",
      description: "The workflow's current state object",
    },
  ]}
/>

## Running with initial state

When starting a workflow run, you can pass `initialState` to set the starting values for the workflow's state:

```typescript
const run = await workflow.createRun();

const result = await run.start({
  inputData: { value: "hello" },
  initialState: {
    counter: 0,
    items: [],
  },
});
```

The `initialState` object should match the structure defined in the workflow's `stateSchema`. See [Workflow State](/docs/v1/workflows/workflow-state) for more details.

## Workflow status

A workflow's `status` indicates its current execution state. The possible values are:

<PropertiesTable
  content={[
    {
      name: "success",
      type: "string",
      description:
        "All steps finished executing successfully, with a valid result output",
    },
    {
      name: "failed",
      type: "string",
      description:
        "Workflow encountered an error during execution, with error details available",
    },
    {
      name: "suspended",
      type: "string",
      description:
        "Workflow execution is paused waiting for resume, with suspended step information",
    },
    {
      name: "tripwire",
      type: "string",
      description:
        "Workflow was terminated by a processor tripwire. This occurs when an agent step within the workflow triggers a tripwire (e.g., content was blocked by a guardrail). The tripwire information is available on the result.",
    },
  ]}
/>

### Handling tripwire status

When a workflow contains an agent step that triggers a tripwire, the workflow returns with `status: 'tripwire'` and includes tripwire details:

```typescript
const run = await workflow.createRun();
const result = await run.start({ inputData: { message: "Hello" } });

if (result.status === "tripwire") {
  console.log("Workflow terminated by tripwire:", result.tripwire?.reason);
  console.log("Processor ID:", result.tripwire?.processorId);
  console.log("Retry requested:", result.tripwire?.retry);
}
```

This is distinct from `status: 'failed'` which indicates an unexpected error. A tripwire status means a processor intentionally stopped execution (e.g., for content moderation).

## Related

- [Step Class](./step)
- [Workflow State](/docs/v1/workflows/workflow-state)
- [Control flow](/docs/v1/workflows/control-flow)
