{"record":{"id":"18376cca0a7cec4f","repo":"mastra-ai/mastra","slug":"run-workflow-requires-a-mastra-context","errorCode":null,"errorMessage":"run-workflow requires a Mastra context.","messagePattern":"run-workflow requires a Mastra context\\.","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"mastracode/sdk/src/tools/workflows/run-workflow.ts","lineNumber":25,"sourceCode":"import { z } from 'zod';\nimport { runWorkflow } from '../../workflows/service.js';\nimport { withEphemeralMemory } from './ephemeral-memory.js';\n\nexport const runWorkflowTool = createTool({\n  id: 'run-workflow',\n  description:\n    '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.',\n  inputSchema: z.object({\n    workflowId: z.string().describe('The id of the saved workflow to run.'),\n    inputData: z.any().describe('The input object the workflow consumes. Must match the workflow inputSchema.'),\n  }),\n  outputSchema: z.object({\n    status: z.string(),\n    result: z.any().optional(),\n    error: z.any().optional(),\n  }),\n  execute: async ({ workflowId, inputData }, { mastra, requestContext }) => {\n    if (!mastra) throw new Error('run-workflow requires a Mastra context.');\n    // Forward the caller's requestContext so agent steps can resolve dynamic\n    // model/tool bindings from session state, and swap the caller's chat\n    // memory scope for a fresh isolated one for the duration of the run so\n    // the workflow's agent step doesn't write into (or read from) the parent\n    // chat thread. See ephemeral-memory.ts.\n    return withEphemeralMemory(requestContext, async ephemeralRequestContext => {\n      const result = await runWorkflow(mastra as Mastra, workflowId, inputData, ephemeralRequestContext);\n      if (result.status === 'tripwire' && result.tripwire) {\n        return {\n          status: result.status,\n          error: `Tripwire: ${result.tripwire.reason ?? 'unknown'} (processor: ${result.tripwire.processorId ?? 'unknown'})`,\n        };\n      }\n      let errorText: string | undefined;\n      if (result.error instanceof Error) {\n        errorText = `${result.error.name}: ${result.error.message}`;\n        const cause = (result.error as { cause?: unknown }).cause;\n        if (cause) {","sourceCodeStart":7,"sourceCodeEnd":43,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/mastracode/sdk/src/tools/workflows/run-workflow.ts#L7-L43","documentation":"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.","triggerScenarios":"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`.","commonSituations":"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.","solutions":["Run the tool through a Mastra agent/server/Studio so `mastra` is injected into the context.","For manual invocations, pass `{ mastra, requestContext }` when calling execute.","Register the target workflowId on the Mastra instance so it can be resolved after the guard passes.","In tests, provide a real Mastra instance (with the workflow registered) in the executionContext."],"exampleFix":"// before\nawait runWorkflowTool.execute({ workflowId: 'deploy', inputData: {} }, { requestContext });\n// after\nconst mastra = new Mastra({ workflows: { deploy } });\nawait runWorkflowTool.execute({ workflowId: 'deploy', inputData: {} }, { mastra, requestContext });","handlingStrategy":"validation","validationCode":"import { Mastra } from '@mastra/core';\nfunction assertRunnableContext(ctx: unknown): asserts ctx is { mastra: Mastra; requestContext: RequestContext } {\n  if (\n    typeof ctx !== 'object' ||\n    ctx === null ||\n    !((ctx as any).mastra instanceof Mastra) ||\n    !(ctx as any).requestContext\n  ) {\n    throw new Error('run-workflow needs { mastra, requestContext } in its execution context.');\n  }\n}","typeGuard":"function isRunContext(ctx: unknown): ctx is { mastra: Mastra; requestContext: RequestContext } {\n  return (\n    typeof ctx === 'object' &&\n    ctx !== null &&\n    (ctx as any).mastra instanceof Mastra &&\n    typeof (ctx as any).requestContext === 'object'\n  );\n}","tryCatchPattern":"try {\n  const { status, result, error } = await runWorkflowTool.execute({ workflowId, inputData }, ctx);\n} catch (err) {\n  if (err instanceof Error && err.message.includes('requires a Mastra context')) {\n    // initialize Mastra (with the workflow registered) and retry inside its runtime\n  } else {\n    // surface workflow-level failure from outputSchema's error field or rethrow\n    throw err;\n  }\n}","preventionTips":["Invoke run-workflow through the Mastra agent/server so context injection (including requestContext forwarding and ephemeral memory) is handled for you.","Register every workflowId you plan to run on the Mastra instance.","Provide both `mastra` and `requestContext` when calling execute manually — the ephemeral-memory wrapper depends on requestContext.","Gate custom runners behind a context type guard before dispatching any tool call."],"tags":["mastra","configuration","runtime-context","workflows"],"backgroundTag":"missing-mastra-context","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}