mastra-ai/mastra · error

run-workflow requires a Mastra context.

Error message

run-workflow requires a Mastra context.

What it means

run-workflow starts a workflow run via `mastra.getWorkflow(...).start(...)`, forwarding the caller's requestContext and an ephemeral memory scope. It throws this Error when `mastra` is missing from the runtime context, since no workflow can be resolved or started without the instance.

Source

Thrown at mastracode/sdk/src/tools/workflows/run-workflow.ts:25

import { z } from 'zod';
import { runWorkflow } from '../../workflows/service.js';
import { withEphemeralMemory } from './ephemeral-memory.js';

export const runWorkflowTool = createTool({
  id: 'run-workflow',
  description:
    'Run a saved workflow by id with the provided input data. Returns the run result inline. Use when the user asks you to "run X", "execute X", or asks for the outcome of a saved workflow.',
  inputSchema: z.object({
    workflowId: z.string().describe('The id of the saved workflow to run.'),
    inputData: z.any().describe('The input object the workflow consumes. Must match the workflow inputSchema.'),
  }),
  outputSchema: z.object({
    status: z.string(),
    result: z.any().optional(),
    error: z.any().optional(),
  }),
  execute: async ({ workflowId, inputData }, { mastra, requestContext }) => {
    if (!mastra) throw new Error('run-workflow requires a Mastra context.');
    // Forward the caller's requestContext so agent steps can resolve dynamic
    // model/tool bindings from session state, and swap the caller's chat
    // memory scope for a fresh isolated one for the duration of the run so
    // the workflow's agent step doesn't write into (or read from) the parent
    // chat thread. See ephemeral-memory.ts.
    return withEphemeralMemory(requestContext, async ephemeralRequestContext => {
      const result = await runWorkflow(mastra as Mastra, workflowId, inputData, ephemeralRequestContext);
      if (result.status === 'tripwire' && result.tripwire) {
        return {
          status: result.status,
          error: `Tripwire: ${result.tripwire.reason ?? 'unknown'} (processor: ${result.tripwire.processorId ?? 'unknown'})`,
        };
      }
      let errorText: string | undefined;
      if (result.error instanceof Error) {
        errorText = `${result.error.name}: ${result.error.message}`;
        const cause = (result.error as { cause?: unknown }).cause;
        if (cause) {

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Run the tool through a Mastra agent/server/Studio so `mastra` is injected into the context.
  2. For manual invocations, pass `{ mastra, requestContext }` when calling execute.
  3. Register the target workflowId on the Mastra instance so it can be resolved after the guard passes.
  4. In tests, provide a real Mastra instance (with the workflow registered) in the executionContext.

Example fix

// before
await runWorkflowTool.execute({ workflowId: 'deploy', inputData: {} }, { requestContext });
// after
const mastra = new Mastra({ workflows: { deploy } });
await runWorkflowTool.execute({ workflowId: 'deploy', inputData: {} }, { mastra, requestContext });
Defensive patterns

Strategy: validation

Validate before calling

import { Mastra } from '@mastra/core';
function assertRunnableContext(ctx: unknown): asserts ctx is { mastra: Mastra; requestContext: RequestContext } {
  if (
    typeof ctx !== 'object' ||
    ctx === null ||
    !((ctx as any).mastra instanceof Mastra) ||
    !(ctx as any).requestContext
  ) {
    throw new Error('run-workflow needs { mastra, requestContext } in its execution context.');
  }
}

Type guard

function isRunContext(ctx: unknown): ctx is { mastra: Mastra; requestContext: RequestContext } {
  return (
    typeof ctx === 'object' &&
    ctx !== null &&
    (ctx as any).mastra instanceof Mastra &&
    typeof (ctx as any).requestContext === 'object'
  );
}

Try / catch

try {
  const { status, result, error } = await runWorkflowTool.execute({ workflowId, inputData }, ctx);
} catch (err) {
  if (err instanceof Error && err.message.includes('requires a Mastra context')) {
    // initialize Mastra (with the workflow registered) and retry inside its runtime
  } else {
    // surface workflow-level failure from outputSchema's error field or rethrow
    throw err;
  }
}

Prevention

When it happens

Trigger: Executing run-workflow with an executionContext whose `mastra` is undefined — direct execute calls, custom harnesses that skip Mastra context injection, or tests mocking only `requestContext`.

Common situations: Automations invoking SDK tools outside Mastra's runtime; test scaffolds with incomplete executionContext; calling the tool before the Mastra instance (and its workflows) are constructed.

Related errors


AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30). Data as JSON: /api/errors/18376cca0a7cec4f. Report an issue: GitHub.