@Job
@Job declares a job: a piece of work with validated input that a client starts by name, with the built-in execute_job tool. A job can run while the client waits, or in the background while the client does something else, and FrontMCP can retry it when it fails. Jobs are also the steps of a @Workflow.
@Job(options)
class MyJob extends JobContext {
async execute(input) { /* ... */ }
}
Reference
@Job(options)
Apply @Job to a class that extends JobContext, and list the class in an app's jobs array. FrontMCP then adds the tools that run jobs to the server; you don't write a tool for each job.
import { Job, JobContext, z } from "@frontmcp/sdk";
@Job({
name: "count-open-tickets",
description: "Count a customer's open tickets",
inputSchema: { customer: z.string() },
outputSchema: { customer: z.string(), open: z.number() },
retry: { maxAttempts: 3, backoffMs: 500 },
})
export class CountOpenTickets extends JobContext {
async execute({ customer }: { customer: string }) {
this.log(`Counting open tickets for ${customer}`);
const open = await countOpenTickets(customer);
return { customer, open };
}
}import { App } from "@frontmcp/sdk";
import { CountOpenTickets } from "./count-open.job";
@App({ id: "help-desk", name: "Help Desk", jobs: [CountOpenTickets] })
export class HelpDeskApp {}Options
Required:
| Option | Type | Description |
|---|---|---|
name | string | What clients pass to execute_job, and what a workflow step's jobName refers to. Unique within the server. If you also set id, the id replaces it. |
inputSchema | object of Zod types | One Zod type per input field, like { customer: z.string() }. execute_job checks the input against it before execute() runs. |
outputSchema | object of Zod types, or any output schema a tool accepts | The shape of the result. TypeScript checks execute()'s return type against it, and FrontMCP checks the result when the job runs: fields it doesn't declare are dropped, and a result that doesn't match fails the run with INVALID_OUTPUT, without a retry. See Troubleshooting. (Changed in 1.9.2: before, the result wasn't checked at run time.) |
Optional:
| Option | Type | Default | Description |
|---|---|---|---|
description | string | What the job does. list_jobs shows it. | |
id | string | name | A stable identifier. When set, it replaces name: clients, list_jobs and workflow steps all use the id. |
retry | JobRetryConfig | none: one attempt | Run execute() again when it throws. See retry. |
timeout | number | server default | Maximum milliseconds per attempt; 0 disables the deadline. When unset, uses jobs.defaultTimeoutMs (300000). Applies to execute_job too. |
cleanup | JobCleanup | { run: JobCleanup; timeoutMs?: number } | none | Called with the attempt's instance and reason ("interrupt", "timeout" or "cancel"). Default cleanup limit: 3000 ms. A failure only logs a warning. |
runner | "inline" | "worker" | "detached" | jobs.runner, else "inline" | Event loop, offload worker pool, or a Node process that survives the server. |
tags | string[] | [] | Labels to filter list_jobs by. |
labels | Record<string, string> | {} | Key-value labels to filter list_jobs by. |
hideFromDiscovery | boolean | false | Leave the job out of list_jobs. It still runs by name. |
permissions | JobPermission[] | none: anyone may run it | Who may run and list the job. See permissions. |
retry
| Field | Type | Default | Description |
|---|---|---|---|
maxAttempts | number | 3 | Attempts in all, counting the first. |
backoffMs | number | 1000 | How long to wait before the second attempt, in milliseconds. |
backoffMultiplier | number | 2 | Each wait is this many times longer than the one before. |
maxBackoffMs | number | 60000 | The longest any one wait can be. |
The wait after attempt n is backoffMs × backoffMultiplier^(n−1), capped at maxBackoffMs. The defaults apply as soon as you set retry: retry: {} means three attempts, with waits of 1 and 2 seconds.
A job without retry runs once, including as a workflow step. Changed in 1.11.3: before, a workflow step without a retry policy was tried three times.
permissions
Each entry is a rule for one action:
| Field | Type | Description |
|---|---|---|
action | "execute" | "list" | "delete" | "create" | "read" | "update" | What the rule guards. FrontMCP checks execute (when execute_job starts a run, again before each attempt, and for a workflow step that runs the job), list (list_jobs) and delete (remove_job). read permits reading another caller's run, and delete also permits cancelling it. create gates submission of a new run, whatever submits it: execute_job, execute_workflow, or a workflow's webhook, event or schedule, whose runs carry the role webhook:<workflow>, event:<event> or schedule:<workflow> (schedules are new in 1.12.0). It is checked once, with execute, before the run exists. update gates changes through update_job or update_workflow. Workflow steps check the job's execute rules without submitting a new job run through execute_job. |
roles | string[] | The caller needs at least one of these, in their roles claim. |
scopes | string[] | The caller needs at least one of these, in their token's scope claim. |
custom | (authInfo) => boolean | Promise<boolean> | Your own check. It receives the caller's authInfo, with the token's claims in authInfo.user. For execute, it runs when the run starts and again before each attempt: four times for a job that runs three times. (Changed in 1.9.4: before, once per run.) |
A rule passes when each of its fields passes, and the caller needs every rule for the action. list_jobs leaves out jobs the caller can't list, submit or run. A caller who isn't allowed to run a job gets the same error as for a job that doesn't exist, so they can't find out which jobs exist by guessing names. When the check before a later attempt refuses the caller, as a custom check can, the run fails at once, without a retry.
execute(input)
FrontMCP calls execute() once the input passes validation, and again for each retry.
input: the validated input. Fields with a.default()are filled in, and fields that aren't ininputSchemaare dropped. The same object isthis.input.- Returns the job's result:
resultin whatexecute_jobreturns, andoutputswhen the job is a workflow step, where later steps read it. Return an object.
To fail, throw, or call this.fail(). A failed attempt is retried if the job has retry, except public errors, invalid output, authorization denials, cancellations, interruptions and admission timeouts.
JobContext
Inside execute(), this is the JobContext:
| Member | Description |
|---|---|
this.log(message) | Adds a line to the run's logs, prefixed with the time: [2026-09-27T09:00:00.000Z] message. Only the lines of the attempt that succeeded are kept, and a failed run's logs is empty, but every line also goes to the server's log. |
this.input | The validated input. |
this.get(token), this.tryGet(token) | Providers, from the job's app and from the server. See Using a provider. (Changed in 1.9.2: before, a job only saw the server's.) |
this.fail(error) | Ends the attempt with error. The message and code of a PublicMcpError reach the client as they are. |
this.auth | The caller who started the run, as in tools: user.sub, isAnonymous, roles, scopes. |
this.callTool(name, args) | Calls a tool of the server as the caller who started the run, on the "job" surface: a tool whose availableWhen.surface leaves out "job" answers Tool "…" not found. See this.callTool(). |
this.context, this.fetch() | The request's context, as in a tool. When execute_job runs the job while the client waits, it's the caller's; in the background, it's a copy with the same session, caller and trace, and a request id of its own. this.fetch() sends the tracing headers, traceparent and x-request-id. See Calling another service from a job. Context classes compares every member. (Changed in 1.9.2: before, this.context threw in a job, and this.fetch() sent no tracing headers.) |
this.workerEnv | On a Cloudflare Worker, the bindings of the request that ran execute_job, when it runs the job while the client waits. On a server from create(), the workerEnv of the executeJob() call, or else of the server, in the background too. undefined elsewhere. (Since 1.9; before, always undefined. Changed in 1.9.4: before, a server from create() had none.) |
this.metadata | The job's options. |
this.attempt | The attempt number, from 1: 2 on the first retry. See Retrying a job that fails. (Changed in 1.9.2: before, it was always 1.) |
this.progress(progress, total?, message?) | Records { progress, total?, message? } on a job run and announces a resource update. Workflow steps have no run recorder. Also sends a session notification when a session exists. Returns true when either succeeds. |
this.signal | An AbortSignal for each attempt: aborts on the step deadline in a workflow, and on timeout, cancellation or shutdown for execute_job. Pass it to cancellable work or check it in a loop. this.fetch() uses it. Work that ignores it can continue after the attempt ends. |
this.respond(value) | Ends the attempt with value as the job's result, as returning it does, and value is checked against outputSchema the same way. (Changed in 1.9.2: before, value replaced the whole execute_job response.) |
job(options)(handler)
The function form takes the same options. handler(input, ctx) receives the validated input and the JobContext. List the result in jobs like a class.
import { job, z } from "@frontmcp/sdk";
import { TicketStore } from "./ticket-store";
export const countOpenTickets = job({
name: "count-open-tickets",
inputSchema: { customer: z.string() },
outputSchema: { customer: z.string(), open: z.number() },
})(async ({ customer }, ctx) => {
return { customer, open: ctx.get(TicketStore).openFor(customer).length };
});
ctx.log() and ctx.progress() work in a handler. fail() is protected, so TypeScript rejects ctx.fail() with error TS2445: throw a PublicMcpError instead, which fails the attempt the same way. (Changed in 1.9.1: before, log() and progress() were protected too.)
JobHook
Changed in 1.10.16: when a hook calls ctx.fail(error), the attempt records that error's message instead of an empty control-flow message. An aborted attempt records Flow aborted: <reason> instead of The job attempt ended before it produced a result. ctx.error exposes the first failure, and JobHook.Finally(stage) runs cleanup after any outcome of that stage.
Each attempt of a job runs the jobs:execute-job flow: a run execute_job starts, inline or in the background, each retry, and each workflow step. JobHook hooks it, as ToolHook hooks tool calls, and FlowCtxOf<"jobs:execute-job"> types the hook's ctx. @frontmcp/sdk also exports the flow's class as the type ExecuteJobFlow. A hook runs once per attempt: three times for a job that succeeds on its third. (New in 1.9.4: before, jobs ran through no flow.)
| Stage | Group | What it does |
|---|---|---|
parseInput | first | Sets job, attempt, runId, workflow, authInfo and input. |
checkJobAuthorization | first | Checks the job's execute permissions against the caller. A refusal fails the run with JOB_NOT_AUTHORIZED, without a retry. |
validateInput | first | Parses input with inputSchema into parsedInput. |
admit | first | Waits for the scope's admission slot. |
createJobContext | first | Builds the job's instance, the JobContext, as jobContext. |
execute | execute | Runs execute(). |
validateOutput | execute | Parses the result with outputSchema, and sets answer: { result, logs }. |
cleanup | error | Runs the job's cleanup when an attempt was interrupted, timed out or cancelled after its instance was built. |
updateRunState | always | Records the attempt on the run, including timeout, cancellation and interruption states. |
finalize | always | Answers with answer. |
ctx.state has:
| Field | What it is |
|---|---|
job | The job: name, and metadata, its options. |
attempt | The attempt number, from 1. |
runId | The run's id. undefined for a workflow step, whose workflow run keeps the record. |
workflow | For a workflow step, { name, stepId, runId }: the workflow, the step's id and the workflow run's id. undefined otherwise. |
authInfo | The caller who started the run. |
input, parsedInput | The job's input as given, and once inputSchema has parsed it. A hook before validateInput can replace input. |
jobContext | The job's instance, from createJobContext on. |
answer | { result, logs }, from validateOutput on. |
flowError | In the always stages, the error that failed the attempt. |
- Where hooks go. A hook on a plugin or a provider of an app runs for that app's jobs; on
@FrontMcp, for every job. On a@Jobclass, it runs for that job's attempts only: as an instance method fromcreateJobContexton, with the job's context asthis, or as astaticmethod on any stage, with the class asthis. A hook for another flow on a@Jobclass stops the server from starting. See Hooking every attempt of a job. - A hook that throws fails the attempt, and the job's
retryapplies, unless the error is public, includingJobNotAuthorizedError. A throw from aFinallyhook is logged and ignored. ctx.respond({ result, logs })answers for the job, from a cache say: the stages that haven't run are skipped,execute()included, apart from thealwaysgroup, and the run completes withresultandlogs.resultis checked againstoutputSchema: extra fields are dropped, and a mismatch fails withINVALID_OUTPUTwithout retrying. Changed in 1.9.5: before, hook results skipped validation.
Built-in tools
When any app declares a job or a workflow, FrontMCP adds these tools to the server:
| Tool | In tools/list | Arguments | Returns |
|---|---|---|---|
execute_job | Yes | name, input? (an object, default {}), background? (default false) | Without background: waits for the job, then { runId, state, uri, result, logs }. With background: true: { runId, state: "pending", uri } at once. |
get_job_status | Yes | runId | { runId, jobName, state, result?, error?, startedAt, completedAt?, attempt, logs }. Times are milliseconds since 1970. It also reads a workflow's run, whose result holds the step results. The owner or a caller passing an explicit read rule can read it: see who can read a run. |
cancel_job | Yes | runId | { runId, state: "cancelled" }. Owner or a caller passing an explicit delete rule only. Cannot cancel workflows or finished runs. |
list_jobs | No | query?, tags?, labels? | { jobs: [{ name, description?, tags, labels, inputSchema? }], count }. query matches the name or description; tags needs any one of them; labels needs all of them. |
update_job | No; requires dynamic registration | name, script?, inputSchema?, outputSchema?, description?, tags? | { success, jobId }; replaces supplied fields on a dynamic job, subject to update permissions. |
remove_job | No | name | Removes a job registered at run time with register_job. For a @Job class it fails with Job "…" is not a dynamic job and cannot be removed. |
execute_workflow and get_workflow_status come with them; see @Workflow. Tools that aren't in tools/list can still be called by name. The update tools are exported as UpdateJobTool and UpdateWorkflowTool. The built-in tool classes are exported from @frontmcp/sdk and @frontmcp/sdk/job/tools; both paths return the same classes. Changed in 1.11.0: before, the subpath shipped types without loadable JavaScript.
Another job tool, register_job, registers a job from a script sent by the client. It exists only on servers that set jobs: { enabled: true, allowDynamicRegistration: true }, and isn't in tools/list there either. It runs code a client sent you, so leave it off unless you know you need it.
@FrontMcp({ jobs })
The server's jobs option controls the subsystem. You don't need it to use jobs.
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | on when an app declares jobs or workflows | Required when you set jobs. false leaves the tools out even when apps declare jobs; true adds them even when none do. |
store | false | { redis?, sqlite?, keyPrefix? } | top-level Redis except Vercel KV, then SQLite, then memory | Storage for runs and dynamic definitions. false forces memory. SQLite needs a path; Redis takes the server's Redis options. Explicit Redis and SQLite are mutually exclusive. Vercel KV is unsupported for job stores. |
defaultTimeoutMs | number | 300000 | Deadline per attempt when a job sets no timeout. 0 disables it. |
runner | "inline" | "worker" | "detached" | "inline" | Default runner. A job may override it. |
admission | { concurrency?: number; memoryMb?: number; maxWaitMs?: number } | no cap; maxWaitMs: 600000 | Bounds concurrent attempts and memory claims per scope, for jobs and workflow steps. An execute_job deadline starts at execution; a workflow step's timeout includes its wait for admission. |
allowDynamicRegistration | boolean | false | Adds register_job, register_workflow, update_job and update_workflow. |
The Playground always uses the memory store: Redis needs Node. The redis fields were checked in Node against a Redis that needs a password. Without the right password, the server doesn't start: NOAUTH Authentication required. when there's none, WRONGPASS invalid username-password pair when it's wrong. A field that contradicts the url stops it with a ZodError that names the field, like redis password contradicts redis.url.
Run states
| State | Meaning |
|---|---|
pending | Created, not started yet. A background call returns this. |
running | An attempt is running. |
retrying | An attempt failed, and the job is waiting before the next one. |
completed | result holds the result. |
timed_out | The last attempt exceeded its deadline. |
cancelled | A caller cancelled the run. |
interrupted | The server shut down or its runner disappeared. |
failed | Every attempt failed. error holds the last error's message and name. |
Who can read a run
A run belongs to the user who started it, identified by their token's issuer (iss) and sub: in-process callers of create() and createDirect() have the issuer direct, unless their authContext.user sets an iss. get_job_status and job://runs/{runId} answer that user or a caller passing the entry's explicit read permission rule. Other callers get Run "<id>" not found from the tool, or Resource not found: job://runs/<id> from the resource, as if the run did not exist. A run another server or endpoint started isn't reachable from this one, even when they share a store. Changed in 1.12.1: before, the owner was the sub alone, and a shared store let any of them reach the run. A run stored before 1.12.1, with no ownerIss, now belongs only to a caller whose token has no issuer. A run a workflow's schedule started has no owner, so only a caller passing an explicit read rule reads it.
An anonymous caller on protocol 2026-07-28 gets a new identity on every request (anon: and a random id), so it cannot prove ownership of its runs without an explicit read rule. That includes the Playground. To let clients poll background runs, authenticate them. The examples below poll as a signed-in user, in-process, with FrontMcpInstance.createDirect().
Caveats
- The class must extend
JobContext, and like@Tool,@Jobchecks when TypeScript compiles thatexecute()'s parameter matchesinputSchemaand its return type matchesoutputSchema. - Hooks run once per attempt. A
JobHooksees every retry and every workflow step as an attempt of its own. Since 1.9.4: before, jobs ran through no flow, so a hook on theexecute_jobtool's call missed retries, background attempts and workflow steps, and a hook on a@Jobclass stopped the server from starting. - A result that doesn't match
outputSchemaisn't retried: the run fails at once, whateverretrysays. - Changed in 1.11.0: before,
execute_jobignoredtimeout. Every attempt now has a deadline; use0for no limit. - Changed in 1.11.3: before, bad input used a generic error code and public errors were retried. Bad input now fails once with
INVALID_INPUTand the Zod issues, without a stack. APublicMcpErroror subclass is not retried. Throw a plainErrororInternalMcpErrorfor a retryable failure. - Changed in 1.11.0: before, jobs used memory unless
jobs.storewas set. They now inherit top-level Redis (except Vercel KV) or SQLite. Usejobs.store: falseto keep them in memory.
Runners and durable run handles
runner: "inline" is the default. "worker" uses the offload pool, where providers are unavailable. "detached" requires a shared job store and a Node server launched from a runnable entry (bootstrap(), runStdio(), runUnixSocket() or @FrontMcp); in-process create(), connect() and the generated CLI cannot start detached runs.
On a shared store, runner heartbeats allow a restarting server to reconcile unfinished runs. A run whose runner disappeared becomes interrupted and its cleanup runs in the reconciling server; a live detached run is watched. Shutdown interrupts inline runs and waits at most lifecycle.shutdownHookTimeoutMs.
Read the uri returned by execute_job (job://runs/{runId}) for JSON with state, progress, revision, updatedAt, result or error and logs. Revisions advance on writes. Subscribers get resource-update notifications for writes made by that process. Access follows the same owner or explicit read rule as status polling; cancellation uses the owner or explicit delete rule. cancel_job cannot cancel workflows.
Custom execution managers and stores
Most servers use the manager FrontMCP creates. A custom host can construct new JobExecutionManager(stateStore, logger, notifyFn?, scope?, options?). Its new options are:
| Option | Type | Default | Description |
|---|---|---|---|
defaultTimeoutMs | number | 300000 | Attempt deadline; 0 disables it. |
admission | JobAdmission | none | Admission controller shared by this manager's attempts: new JobAdmission({ concurrency?, memoryMb?, maxWaitMs? }), the options of jobs.admission. See below. |
cancelPollMs | number | no polling | Interval for checking cancellation written by another process. |
runner | JobRunner | "inline" | Default runner. |
findJob | (name: string) => JobEntry | undefined | none | Resolve a detached run's job or an orphaned run's cleanup. |
detachedUnavailable | { why: string; remedy: string } | none | Refuse detached runs with this explanation. |
spawnDetached | (runId: string) => { pid?: number; once(event: "error", listener: (error: Error) => void): unknown } | rerun the server's command | Start a detached worker. |
cancel(runId) returns Promise<void> and cancels an unfinished job. dispose(timeoutMs?) interrupts this manager's active runs and waits, optionally with a deadline; detached runs keep running. reconcile() settles runs whose runner disappeared and watches live detached runs. runDetached(runId) executes that run in the current worker process; an unknown or finished run is left alone. Both return Promise<void>.
Custom JobStateStore implementations can add these optional methods:
| Method | Returns | Description |
|---|---|---|
requestCancel(runId) | Promise<void> | Keep a cancellation request visible to every process. |
isCancelRequested(runId) | Promise<boolean> | Read that cancellation request. Without these methods, the manager checks the run's cancelled state. |
touchRunner(runnerId, ttlSeconds) | Promise<void> | Renew a runner heartbeat with the store's TTL. |
isRunnerAlive(runnerId) | Promise<boolean> | Check the heartbeat. Without heartbeat methods, liveness uses the PID on its host. |
claimRun(runId) | Promise<boolean> | Atomically let one reconciler settle an orphan and run cleanup. |
createRun() starts at revision 1; updateRun() increments the revision and stamps updatedAt. Run records can carry progress, runner and scopeId. A run's resource URI is job://runs/{runId}, and who can read a run gives the access rules the built-in tools and that resource apply.
The helpers a custom host uses
@frontmcp/sdk exports what the built-in job tools use to limit attempts and check access, so a host of your own can do the same. New in 1.11.1: before, none of the three was exported.
| Export | What it does |
|---|---|
new JobAdmission({ concurrency?, memoryMb?, maxWaitMs? }) | Limits the attempts that run at once, as jobs.admission does: concurrency attempts, each claiming memoryMb of free memory, admitted in the order they arrived. maxWaitMs defaults to 600000. Pass it as the manager's admission. slot() returns a JobAdmissionSlot, a type @frontmcp/sdk exports too: acquire(jobName, signal?) waits for a place, and rejects with JobAdmissionTimeoutError after maxWaitMs; release() frees it. |
jobRunUri(runId) | The run's resource URI, job://runs/<runId>. |
mayAccessRun(scope, run, action, authInfo) | Promise<boolean>: whether the caller in authInfo may "read" or "delete" (cancel) the run, by the rules in who can read a run: the owner may, and anyone else only through the job's or workflow's permissions rule for that action. scope is the ScopeEntry, this.scope in a tool. |
import { jobRunUri, mayAccessRun, Tool, ToolContext, z, type JobRunRecord } from "@frontmcp/sdk";
// A run as your host's own store keeps it.
const runs = new Map<string, JobRunRecord>([
["run-1", { runId: "run-1", jobId: "export-invoices", jobName: "export-invoices", ownerSub: "nour", ownerIss: "direct", state: "completed", input: {}, startedAt: 0, attempt: 1, maxAttempts: 1, logs: [], background: true }],
]);
@Tool({ name: "run_handle", description: "Get the resource URI of a run the caller may read", inputSchema: { runId: z.string() } })
export class RunHandle extends ToolContext {
async execute({ runId }: { runId: string }) {
const run = runs.get(runId);
const readable = run !== undefined && (await mayAccessRun(this.scope, run, "read", this.context.authInfo));
return { uri: readable ? jobRunUri(run.runId) : null };
}
}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
The Playground's own call is anonymous, so it gets { "uri": null }: an anonymous caller isn't the owner, and has no billing role.
Usage
Cancelling a run and reading its handle
This job waits for cancellation. The test uses one signed-in caller so its later requests own the same run.
import { App, Job, JobContext, z } from "@frontmcp/sdk";
@Job({ name: "wait-for-cancel", description: "Wait until the owner cancels the run", inputSchema: {}, outputSchema: { stopped: z.boolean() }, timeout: 5000 })
class WaitForCancel extends JobContext {
async execute() {
await new Promise<void>((resolve) => {
if (this.signal?.aborted) return resolve();
this.signal?.addEventListener("abort", () => resolve(), { once: true });
});
return { stopped: true };
}
}
@App({ name: "Desk", jobs: [WaitForCancel] })
export class Desk {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Running a job and reading its result
Call execute_job with the job's name and its input. It waits for the job and returns the run: its id, its state, the result, and the lines the job logged.
import { Job, JobContext, z } from "@frontmcp/sdk";
const tickets = [
{ id: "T-1", customer: "Ada", status: "open" },
{ id: "T-2", customer: "Grace", status: "closed" },
{ id: "T-3", customer: "Ada", status: "open" },
];
@Job({
name: "count-open-tickets",
description: "Count a customer's open tickets",
inputSchema: { customer: z.string().min(1) },
outputSchema: { customer: z.string(), open: z.number() },
})
export class CountOpenTickets extends JobContext {
async execute({ customer }: { customer: string }) {
this.log(`Counting open tickets for ${customer}`);
const open = tickets.filter((t) => t.customer === customer && t.status === "open").length;
return { customer, open };
}
}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Open the Tests tab. The app declares no tools, yet the server has five: FrontMCP added them for the job.
Failing
A job fails when execute() throws, and execute_job returns an isError result. What the client reads depends on how the job failed:
Failures
Example 1 of 3
Bad input
Input that doesn't match inputSchema fails with INVALID_INPUT and Invalid input for job "…", followed by the Zod issues. The message reaches production clients too, and the attempt is not retried.
import { App, Job, JobContext, z } from "@frontmcp/sdk";
@Job({
name: "count-open-tickets",
inputSchema: { customer: z.string().min(1) },
outputSchema: { customer: z.string(), open: z.number() },
})
export class CountOpenTickets extends JobContext {
async execute({ customer }: { customer: string }) {
return { customer, open: 2 };
}
}
@App({ id: "help-desk", name: "Help Desk", jobs: [CountOpenTickets] })
export class HelpDeskApp {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Example 2 of 3
A thrown error
A plain Error fails with TOOL_EXECUTION_ERROR. In development the text has the message and the stack; in production, only "Internal FrontMCP error" and an error ID.
import { App, Job, JobContext, z } from "@frontmcp/sdk";
@Job({
name: "count-open-tickets",
inputSchema: { customer: z.string() },
outputSchema: { customer: z.string(), open: z.number() },
})
export class CountOpenTickets extends JobContext {
async execute({ customer }: { customer: string }): Promise<{ customer: string; open: number }> {
throw new Error("The ticket database is down");
}
}
@App({ id: "help-desk", name: "Help Desk", jobs: [CountOpenTickets] })
export class HelpDeskApp {}import { test, expect } from "@frontmcp/testing";
test("the message follows the tool's", async ({ mcp }) => {
const result = await mcp.tools.call("execute_job", { name: "count-open-tickets", input: { customer: "Ada" } });
expect(result).toBeError("TOOL_EXECUTION_ERROR");
expect(result.text()).toMatch(/^Tool "execute_job" execution failed: The ticket database is down\n/);
});Example 3 of 3
A public error
this.fail() with a PublicMcpError sends your message and code as they are, in development and in production. Use it for failures the model can act on.
import { App, Job, JobContext, PublicMcpError, z } from "@frontmcp/sdk";
const customers = ["Ada", "Grace"];
@Job({
name: "count-open-tickets",
inputSchema: { customer: z.string() },
outputSchema: { customer: z.string(), open: z.number() },
})
export class CountOpenTickets extends JobContext {
async execute({ customer }: { customer: string }) {
if (!customers.includes(customer)) {
this.fail(new PublicMcpError(`There's no customer ${customer}.`, "CUSTOMER_NOT_FOUND"));
}
return { customer, open: 2 };
}
}
@App({ id: "help-desk", name: "Help Desk", jobs: [CountOpenTickets] })
export class HelpDeskApp {}import { test, expect } from "@frontmcp/testing";
test("the client reads the message and the code", async ({ mcp }) => {
const result = await mcp.tools.call("execute_job", { name: "count-open-tickets", input: { customer: "Zed" } });
expect(result).toBeError("CUSTOMER_NOT_FOUND");
expect(result.text()).toBe("There's no customer Zed.");
});Retrying a job that fails
With retry, a failed attempt is tried again after a wait. Here the mail server is busy two times out of three, so the job succeeds on its third attempt, after waiting 100 and then 200 milliseconds:
import { Job, JobContext, z } from "@frontmcp/sdk";
import { sendEmail } from "./mail";
@Job({
name: "notify-agent",
description: "Email a support agent about a ticket",
inputSchema: { agent: z.string(), ticket: z.string() },
outputSchema: { sent: z.boolean() },
retry: { maxAttempts: 3, backoffMs: 100 },
})
export class NotifyAgent extends JobContext {
async execute({ agent, ticket }: { agent: string; ticket: string }) {
this.log(`Attempt ${this.attempt}: emailing ${agent} about ${ticket}`);
sendEmail(agent, `${ticket} needs you`);
return { sent: true };
}
}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
If the last attempt fails too, the call fails with that attempt's error. this.attempt says which attempt is running. Only retry work that's safe to repeat: here, a second email is better than none, but a job that charges a card needs to know whether the first attempt went through.
Running a job in the background
With background: true, execute_job returns a runId at once, and the job runs after the call has returned. The caller that started it polls get_job_status with the runId until the run is completed or failed.
import { Job, JobContext, z } from "@frontmcp/sdk";
@Job({
name: "export-tickets",
description: "Export a customer's tickets as CSV",
inputSchema: { customer: z.string() },
outputSchema: { customer: z.string(), csv: z.string() },
})
export class ExportTickets extends JobContext {
async execute({ customer }: { customer: string }) {
this.log(`Exporting tickets for ${customer}`);
await new Promise((resolve) => setTimeout(resolve, 100)); // stands in for a slow query
return { customer, csv: "id,title\nT-1,Cannot log in\nT-3,Login link expired" };
}
}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Without the TC39 AsyncContext, FrontMCP's browser build serves one request at a time and runs a background job before the next one, so there the first poll already finds the run completed. The Playground provides a minimal AsyncContext, so here the run is still running at first, as on Node.
The Call tab shows the pending run. Calling get_job_status with its runId from the Call tab fails with "not found": the Playground's caller is anonymous, and nobody can read an anonymous caller's runs, not even that caller. The last test signs in as nour, who can, and sam, who can't. Running Jobs in the Background walks through polling.
Using a provider
A job gets providers with this.get(), from its app and from the server, as the app's tools do. Both get the same instance, so a tool and a job share data:
import { Job, JobContext, z } from "@frontmcp/sdk";
import { TicketStore } from "./ticket-store";
@Job({
name: "count-open-tickets",
inputSchema: { customer: z.string() },
outputSchema: { customer: z.string(), open: z.number() },
})
export class CountOpenTickets extends JobContext {
async execute({ customer }: { customer: string }) {
return { customer, open: this.get(TicketStore).openFor(customer).length };
}
}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
A provider in @FrontMcp({ providers }) works too, and is shared with every app. A provider on another app isn't available to the job: see Troubleshooting. (Changed in 1.9.2: before, a job only saw the server's providers.)
Calling another service from a job
this.fetch() works in a job as in a tool, and sends the request's tracing headers, so the other service's logs tie its request to the call that started the job. A background run keeps the caller's trace:
import { Job, JobContext, z } from "@frontmcp/sdk";
@Job({
name: "sync-customer",
description: "Copy a customer's plan from the CRM",
inputSchema: { customerId: z.string() },
outputSchema: { customerId: z.string(), plan: z.string() },
})
export class SyncCustomer extends JobContext {
async execute({ customerId }: { customerId: string }) {
const response = await this.fetch(`https://crm.example/customers/${customerId}`);
const { plan } = await response.json();
return { customerId, plan };
}
}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
In the background, this.context is a copy of the starting call's: the same session, caller and trace, and a request id of its own, since the call it came from has already returned. (Changed in 1.9.2: before, a job had no request context, this.context threw, and this.fetch() sent no tracing headers.)
Restricting who can run a job
permissions limits a job to callers with a role, a scope, or anything a function can check. Anyone else gets the same error as for a job that doesn't exist, and list_jobs doesn't show them the job:
import { Job, JobContext, z } from "@frontmcp/sdk";
@Job({
name: "export-invoices",
description: "Export a month's invoices",
inputSchema: { month: z.string().regex(/^\d{4}-\d\d$/) },
outputSchema: { month: z.string(), invoices: z.number() },
permissions: [{ action: "execute", roles: ["billing"] }],
})
export class ExportInvoices extends JobContext {
async execute({ month }: { month: string }) {
return { month, invoices: 42 };
}
}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Hooking every attempt of a job
A JobHook runs for each attempt of a job, so a plugin can audit, time or cache job runs the way it hooks tool calls. ctx.state.attempt tells the attempts apart, and ctx.state.flowError is set in the always stages when the attempt failed.
Job hooks
Example 1 of 3
Seeing each attempt
The plugin records how each attempt ended. The mail server is busy two times out of three, so one call makes three attempts:
import { DynamicPlugin, FlowCtxOf, JobHook, Plugin } from "@frontmcp/sdk";
export const attempts: string[] = [];
@Plugin({ name: "attempt-log" })
export class AttemptLogPlugin extends DynamicPlugin<object> {
@JobHook.Did("finalize")
async record(ctx: FlowCtxOf<"jobs:execute-job">) {
const { job, attempt, flowError } = ctx.state;
attempts.push(`${job?.name} attempt ${attempt}: ${flowError ? flowError.message : "completed"}`);
}
}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Example 2 of 3
Answering from a cache
A hook can answer for the job with ctx.respond({ result, logs }). This one saves each report the job builds, and answers the next request for the same day from it, without running execute():
import { DynamicPlugin, FlowCtxOf, JobHook, Plugin } from "@frontmcp/sdk";
const reports = new Map<string, unknown>();
@Plugin({ name: "report-cache" })
export class ReportCachePlugin extends DynamicPlugin<object> {
@JobHook.Will("execute", { filter: (ctx) => ctx.state.job?.name === "build-daily-report" })
async answerFromCache(ctx: FlowCtxOf<"jobs:execute-job">) {
const { day } = ctx.state.parsedInput as { day: string };
if (reports.has(day)) ctx.respond({ result: reports.get(day), logs: [`Report for ${day} from the cache`] });
}
@JobHook.Did("validateOutput", { filter: (ctx) => ctx.state.job?.name === "build-daily-report" })
async save(ctx: FlowCtxOf<"jobs:execute-job">) {
const { day } = ctx.state.parsedInput as { day: string };
reports.set(day, ctx.state.answer?.result);
}
}import { Job, JobContext, z } from "@frontmcp/sdk";
export const built: string[] = [];
@Job({
name: "build-daily-report",
description: "Count the tickets opened and closed on one day.",
inputSchema: { day: z.string() },
outputSchema: { day: z.string(), opened: z.number(), closed: z.number() },
})
export class BuildDailyReport extends JobContext {
async execute({ day }: { day: string }) {
built.push(day);
this.log(`Read every ticket of ${day}`);
return { day, opened: 12, closed: 9 };
}
}import { App } from "@frontmcp/sdk";
import { BuildDailyReport } from "./build-daily-report.job";
import { ReportCachePlugin } from "./report-cache.plugin";
@App({ id: "help-desk", name: "Help Desk", jobs: [BuildDailyReport], plugins: [ReportCachePlugin] })
export class HelpDeskApp {}import { test, expect } from "@frontmcp/testing";
import { built } from "./build-daily-report.job";
test("the second run of a day is answered from the cache", async ({ mcp }) => {
built.length = 0;
const run = () => mcp.tools.call("execute_job", { name: "build-daily-report", input: { day: "2026-09-25" } });
const first = (await run()).json();
const second = (await run()).json();
expect(built).toEqual(["2026-09-25"]);
expect(first.logs).toEqual([expect.stringMatching(/\] Read every ticket of 2026-09-25$/)]);
expect(second).toEqual({
runId: expect.any(String),
uri: expect.stringMatching(/^job:\/\/runs\//),
state: "completed",
result: { day: "2026-09-25", opened: 12, closed: 9 },
logs: ["Report for 2026-09-25 from the cache"],
});
});The answer becomes the run's result, which get_job_status returns too. It is checked against outputSchema, as a result returned by the job is.
Example 3 of 3
On the job class
A @Job class can declare hooks for its own attempts. Stages before createJobContext run before the job's instance exists, so a hook on them is a static method, with the class as this. Here a static hook tidies the input before inputSchema checks it, and an instance hook adds a line to the run's logs:
import { FlowCtxOf, Job, JobContext, JobHook, z } from "@frontmcp/sdk";
const tickets = [
{ id: "T-1", customer: "Ada", status: "open" },
{ id: "T-3", customer: "Ada", status: "open" },
];
@Job({
name: "count-open-tickets",
inputSchema: { customer: z.enum(["Ada", "Grace"]) },
outputSchema: { customer: z.string(), open: z.number() },
})
export class CountOpenTickets extends JobContext {
@JobHook.Will("validateInput")
static tidyCustomer(ctx: FlowCtxOf<"jobs:execute-job">) {
const { customer } = ctx.state.input as { customer: string };
const name = customer.trim();
ctx.state.set("input", { customer: name.charAt(0).toUpperCase() + name.slice(1).toLowerCase() });
}
@JobHook.Did("execute")
async noteAttempt() {
this.log(`Counted on attempt ${this.attempt}`);
}
async execute({ customer }: { customer: string }) {
return { customer, open: tickets.filter((t) => t.customer === customer && t.status === "open").length };
}
}import { App } from "@frontmcp/sdk";
import { CountOpenTickets } from "./count-open.job";
@App({ id: "help-desk", name: "Help Desk", jobs: [CountOpenTickets] })
export class HelpDeskApp {}import { test, expect } from "@frontmcp/testing";
import { App, FrontMcpInstance, Job, JobContext, JobHook, z } from "@frontmcp/sdk";
test("the static hook tidies the input, and the instance hook logs", async ({ mcp }) => {
const run = (await mcp.tools.call("execute_job", { name: "count-open-tickets", input: { customer: " ada " } })).json();
expect(run.result).toEqual({ customer: "Ada", open: 2 });
expect(run.logs).toEqual([expect.stringMatching(/\] Counted on attempt 1$/)]);
});
test("an instance hook before `createJobContext` stops the server", async () => {
@Job({ name: "count-open-tickets", inputSchema: { customer: z.string() }, outputSchema: { open: z.number() } })
class TidyCountJob extends JobContext {
@JobHook.Will("validateInput")
async tidyCustomer() {}
async execute() {
return { open: 2 };
}
}
@App({ id: "help-desk", name: "Help Desk", jobs: [TidyCountJob] })
class HelpDeskApp {}
const starting = FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] });
await expect(starting).rejects.toThrow(
"Job \"TidyCountJob\" declares hooks that would never run: tidyCustomer() (will 'validateInput' of jobs:execute-job): runs before 'createJobContext' builds the instance it runs on; declare it as a static method to run it without an instance.",
);
});A plugin or a provider on an app hooks that app's jobs only. To hook every job a server runs, register the plugin on @FrontMcp. Hooks covers Will, Did, Finally, Around and Stage, which work on JobHook as on every flow.
Writing a job as a function
For a small job that doesn't log, the function form is shorter. The handler gets the JobContext as its second argument, for ctx.get() and ctx.auth.
import { App, job, z } from "@frontmcp/sdk";
export const shout = job({
name: "shout",
inputSchema: { text: z.string() },
outputSchema: { text: z.string() },
})(async ({ text }) => {
return { text: text.toUpperCase() };
});
@App({ id: "help-desk", name: "Help Desk", jobs: [shout] })
export class HelpDeskApp {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Checking a hook's cached result
A cache can return stale data whose shape no longer matches the job. Hook answers go through outputSchema too: a mismatch fails with INVALID_OUTPUT, without retrying.
import { Job, JobContext, JobHook, z } from "@frontmcp/sdk";
export let cacheReads = 0;
@Job({ name: "cached-count", inputSchema: {}, outputSchema: { open: z.number() }, retry: { maxAttempts: 3, backoffMs: 1 } })
export class CachedCount extends JobContext {
@JobHook.Will("execute")
cached(ctx: any) {
cacheReads += 1;
ctx.respond({ result: { open: "twelve" }, logs: [] });
}
async execute() {
return { open: 12 };
}
}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Updating a runtime job
With jobs.allowDynamicRegistration, update_job replaces only the fields supplied. The same option serves update_workflow for dynamic workflows. Neither changes a class declared in code.
import { test, expect } from "@frontmcp/testing";
import { FrontMcpInstance } from "@frontmcp/sdk";
test("update_job replaces the description and keeps its tags", async () => {
const server = await FrontMcpInstance.createDirect({
info: { name: "help-desk", version: "1.0.0" }, apps: [],
jobs: { enabled: true, allowDynamicRegistration: true },
});
try {
await server.callTool("register_job", { name: "count-tickets", script: "return { count: 2 };", description: "Old description", tags: ["tickets"] });
const result = await server.callTool("update_job", { name: "count-tickets", description: "Count open tickets" });
expect(result.structuredContent).toEqual({ success: true, jobId: "count-tickets" });
const listed = await server.callTool("list_jobs", {});
expect((listed.structuredContent as any).jobs).toContainEqual(expect.objectContaining({
name: "count-tickets", description: "Count open tickets", tags: ["tickets"],
}));
} finally { await server.dispose(); }
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Troubleshooting
Job "…" is declared in code and cannot be updated
update_job only changes jobs made with register_job. Edit a declared class and restart the server instead. The error code is INVALID_INPUT.
Job or workflow "…" not found or not permitted
execute_job found no job by that name that the caller may run. Check, in order:
- The name is spelled as in
@Job({ name }). If the job also setsid, use theid. - The class is in an app's
jobsarray, and the app is in@FrontMcp({ apps }). - The job's
permissionslet this caller run it. The error is the same on purpose, so a caller can't tell a job they may not run from one that doesn't exist. Calllist_jobsas that caller to see what they can run.
Run "…" not found
get_job_status answers the owner or a caller passing the job's explicit read rule, and says "not found" to everyone else. An anonymous caller on protocol 2026-07-28, like the Playground's, can't read its own runs either, because each of its requests has a new identity. See who can read a run. Also check that the runId is from this server since its last restart: runs use memory when no shared backend is configured.
Provider "…" is not available in a job
A job resolves providers from its own app and from the server, so a provider registered on another app is missing:
import { App, FrontMcp, Job, JobContext, Provider, z } from "@frontmcp/sdk";
@Provider({ name: "TicketStore" })
export class TicketStore {
openFor(customer: string) {
return customer === "Ada" ? ["T-1", "T-3"] : [];
}
}
@Job({
name: "count-open-tickets",
inputSchema: { customer: z.string() },
outputSchema: { customer: z.string(), open: z.number() },
})
export class CountOpenTickets extends JobContext {
async execute({ customer }: { customer: string }) {
return { customer, open: this.get(TicketStore).openFor(customer).length };
}
}
@App({ id: "help-desk", name: "Help Desk", jobs: [CountOpenTickets] })
export class HelpDeskApp {}
// 🚩 TicketStore is on another app
@App({ id: "tickets", name: "Tickets", providers: [TicketStore] })
export class TicketsApp {}
@FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp, TicketsApp] })
export default class Server {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Register the provider on the job's app, or on the server with @FrontMcp({ providers }) to share it between apps, as in Using a provider. Before 1.9.2, a job didn't see its own app's providers either, so servers written for 1.9.1 often have them on @FrontMcp, where they still work.
Invalid input for job "…"
The input didn't match the job's inputSchema. Each entry in the list has the field's path and a message. See Bad input. Bad input is not retried, whatever the retry policy.
A job runs past its timeout
execute_job enforces the job's timeout, or jobs.defaultTimeoutMs (300000 ms). Changed in 1.11.0: before, only workflow steps enforced a timeout. Set timeout: 0 on a job for unlimited attempts, or jobs.defaultTimeoutMs: 0 to make that the default for jobs that set no timeout. When a deadline passes, the attempt fails with JOB_TIMEOUT and its signal aborts:
import { App, Job, JobContext, z } from "@frontmcp/sdk";
@Job({ name: "export-tickets", inputSchema: {}, outputSchema: { rows: z.number() }, timeout: 50 })
export class ExportTickets extends JobContext {
async execute() {
await new Promise((resolve) => setTimeout(resolve, 150));
return { rows: 3 };
}
}
@App({ id: "help-desk", name: "Help Desk", jobs: [ExportTickets] })
export class HelpDeskApp {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Pass this.signal to cancellable work, or check it inside a loop. A timeout ends the attempt immediately; JavaScript that ignores the signal can keep running beside its retry.
Tool output validation failed (output does not match outputSchema at …)
The job returned something outputSchema doesn't describe, and the text names the first field that doesn't match. execute_job fails with INVALID_OUTPUT, a background run fails with InvalidOutputError in its error, and the job isn't retried, even with retry. Fields the schema doesn't declare are dropped instead:
import { App, Job, JobContext, z } from "@frontmcp/sdk";
export let attempts = 0;
// Stands in for rows from a database you don't control: "open" comes back as text.
const rows: Record<string, Record<string, unknown>> = {
Ada: { open: "2", internalNote: "VIP" },
Grace: { open: 0, internalNote: "Prefers email" },
};
@Job({ name: "count-open-tickets", inputSchema: { customer: z.string() }, outputSchema: { open: z.number() }, retry: { maxAttempts: 3, backoffMs: 10 } })
export class CountOpenTickets extends JobContext {
async execute({ customer }: { customer: string }) {
attempts += 1;
return rows[customer] as { open: number };
}
}
@App({ id: "help-desk", name: "Help Desk", jobs: [CountOpenTickets] })
export class HelpDeskApp {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
TypeScript catches most mismatches when execute() returns a typed value. For data you don't control, build the result from the fields you mean to send, or parse it with the schema yourself, z.object({ open: z.number() }).parse(row), and fail with a PublicMcpError when it doesn't parse. (Changed in 1.9.2: before, FrontMCP didn't check the result, and sent it as it was.)
Job "…" declares hooks that would never run
The server doesn't start, with InvalidHookFlowError: a @Job class has an instance method hook on a stage before createJobContext, where the job's instance doesn't exist yet. The message names the method and the stage, and says to declare it as a static method. Make it static, and read what it needs from its ctx argument instead of this, as On the job class does. Job "…" has hooks for unsupported flows means a hook on the class is for another flow, like a ToolHook: move it to a plugin or a provider.
TypeScript says Unable to resolve signature of class decorator
@Job checks the class against its options, like @Tool. Error TS1238 on the decorator line says which check failed:
'execute() parameter error': "Parameter type does not match the input schema.":execute()'s parameter type disagrees withinputSchema.'execute() return type error': "The method's return type is not assignable to the expected output schema type.":execute()returns somethingoutputSchemadoesn't describe.'Job class error': "Class must extend JobContext": the class doesn't extendJobContext.
A @Job without outputSchema doesn't compile either, and fails when the class is loaded with a Zod issue at the path outputSchema.