@Workflow
@Workflow declares a workflow: a set of steps, each of which runs a job. A step starts once the steps it depends on have finished, steps that don't depend on each other run in parallel, and a step's input can be built from the results of the steps before it. A client runs a workflow by name with the built-in execute_workflow tool, and a workflow can also start by itself: from a signed webhook, from an event, or on a cron schedule.
@Workflow(options)
class MyWorkflow {}
Reference
@Workflow(options)
Apply @Workflow to an empty class: everything is in the options. List the class in an app's workflows array, and the jobs its steps run in the app's jobs.
import { Workflow } from "@frontmcp/sdk";
@Workflow({
name: "nightly-report",
description: "Collect one day's tickets, find the SLA breaches, and write a report",
steps: [
{ id: "collect", jobName: "collect-tickets", input: { day: "2026-09-26" } },
{
id: "breaches",
jobName: "find-sla-breaches",
dependsOn: ["collect"],
input: (steps) => ({ tickets: steps.get("collect").outputs.tickets }),
},
{
id: "report",
jobName: "write-report",
dependsOn: ["collect", "breaches"],
input: (steps) => ({ tickets: steps.get("collect").outputs.tickets, breaches: steps.get("breaches").outputs.breaches }),
},
],
})
export class NightlyReport {}import { App } from "@frontmcp/sdk";
import { CollectTickets, FindSlaBreaches, WriteReport } from "./jobs";
import { NightlyReport } from "./nightly-report.workflow";
@App({
id: "help-desk",
name: "Help Desk",
jobs: [CollectTickets, FindSlaBreaches, WriteReport],
workflows: [NightlyReport],
})
export class HelpDeskApp {}See more examples below, and the whole server in the Nightly Ticket Report example.
Options
Required:
| Option | Type | Description |
|---|---|---|
name | string | What clients pass to execute_workflow. Unique within the server. If you also set id, the id replaces it. |
steps | WorkflowStep[] | The steps, at least one. See steps. Their order in the array doesn't matter: dependsOn decides the order they run in. |
Optional:
| Option | Type | Default | Description |
|---|---|---|---|
description | string | What the workflow does. list_workflows shows it. | |
id | string | name | A stable identifier. When set, it replaces name: clients and list_workflows use the id. |
maxConcurrency | number | 5 | How many steps may run at the same time. |
timeout | number | 600000 (10 minutes) | How long the whole workflow may run, in milliseconds. Checked each time a batch of steps finishes, so it doesn't interrupt a step that's running. |
inputSchema | object of Zod types | Describes the input a client passes to execute_workflow. Checked before a run starts; defaults are applied and undeclared keys are dropped. | |
outputSchema | an output schema | Accepted, and not used by FrontMCP. | |
trigger | "manual" | "webhook" | "event" | "schedule" | "manual" | What starts a run besides execute_workflow, which runs every workflow: nothing else, a signed HTTP webhook, an event, or the times of a cron expression. "schedule" is new in 1.12.0. |
webhook | { path?, secret?, methods?, maxBodyBytes? } | Required secret for a webhook trigger; see triggers. | |
event | string | the workflow name | Event to listen for with trigger: "event". Refused with another trigger. |
schedule | { cron, timezone?, input? } | When a trigger: "schedule" workflow runs; see schedule options. Refused with another trigger. New in 1.12.0. | |
tags | string[] | [] | Labels to filter list_workflows by. |
labels | Record<string, string> | {} | Key-value labels to filter list_workflows by. |
hideFromDiscovery | boolean | false | Leave the workflow out of list_workflows. It still runs by name. |
permissions | JobPermission[] | none: anyone may run it | Who may run and list the workflow. The rules work as for jobs. |
Workflow triggers
A trigger: "webhook" workflow serves webhook.path, default /workflows/webhook/{name}, for webhook.methods (default ["POST"]; accepts GET and POST). It requires a unique webhook.secret of at least 32 characters. webhook.maxBodyBytes defaults to 1048576.
Send a JSON object with X-FrontMCP-Timestamp (Unix seconds within five minutes of the server's clock) and X-FrontMCP-Signature: v1=<hex HMAC-SHA256 of "<timestamp>.<body>">, signing the body's bytes as sent. A GET signs an empty body and passes {} as input. A valid request starts a background run and answers 202 { runId, state: "pending" }. Bad, expired or replayed signatures answer 401; permission denials 403; invalid JSON or input 400; an oversized body 413; and a POST without application/json 415. Replay tracking is in memory per server process: each workflow remembers up to 10,000 signatures, each until its five minutes are up, and while it holds that many, a new request gets 429 {"error":"Too many requests; retry later"}. Changed in 1.12.1: before, the oldest signature was forgotten to make room, so it could be sent again. The trigger principal has role webhook:<workflow> for permission rules.
A trigger: "event" workflow listens for event (default its name) on the scope's channel event bus. Emit with this.scope.channelEventBus?.emit("user.signup", { userId }). The payload is the workflow input, and its caller has role event:<event>. Event workflows create the bus even without channels enabled. A refused run logs Event "<event>" did not start workflow "<name>": <reason>.
Published events arrive on the same bus. New in 1.12.0. A server that declares an event emits each occurrence it publishes on the bus under the event's name, with { eventId, name, timestamp, data } as the payload. A workflow with event: "ticket.closed" therefore starts for every publish of ticket.closed, from a tool, a duty or a worker, with the occurrence as its input: declare those four fields in its inputSchema. An occurrence published with an audience or a subscriptionId starts the workflow too: it runs inside the server as event:<event>, not as one of the subscribers the occurrence is for. events: { bridge: false } on the server turns this off. See starting from a published event.
A trigger: "schedule" workflow starts one background run at each time of schedule.cron, with schedule.input as its input, among all the processes of the server. Its caller has role schedule:<workflow>. New in 1.12.0. See schedule options.
Changed in 1.11.3: before, trigger and webhook registered nothing. Webhook options now require a valid secret and a route that does not collide with another route. Workflows registered at runtime support only manual triggers.
workflowTriggerOf(authInfo) returns the run’s WorkflowTriggerPrincipal, or undefined for an ordinary caller. The principal has kind ("webhook", "event" or "schedule"), name, role and toAuthInfo(). Both are exported from @frontmcp/sdk. In a step's job, this.auth of a run a trigger started is anonymous, with no roles: read the trigger with workflowTriggerOf(this.context.authInfo).
webhook options
| Option | Type | Default | Description |
|---|---|---|---|
path | string | /workflows/webhook/{name} | Route path; cannot collide with an existing or reserved route. |
methods | ("GET" | "POST")[] | ["POST"] | Allowed methods. |
secret | string | required | Unique secret of at least 32 characters, used to verify the request signature. |
maxBodyBytes | number | 1048576 | Largest JSON request body. |
schedule options
New in 1.12.0.
| Option | Type | Default | Description |
|---|---|---|---|
cron | string | required | A cron expression: minute hour day-of-month month day-of-week, or six fields with seconds first. The one @Duty({ cron }) takes, read the same way. |
timezone | string | "UTC" | The IANA time zone cron is read in, such as "Europe/Berlin". |
input | object | {} | The input of each scheduled run, checked against the workflow's inputSchema. |
- One run for each scheduled time, whatever the number of server processes. Each schedule has a lease that one process holds, as a duty has. With a top-level
redisthat is a Redis server, the lease is shared by every machine on that Redis, underfrontmcp:cluster:schedule:<info.name>:<workflow>, with both names percent-encoded. Without one, or with Vercel KV, it is shared by the processes of one machine that run from the same project root, in the SQLite fileduties.sqliteunder~/.frontmcporFRONTMCP_HOME, which needs@frontmcp/storage-sqlite. The lease lasts 60 seconds and is checked every 20: a process takes over from a holder that shut down at its next check, and from one that died within 80 seconds. - Nothing runs at startup. The lease store keeps the time the schedule was last taken. A process that gets the lease after a restart or a takeover starts one run if a scheduled time passed since, however many were missed, then continues on schedule.
- The run's id comes from the schedule and the scheduled time:
schedule-<time in ms>-<hash>, the same in every process that shares the lease. A scheduled time stays owed in the lease store until its run exists, so a process that takes over from a holder that died in between starts that run, unless the job store already holds a run with that id. That needs a job store the processes share, Redis or SQLite: with runs kept in memory, a takeover cannot see a run the dead process created. - Runs may overlap. A scheduled time starts its run even while the run of the last one is still going. Pick a cron with gaps longer than a run, or make the jobs safe to run side by side.
- The run runs as the role
schedule:<workflow name>, and nothing else. A workflow withcreateorexecuterules must allow that role, and so must each step job withexecuterules. Nobody owns the run: reading it withget_workflow_statusneeds an explicitreadrule, as for any run its caller did not start. - A run that can't start (a denial, an
inputthat doesn't match theinputSchema) is logged as a warning,The schedule did not start workflow "<name>": <reason>, and is not tried again: the next scheduled time starts its own run. - A lease store that can't be opened logs
The schedule of workflow "<name>" did not start: <cause>. The server keeps running and opens the store again every 20 seconds; the schedule starts once it opens. A schedule adds no check to/readyz. - Schedules need a long-lived process. They start once the server serves and stop when it shuts down. A serverless deployment logs
Scheduled workflows ("<name>") do not run in a serverless or edge deployment: they need a long-lived process, and FrontMCP's browser build starts none.
Steps
| Field | Type | Default | Description |
|---|---|---|---|
id | string | Required. Unique within the workflow. It names the step in dependsOn, in steps.get() and in the result's stepResults. | |
jobName | string | Required. The job to run: its name, or its id if it has one. | |
input | object, or (steps, input) => object | the workflow's input | The job's input. A function receives steps and builds the input from earlier steps' results. Its second argument is the parsed workflow input. |
dependsOn | string[] | [] | Steps that must finish first. A step with none starts right away. |
condition | (steps, input) => boolean | Checked when the step is ready to run. If it returns false or throws, the step is skipped. | |
continueOnError | boolean | false | If the step fails, run its dependents anyway, and don't fail the workflow because of it. |
retry | JobRetryConfig | the job's retry, or one attempt | Retries for this step, with the same fields as a job's retry. Without either policy, the step runs once. |
timeout | number | the job's timeout, else jobs.defaultTimeoutMs (5 minutes) | How long one attempt may run, in milliseconds, including its wait for admission. A step that runs longer fails immediately and aborts the job's this.signal (ctx.signal for function jobs). Code must honor that signal to stop work. Did("execute") is skipped, and finalize hooks see WorkflowJobTimeoutError. Changed in 1.9.5: before, an already-started attempt could finish as a success after the step timed out. |
The job still checks its input against its own inputSchema, so input that doesn't match fails the step.
steps.get(id)
In input and condition, steps.get(id) returns a finished step's result: { outputs, state }, where outputs is what the step's job returned and state is "completed", "failed" or "skipped". A failed or skipped step's outputs is {}.
For a step that hasn't finished, or doesn't exist, steps.get() throws: in input, the step fails, and in condition, it's skipped. So list every step whose results a step reads in its dependsOn.
How steps run
- Every step whose
dependsOnsteps have all finished (completed or skipped) is ready. Up tomaxConcurrencyof them start together, as one batch. - The next batch starts when the whole batch has finished.
- When a step fails, the steps that depend on it directly or indirectly are
skipped. Steps that don't depend on it keep running. - When every step has a result, the workflow is
failedif any step failed withoutcontinueOnError, andcompletedotherwise.
A step skipped by a condition counts as finished, so its dependents can run. A skip caused by failure propagates through all dependencies.
Each attempt of a step runs the job's jobs:execute-job flow, as execute_job does, so a JobHook sees it, and the job's own permissions are checked there against the caller who started the workflow. See Seeing each step's attempts. (New in 1.9.4: before, steps ran outside any flow.)
workflow(options)
The function form takes the same options and returns something to list in workflows:
import { workflow } from "@frontmcp/sdk";
export const remindAda = workflow({
name: "remind-ada",
steps: [{ id: "count", jobName: "count-open-tickets", input: { customer: "Ada" } }],
});
Built-in tools
When any app declares a job or a workflow, FrontMCP adds these tools to the server, next to the job tools:
| Tool | In tools/list | Arguments | Returns |
|---|---|---|---|
execute_workflow | Yes | name, input? (an object), background? (default false) | Without background: waits for every step, then { runId, state, result }, where result is { workflowName, state, stepResults, startedAt, completedAt } and stepResults maps each step's id to its { outputs, state }. With background: true: { runId, state: "pending" } at once. |
update_workflow | No; requires dynamic registration | name, steps?, description?, tags? | { success, workflowId }; replaces supplied fields on a dynamic workflow, subject to update permissions. |
get_workflow_status | Yes | runId | { runId, workflowName, state, stepResults, startedAt, completedAt? }. stepResults is always {}: read the steps with get_job_status instead, which returns the whole result for a workflow's runId. The owner or a caller passing the workflow's explicit read rule can read it, as for jobs. |
list_workflows | No | query?, tags?, labels? | { workflows: [{ name, description?, trigger, stepCount, tags }], count }, without workflows the caller can't list, submit or run. |
remove_workflow | No | name | Removes a workflow registered at run time. For a @Workflow class it fails with Workflow "…" is not dynamic and cannot be removed. |
A run's state is pending, running, completed or failed. A workflow that ran, even with failed steps, is a successful execute_workflow call: check state, not isError. The call itself fails only when the workflow can't run: an unknown name, a caller without permission, a dependsOn mistake, or its timeout.
Caveats
- The result doesn't say why a step failed. A failed step is
{ outputs: {}, state: "failed" }, whatever the reason; the error goes to the server's log, and an error of the step's job to job hooks too. - Changed in 1.11.3: before, steps without a retry policy ran three times; they now run once.
- Changed in 1.11.3: before, a failure skipped only direct dependents; it now skips indirect dependents too.
dependsOnmistakes are found when the workflow runs, not when the server starts.- Input and condition functions receive
(steps, input), with the workflow's parsed input. - Workflow input is checked before a run starts. Webhook, event and schedule triggers work only for workflows declared in code.
- Jobs'
logsaren't kept: a workflow's result has no logs. - A step runs its job as the caller who started the workflow, so a step whose job has
permissionsthe caller doesn't meet fails. - A step's job calls tools on the
"job"surface, as it does fromexecute_job: a tool whoseavailableWhen.surfaceleaves out"job"isn't found, andgetCallSurface()is"job"in the job and the tools it calls.
The workflow tool classes are exported from @frontmcp/sdk and @frontmcp/sdk/workflow/tools, as the same objects. Changed in 1.11.0: before, the subpath shipped types without loadable JavaScript.
Runners and admission
A step uses the inline runner unless its job or the server sets runner: "worker", which uses the offload pool. Steps do not start detached processes: runner: "detached" runs inline in a workflow. The server's jobs.admission limits apply to workflow steps too, but a step's timeout includes its wait for admission.
Work that ignores a step's signal may continue beside a retry.
Usage
Running steps one after another
A step that lists another in dependsOn waits for it, and its input function can read that step's outputs:
import { Workflow } from "@frontmcp/sdk";
@Workflow({
name: "remind-customer",
description: "Count Ada's open tickets and draft a reminder about them",
steps: [
{ id: "count", jobName: "count-open-tickets", input: { customer: "Ada" } },
{
id: "draft",
jobName: "draft-reminder",
dependsOn: ["count"],
input: (steps) => steps.get("count").outputs,
},
],
})
export class RemindCustomer {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Running steps in parallel
Steps that don't depend on each other start together, up to maxConcurrency at a time. Here three queues load at once, and report waits for all three:
import { Workflow } from "@frontmcp/sdk";
const loadSteps = ["billing", "login", "shipping"].map((queue) => ({
id: queue,
jobName: "load-queue",
input: { queue },
}));
@Workflow({
name: "queue-report",
steps: [
...loadSteps,
{
id: "report",
jobName: "sum-queues",
dependsOn: ["billing", "login", "shipping"],
input: (steps) => ({
sizes: ["billing", "login", "shipping"].map((id) => steps.get(id).outputs.size as number),
}),
},
],
})
export class QueueReport {}
@Workflow({ name: "queue-report-one-at-a-time", maxConcurrency: 1, steps: loadSteps })
export class QueueReportOneAtATime {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Without the TC39 AsyncContext, FrontMCP's browser build runs ready steps one at a time, as if maxConcurrency were 1. (Changed in 1.8.5: before, steps that overlapped there failed and were retried, and the workflow could end failed.) The Playground provides a minimal AsyncContext, so here they run at the same time, as on Node.
Passing input to a workflow
execute_workflow's input goes to every step that has no input of its own. Input functions receive the parsed workflow input as their second argument; they can also read earlier steps' outputs:
import { Workflow, z } from "@frontmcp/sdk";
@Workflow({
name: "remind-customer",
description: "Count a customer's open tickets and draft a reminder about them",
inputSchema: { customer: z.string() },
steps: [
{ id: "count", jobName: "count-open-tickets" }, // no input: gets the workflow's
{
id: "draft",
jobName: "draft-reminder",
dependsOn: ["count"],
input: (steps) => steps.get("count").outputs, // includes the customer
},
],
})
export class RemindCustomer {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
The second test runs the workflow with a number for customer. execute_workflow refuses it with INVALID_INPUT before any step starts. Changed in 1.11.3: before, the workflow's schema was not checked.
Handling a failed step
By default, a failed step skips the steps that depend on it and fails the workflow. continueOnError lets its dependents run anyway, and condition skips a step on purpose:
Failed steps
Example 1 of 3
Skipped dependents
notify fails, so archive, which depends on it, is skipped. stats doesn't depend on it and runs. The call succeeds; the workflow's state is failed.
import { App, Job, JobContext, Workflow, z } from "@frontmcp/sdk";
@Job({ name: "notify-team", inputSchema: {}, outputSchema: { sent: z.boolean() } })
export class NotifyTeam extends JobContext {
async execute(): Promise<{ sent: boolean }> {
throw new Error("Mail server busy");
}
}
@Job({ name: "archive-tickets", inputSchema: {}, outputSchema: { archived: z.number() } })
export class ArchiveTickets extends JobContext {
async execute() {
return { archived: 12 };
}
}
@Job({ name: "daily-stats", inputSchema: {}, outputSchema: { closed: z.number() } })
export class DailyStats extends JobContext {
async execute() {
return { closed: 12 };
}
}
@Workflow({
name: "close-day",
steps: [
{ id: "notify", jobName: "notify-team", retry: { maxAttempts: 1 } },
{ id: "archive", jobName: "archive-tickets", dependsOn: ["notify"] },
{ id: "stats", jobName: "daily-stats" },
],
})
export class CloseDay {}
@App({ id: "help-desk", name: "Help Desk", jobs: [NotifyTeam, ArchiveTickets, DailyStats], workflows: [CloseDay] })
export class HelpDeskApp {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Example 2 of 3
continueOnError
With continueOnError: true on notify, archive runs, and can check how notify went. The workflow is completed.
import { App, Job, JobContext, Workflow, z } from "@frontmcp/sdk";
@Job({ name: "notify-team", inputSchema: {}, outputSchema: { sent: z.boolean() } })
export class NotifyTeam extends JobContext {
async execute(): Promise<{ sent: boolean }> {
throw new Error("Mail server busy");
}
}
@Job({ name: "archive-tickets", inputSchema: { teamNotified: z.boolean() }, outputSchema: { archived: z.number(), note: z.string() } })
export class ArchiveTickets extends JobContext {
async execute({ teamNotified }: { teamNotified: boolean }) {
return { archived: 12, note: teamNotified ? "Team notified" : "Team not notified" };
}
}
@Workflow({
name: "close-day",
steps: [
{ id: "notify", jobName: "notify-team", retry: { maxAttempts: 1 }, continueOnError: true },
{
id: "archive",
jobName: "archive-tickets",
dependsOn: ["notify"],
input: (steps) => ({ teamNotified: steps.get("notify").state === "completed" }),
},
],
})
export class CloseDay {}
@App({ id: "help-desk", name: "Help Desk", jobs: [NotifyTeam, ArchiveTickets], workflows: [CloseDay] })
export class HelpDeskApp {}import { test, expect } from "@frontmcp/testing";
test("archive runs after notify fails", async ({ mcp }) => {
const { state, result } = (await mcp.tools.call("execute_workflow", { name: "close-day" })).json();
expect(state).toBe("completed");
expect(result.stepResults.notify).toEqual({ state: "failed", outputs: {} });
expect(result.stepResults.archive.outputs).toEqual({ archived: 12, note: "Team not notified" });
});Example 3 of 3
condition
escalate only runs when there are breached tickets. Today there are none, so it's skipped, and report, which depends on it, still runs.
import { App, Job, JobContext, Workflow, z } from "@frontmcp/sdk";
@Job({ name: "find-sla-breaches", inputSchema: {}, outputSchema: { ids: z.array(z.string()) } })
export class FindSlaBreaches extends JobContext {
async execute() {
return { ids: [] as string[] };
}
}
@Job({ name: "escalate", inputSchema: { ids: z.array(z.string()) }, outputSchema: { paged: z.string() } })
export class Escalate extends JobContext {
async execute({ ids }: { ids: string[] }) {
return { paged: `On-call lead, about ${ids.join(", ")}` };
}
}
@Job({ name: "write-report", inputSchema: { escalated: z.boolean() }, outputSchema: { line: z.string() } })
export class WriteReport extends JobContext {
async execute({ escalated }: { escalated: boolean }) {
return { line: escalated ? "Breaches escalated." : "No escalation needed." };
}
}
@Workflow({
name: "sla-check",
steps: [
{ id: "breaches", jobName: "find-sla-breaches" },
{
id: "escalate",
jobName: "escalate",
dependsOn: ["breaches"],
condition: (steps) => (steps.get("breaches").outputs.ids as string[]).length > 0,
input: (steps) => ({ ids: steps.get("breaches").outputs.ids }),
},
{
id: "report",
jobName: "write-report",
dependsOn: ["escalate"],
input: (steps) => ({ escalated: steps.get("escalate").state === "completed" }),
},
],
})
export class SlaCheck {}
@App({ id: "help-desk", name: "Help Desk", jobs: [FindSlaBreaches, Escalate, WriteReport], workflows: [SlaCheck] })
export class HelpDeskApp {}import { test, expect } from "@frontmcp/testing";
test("escalate is skipped, and report still runs", async ({ mcp }) => {
const { state, result } = (await mcp.tools.call("execute_workflow", { name: "sla-check" })).json();
expect(state).toBe("completed");
expect(result.stepResults.escalate).toEqual({ state: "skipped", outputs: {} });
expect(result.stepResults.report.outputs).toEqual({ line: "No escalation needed." });
});Running a workflow in the background
With background: true, execute_workflow returns a runId at once. The user who started the run reads its steps with get_job_status: get_workflow_status returns the run's state, but never its steps.
import { App, Job, JobContext, Workflow, z } from "@frontmcp/sdk";
@Job({ name: "load-queue", inputSchema: { queue: z.string() }, outputSchema: { queue: z.string(), size: z.number() } })
export class LoadQueue extends JobContext {
async execute({ queue }: { queue: string }) {
await new Promise((resolve) => setTimeout(resolve, 100)); // stands in for a slow query
return { queue, size: queue.length };
}
}
@Workflow({
name: "queue-report",
steps: [
{ id: "billing", jobName: "load-queue", input: { queue: "billing" } },
{ id: "login", jobName: "load-queue", dependsOn: ["billing"], input: { queue: "login" } },
],
})
export class QueueReport {}
@App({ id: "help-desk", name: "Help Desk", jobs: [LoadQueue], workflows: [QueueReport] })
export class HelpDeskApp {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
As with jobs, nobody can read an anonymous caller's runs, so the Playground's Call tab can start a background run but not poll it. The last test signs in as nour. Chaining Jobs into Workflows covers when to run a workflow in the background, and the Nightly Ticket Report example starts one from a tool and keeps its report where another tool can read it.
Seeing each step's attempts
A step's result doesn't say why it failed, but a JobHook sees every attempt of every step, and the job's error when one fails. For a step, ctx.state.workflow is { name, stepId, runId }: the workflow, the step's id and the workflow run's id. ctx.state.runId is undefined, since the workflow run keeps the record:
import { DynamicPlugin, FlowCtxOf, JobHook, Plugin } from "@frontmcp/sdk";
export const stepLog: string[] = [];
@Plugin({ name: "step-log" })
export class StepLogPlugin extends DynamicPlugin<object> {
@JobHook.Did("finalize", { filter: (ctx) => ctx.state.workflow !== undefined })
async record(ctx: FlowCtxOf<"jobs:execute-job">) {
const { workflow, attempt, flowError } = ctx.state;
stepLog.push(`${workflow?.name}/${workflow?.stepId} attempt ${attempt}: ${flowError ? flowError.message : "completed"}`);
}
}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
The two steps don't depend on each other, so they run together, and the test sorts the lines. The same hook sees execute_job's runs too, without workflow; the filter leaves them out. (New in 1.9.4: before, steps ran outside any flow, and nothing but the server's log saw their errors.)
Stopping work when a step times out
A timeout aborts the job's this.signal, which is set on every job attempt. Check it before doing more work. A job that returns after the timeout still ends as a failed attempt, and finalize hooks see the timeout error.
import { App, Job, JobContext, JobHook, Workflow, z } from "@frontmcp/sdk";
export const seen = { aborted: false, executedHook: false, error: "" };
@Job({ name: "slow-count", inputSchema: {}, outputSchema: { open: z.number() }, retry: { maxAttempts: 1 } })
class SlowCount extends JobContext {
async execute() {
await new Promise((resolve) => setTimeout(resolve, 100));
seen.aborted = this.signal?.aborted ?? false;
return { open: 12 };
}
@JobHook.Did("execute")
afterExecute() { seen.executedHook = true; }
@JobHook.Did("finalize")
finalized(ctx: any) { seen.error = ctx.state.flowError?.constructor.name ?? ""; }
}
@Workflow({ name: "count-before-deadline", steps: [{ id: "count", jobName: "slow-count", timeout: 20 }] })
class CountBeforeDeadline {}
@App({ id: "help-desk", name: "Help Desk", jobs: [SlowCount], workflows: [CountBeforeDeadline] })
export class HelpDeskApp {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Starting from an app event
An event workflow receives the event payload as validated input. Its create and execute rules must admit event:<event>; the jobs it calls check execute.
import { App, Tool, ToolContext, Job, JobContext, Workflow, z } from "@frontmcp/sdk";
export const welcomed: string[] = [];
@Job({ name: "welcome", inputSchema: { userId: z.string() }, outputSchema: { sent: z.boolean() } })
class Welcome extends JobContext {
async execute({ userId }: { userId: string }) {
welcomed.push(userId);
return { sent: true };
}
}
@Workflow({
name: "welcome-user", trigger: "event", event: "user.signup",
inputSchema: { userId: z.string() },
permissions: [{ action: "create", roles: ["event:user.signup"] }, { action: "execute", roles: ["event:user.signup"] }],
steps: [{ id: "welcome", jobName: "welcome", input: (_steps, input) => ({ userId: input.userId }) }],
})
class WelcomeUser {}
@Tool({ name: "signup", description: "Welcome a new user", inputSchema: { userId: z.string() } })
class Signup extends ToolContext {
async execute(input: { userId: string }) {
this.scope.channelEventBus?.emit("user.signup", input);
return { accepted: true };
}
}
@App({ name: "Help Desk", tools: [Signup], jobs: [Welcome], workflows: [WelcomeUser] })
export class HelpDesk {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Starting from a published event
New in 1.12.0. An event the server declares reaches the same bus when it is published, so a workflow can react to it without the publisher knowing. The tool below only publishes ticket.closed. The workflow listens to that name, gets the occurrence as its input, and runs as the role event:ticket.closed:
import { App, Job, JobContext, Tool, ToolContext, Workflow, event, workflowTriggerOf, z } from "@frontmcp/sdk";
export const surveys: { ticket: string; eventId: string; role?: string }[] = [];
export const ticketClosed = event({
name: "ticket.closed",
description: "A support ticket was closed",
payloadSchema: { id: z.string() },
});
const occurrence = { eventId: z.string(), name: z.string(), timestamp: z.string(), data: z.object({ id: z.string() }) };
@Job({ name: "send-survey", inputSchema: occurrence, outputSchema: { sent: z.boolean() } })
class SendSurvey extends JobContext {
async execute({ eventId, data }: { eventId: string; data: { id: string } }) {
surveys.push({ ticket: data.id, eventId, role: workflowTriggerOf(this.context.authInfo)?.role });
return { sent: true };
}
}
@Workflow({
name: "survey-after-close", trigger: "event", event: "ticket.closed",
inputSchema: occurrence,
steps: [{ id: "survey", jobName: "send-survey" }],
})
class SurveyAfterClose {}
@Tool({
name: "close_ticket",
description: "Close a support ticket, and tell its agent alone when one is named",
inputSchema: { id: z.string(), agent: z.string().optional() },
})
class CloseTicket extends ToolContext {
async execute({ id, agent }: { id: string; agent?: string }) {
const onlyForAgent = agent ? { audience: { sub: agent } } : undefined;
return this.events.publish(ticketClosed, { id }, onlyForAgent);
}
}
@App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket], events: [ticketClosed], jobs: [SendSurvey], workflows: [SurveyAfterClose] })
export class HelpDesk {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
publish() answers { eventId, matched }: matched counts the webhook subscriptions the occurrence was queued for, none here. The workflow starts whether or not anyone is subscribed, and whoever the occurrence is for: the second test publishes with an audience, which narrows the subscribers that are told, not the workflows that start. A worker or a duty that publishes the event starts it the same way.
Starting from a signed webhook
Sign the exact JSON body with the configured secret. The tests use Web Crypto to sign the same bytes the handler reads:
import { test, expect } from "@frontmcp/testing";
import { App, FrontMcpInstance, Job, JobContext, workflow, z } from "@frontmcp/sdk";
const secret = "example-webhook-secret-at-least-32-characters";
@Job({ name: "count", inputSchema: { count: z.number() }, outputSchema: { count: z.number() } })
class Count extends JobContext {
async execute(input: { count: number }) { return input; }
}
@App({ name: "Help Desk", jobs: [Count], workflows: [workflow({
name: "count-tickets", trigger: "webhook", webhook: { secret },
inputSchema: { count: z.number() }, steps: [{ id: "count", jobName: "count" }],
})] })
class HelpDesk {}
test("only a signed webhook starts the workflow", async () => {
const handler = await FrontMcpInstance.createFetchHandler({ info: { name: "help-desk", version: "1" }, apps: [HelpDesk] });
const body = JSON.stringify({ count: 2 });
const url = "http://localhost/workflows/webhook/count-tickets";
expect((await handler(new Request(url, { method: "POST", headers: { "content-type": "application/json" }, body }))).status).toBe(401);
const timestamp = String(Math.floor(Date.now() / 1000));
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
const mac = await crypto.subtle.sign("HMAC", key, encoder.encode(`${timestamp}.${body}`));
const signature = Array.from(new Uint8Array(mac), (b) => b.toString(16).padStart(2, "0")).join("");
const response = await handler(new Request(url, { method: "POST", body, headers: {
"content-type": "application/json", "X-FrontMCP-Timestamp": timestamp, "X-FrontMCP-Signature": `v1=${signature}`,
} }));
expect(response.status).toBe(202);
expect(await response.json()).toMatchObject({ runId: expect.any(String), state: "pending" });
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Running on a schedule
New in 1.12.0. trigger: "schedule" starts a background run at each time of the cron, in one process among the server's copies. When the workflow has execute rules, add the schedule's role to them:
import { Workflow, z } from "@frontmcp/sdk";
@Workflow({
name: "weekday-digest",
description: "Sends the digest every weekday morning",
trigger: "schedule",
schedule: { cron: "0 9 * * 1-5", timezone: "Europe/Berlin", input: { audience: "team" } },
inputSchema: { audience: z.string() },
permissions: [
{ action: "execute", roles: ["admin", "schedule:weekday-digest"] },
{ action: "read", roles: ["admin"] },
],
steps: [{ id: "send", jobName: "send-digest" }],
})
export class WeekdayDigest {}The process that holds the schedule's lease logs The schedule of workflow "weekday-digest" runs in this process on cron "0 9 * * 1-5" (Europe/Berlin), and the others The schedule of workflow "weekday-digest" already runs elsewhere (lease "<key>"); this one takes it over if that one stops. Each scheduled run has an id like schedule-1794407638000-be4ebbb5b741e13f. An admin still runs the workflow by hand with execute_workflow, and reads a scheduled run by that id through the read rule. Without schedule:weekday-digest among the execute roles, every scheduled time logs:
Execution of "weekday-digest" denied: caller does not satisfy its execute permissions
The schedule did not start workflow "weekday-digest": its create or execute rules don't allow the role "schedule:weekday-digest"; add it to their roles
No schedule starts in the Playground, which runs FrontMCP's browser build. What the server checks at startup runs there, and so does the schedule's principal, which a test can hand to a custom rule:
import { test, expect } from "@frontmcp/testing";
import { App, FrontMcpInstance, Job, JobContext, Workflow, WorkflowTriggerPrincipal, workflowTriggerOf, z } from "@frontmcp/sdk";
@Job({ name: "send-digest", inputSchema: { audience: z.string() }, outputSchema: { sent: z.boolean() } })
class SendDigest extends JobContext {
async execute() {
return { sent: true };
}
}
async function startupErrorOf(options: Record<string, unknown>) {
@Workflow({ name: "weekday-digest", steps: [{ id: "send", jobName: "send-digest" }], ...options } as never)
class WeekdayDigest {}
@App({ id: "help-desk", name: "Help Desk", jobs: [SendDigest], workflows: [WeekdayDigest] })
class HelpDesk {}
const error = await FrontMcpInstance.createFetchHandler({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk] }).catch((thrown) => thrown);
return { code: error.code, message: error.message };
}
test("a schedule the server can't read stops startup", async () => {
expect(await startupErrorOf({ trigger: "schedule" })).toEqual({
code: "INVALID_WORKFLOW_TRIGGER",
message: `Workflow "weekday-digest": trigger: 'schedule' needs schedule.cron, a cron expression such as "0 9 * * 1-5", and the server does not start without it`,
});
expect(await startupErrorOf({ trigger: "schedule", schedule: { cron: "61 9 * * 1-5" } })).toEqual({
code: "INVALID_WORKFLOW_TRIGGER",
message: `Workflow "weekday-digest": schedule.cron "61 9 * * 1-5" can't be read: Invalid value for minute: 61`,
});
expect(await startupErrorOf({ trigger: "schedule", schedule: { cron: "0 0 30 2 *" } })).toMatchObject({
message: `Workflow "weekday-digest": schedule.cron "0 0 30 2 *" can't be read: it never matches a date`,
});
expect(await startupErrorOf({ trigger: "schedule", schedule: { cron: "0 9 * * 1-5", timezone: "Berlin" } })).toMatchObject({
message: `Workflow "weekday-digest": schedule.timezone "Berlin" is not an IANA time zone such as "Europe/Berlin"`,
});
});
test("a schedule on a workflow with another trigger stops startup too", async () => {
expect(await startupErrorOf({ schedule: { cron: "0 9 * * 1-5" } })).toMatchObject({
code: "INVALID_WORKFLOW_TRIGGER",
message: `Workflow "weekday-digest": schedule is set, but trigger is not 'schedule': set trigger: 'schedule' to run it on that schedule, or remove schedule`,
});
});
test("a scheduled run's caller is the schedule's principal, which a custom rule can read", () => {
const onlyTheSchedule = (authInfo: Record<string, unknown>) => workflowTriggerOf(authInfo)?.role === "schedule:weekday-digest";
const schedule = new WorkflowTriggerPrincipal("schedule", "weekday-digest");
expect(schedule.role).toBe("schedule:weekday-digest");
expect(onlyTheSchedule(schedule.toAuthInfo())).toBe(true);
expect(onlyTheSchedule({ user: { sub: "nour", roles: ["schedule:weekday-digest"] } })).toBe(false);
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
A token cannot carry the schedule's principal: for workflowTriggerOf(), a caller whose roles claim says schedule:weekday-digest is not the schedule, as the last test shows.
Troubleshooting
Invalid input for workflow "…"
The input does not match the workflow’s schema. Check the issue paths in the message. No step starts; see passing input.
Workflow "…": trigger: 'webhook' needs webhook.secret
Set a unique secret of at least 32 characters. A webhook block without trigger: "webhook", or an event or a schedule with another trigger, also stops startup with INVALID_WORKFLOW_TRIGGER. Route collisions fail with INVALID_HTTP_ROUTE. See Workflow triggers.
Workflow "…": trigger: 'schedule' needs schedule.cron or schedule.cron "…" can't be read
WorkflowTriggerConfigError (INVALID_WORKFLOW_TRIGGER) stopped startup. Give the workflow a schedule with a cron of five fields, or six with seconds first; a year field, a date and an expression that never matches a date are refused. schedule.timezone "…" is not an IANA time zone asks for a name such as "Europe/Berlin". See schedule options.
The schedule did not start workflow "…"
The run was refused, and the log line says why. its create or execute rules don't allow the role "schedule:<workflow>": add that role to the workflow's create and execute rules. Invalid input for workflow "…": schedule.input does not match the inputSchema. The next scheduled time starts its own run. A step whose job has execute rules that leave the role out fails inside the run instead, with Job or workflow "…" not found or not permitted in the log.
The schedule of workflow "…" did not start: …
The schedule's lease store could not be opened. Without a top-level redis it is a SQLite file that needs @frontmcp/storage-sqlite; with one, check that Redis is reachable. The store is opened again every 20 seconds, and the schedule starts once it opens.
A scheduled workflow runs at the wrong hour, or did not run at startup
The cron is read in UTC unless schedule.timezone names the zone it is meant in. A schedule never runs at startup: it waits for its next scheduled time, or runs once when a scheduled time passed while no process held its lease.
Workflow "…" is declared in code and cannot be updated
update_workflow only changes workflows made with register_workflow; a declared class fails with INVALID_INPUT. Runtime registration accepts only manual triggers, and at most 100 steps, each with at most 100 dependsOn entries: a longer list is INVALID_INPUT too. Changed in 1.12.1: before, there was no limit. Change the class and restart for a webhook or event workflow.
A step failed, and the result doesn't say why
A step's result is { outputs: {}, state: "failed" } whatever went wrong: the job threw, its input didn't match, it timed out, its jobName doesn't exist, or its input function read a step that hadn't finished. The error only goes to the server's log; a job hook also sees the errors of the step's job. To see it, run the step's job by itself with execute_job and the same input:
import { App, Job, JobContext, PublicMcpError, Workflow, z } from "@frontmcp/sdk";
@Job({ name: "escalate", inputSchema: { ids: z.array(z.string()) }, outputSchema: { paged: z.string() } })
export class Escalate extends JobContext {
async execute({ ids }: { ids: string[] }): Promise<{ paged: string }> {
this.fail(new PublicMcpError("Nobody is on call tonight.", "NO_ON_CALL"));
}
}
@Workflow({ name: "sla-check", steps: [{ id: "escalate", jobName: "escalate", input: { ids: ["T-7"] }, retry: { maxAttempts: 1 } }] })
export class SlaCheck {}
@App({ id: "help-desk", name: "Help Desk", jobs: [Escalate], workflows: [SlaCheck] })
export class HelpDeskApp {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
If the step's input comes from a function, return the values it would build from an earlier step, and pass those.
A failing step takes three seconds
A step inherits its job's retry policy unless it supplies its own. Without either policy it runs once. Changed in 1.11.3: before, a step without a policy was tried three times over three seconds.
import { App, Job, JobContext, Workflow, z } from "@frontmcp/sdk";
@Job({ name: "notify-team", inputSchema: {}, outputSchema: { sent: z.boolean() } })
export class NotifyTeam extends JobContext {
async execute(): Promise<{ sent: boolean }> {
throw new Error("Mail server busy");
}
}
@Workflow({ name: "notify", steps: [{ id: "notify", jobName: "notify-team" }] })
export class Notify {}
@Workflow({ name: "notify-once", steps: [{ id: "notify", jobName: "notify-team", retry: { maxAttempts: 1 } }] })
export class NotifyOnce {}
@App({ id: "help-desk", name: "Help Desk", jobs: [NotifyTeam], workflows: [Notify, NotifyOnce] })
export class HelpDeskApp {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
A step ran even though a step before it failed
When a step fails, FrontMCP skips both its direct and indirect dependents. Here archive fails, so report and notify are skipped, even without a condition. Changed in 1.11.3: before, only direct dependents were skipped, and notify ran.
import { App, Job, JobContext, Workflow, z } from "@frontmcp/sdk";
@Job({ name: "archive-tickets", inputSchema: {}, outputSchema: { archived: z.number() } })
export class ArchiveTickets extends JobContext {
async execute(): Promise<{ archived: number }> {
throw new Error("Archive is full");
}
}
@Job({ name: "write-report", inputSchema: {}, outputSchema: { text: z.string() } })
export class WriteReport extends JobContext {
async execute() {
return { text: "12 tickets archived" };
}
}
@Job({ name: "email-report", inputSchema: { text: z.string().optional() }, outputSchema: { sent: z.string() } })
export class EmailReport extends JobContext {
async execute({ text }: { text?: string }) {
return { sent: text ?? "(no report)" };
}
}
const steps = [
{ id: "archive", jobName: "archive-tickets", retry: { maxAttempts: 1 } },
{ id: "report", jobName: "write-report", dependsOn: ["archive"] },
];
@Workflow({
name: "unguarded",
steps: [
...steps,
{ id: "notify", jobName: "email-report", dependsOn: ["report"], input: (s) => s.get("report").outputs },
],
})
export class Unguarded {}
@Workflow({
name: "guarded",
steps: [
...steps,
{
id: "notify",
jobName: "email-report",
dependsOn: ["report"],
condition: (s) => s.get("report").state === "completed", // ✅ only after a real report
input: (s) => s.get("report").outputs,
},
],
})
export class Guarded {}
@App({ id: "help-desk", name: "Help Desk", jobs: [ArchiveTickets, WriteReport, EmailReport], workflows: [Unguarded, Guarded] })
export class HelpDeskApp {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Step "…" depends on unknown step "…" or Workflow has a cycle involving step "…"
A step's dependsOn names a step id that isn't in steps, or steps depend on each other in a loop. FrontMCP checks this when the workflow runs, not when the server starts, so the server starts fine and every execute_workflow call fails:
import { App, Job, JobContext, Workflow, z } from "@frontmcp/sdk";
@Job({ name: "archive-tickets", inputSchema: {}, outputSchema: { archived: z.number() } })
export class ArchiveTickets extends JobContext {
async execute() {
return { archived: 12 };
}
}
@Workflow({
name: "close-day",
steps: [
{ id: "archive", jobName: "archive-tickets", dependsOn: ["notify"] }, // 🚩 there's no "notify" step
],
})
export class CloseDay {}
@App({ id: "help-desk", name: "Help Desk", jobs: [ArchiveTickets], workflows: [CloseDay] })
export class HelpDeskApp {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Fix the id, or break the loop. A test that runs each workflow once catches this before your users do.
Workflow "…" timed out after …ms
The workflow ran longer than its timeout. FrontMCP checks it each time a batch of steps finishes, so the step that was running finished first, and the call fails with TOOL_EXECUTION_ERROR instead of returning the steps' results:
import { App, Job, JobContext, Workflow, z } from "@frontmcp/sdk";
@Job({ name: "load-queue", inputSchema: { queue: z.string() }, outputSchema: { queue: z.string() } })
export class LoadQueue extends JobContext {
async execute({ queue }: { queue: string }) {
await new Promise((resolve) => setTimeout(resolve, 60));
return { queue };
}
}
@Workflow({
name: "queue-report",
timeout: 50,
steps: [
{ id: "billing", jobName: "load-queue", input: { queue: "billing" } },
{ id: "login", jobName: "load-queue", dependsOn: ["billing"], input: { queue: "login" } },
],
})
export class QueueReport {}
@App({ id: "help-desk", name: "Help Desk", jobs: [LoadQueue], workflows: [QueueReport] })
export class HelpDeskApp {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Raise timeout, or run the workflow in the background. To limit one step, set the step's timeout: a step that runs too long fails, and the workflow carries on as for any failed step.
Job or workflow "…" not found or not permitted
execute_workflow found no workflow by that name that the caller may run. Check that the name matches @Workflow({ name }) (or its id, if it has one), that the class is in an app's workflows, and that its permissions let the caller run it. A step whose jobName is wrong doesn't cause this error: that step fails.
get_workflow_status returns an empty stepResults
get_workflow_status never fills in stepResults. Call get_job_status with the same runId: its result is the workflow's result, steps included. Running a workflow in the background shows both.
A step's input function can't see the workflow's input
An input function receives (steps, input), where input is the parsed workflow input. Changed in 1.11.3: before, only steps was passed. See Passing input to a workflow.