@Duty

Checked against FrontMCP 1.12.2 on

A timer in a provider runs in every copy of a server. @Duty gives recurring work a lease, so one process runs it: one on a machine, one in a workspace, or one among all the machines that share the server's Redis. It runs every interval or at the times of a cron expression. Use it for refreshing an index, clearing old files or a report every weekday morning; use a job for work a client starts and follows by run id, and a worker for work that never ends by itself.

@Provider()
@Duty({ name?, every | cron, timezone?, scope, leaseMs? })
class RefreshIndex {
  async run({ signal }: DutyRunContext) { /* refresh while the lease is held */ }
}

Reference

@Duty(options)

Decorate a provider class with a run(context) method and register it in providers. @Duty marks the class as a provider, so @Provider() is optional.

OptionTypeDefaultDescription
namestringclass nameLease name within the server. Set it explicitly when a build renames classes.
everynumber | stringone of every or cronPositive whole milliseconds or a duration such as "500ms", "30s", "5m", "1h" or "1d". At most 2147483647 ms.
cronstringone of every or cronA cron expression of five fields, or six with seconds first. See cron schedules. New in 1.12.0.
timezonestring"UTC"The IANA time zone cron is read in, such as "Europe/Berlin". Only with cron. New in 1.12.0.
scope"machine" | "workspace" | "cluster"requiredAmong which processes one holds the lease. See scopes and leases. "cluster" is new in 1.12.0.
leaseMsnumberthree intervals, clamped to 3000–60000 ms; 60000 ms with cronLease lifetime; renewed every third of it. Minimum 1000 ms.

A duty has exactly one of every and cron. scope is required with both: TypeScript refuses a @Duty without it.

run({ signal }) returns void or a promise. The signal aborts on lease loss or shutdown. A run that would start while the last one is still running is skipped, not queued; an exception is logged as Duty "<name>" failed: <cause> and the holder keeps the lease. Another process can take over after the holder stops renewing its lease.

dutyMetadataOf(instance) returns its class's ResolvedDutyMetadata: name, scope, leaseMs, and either everyMs or cron: { expression, timezone }. It returns undefined when the class has none. dutyMetadataSchema validates the decorator options and converts every to milliseconds.

Cron schedules

New in 1.12.0. cron takes five fields, minute hour day-of-month month day-of-week, or six with second first. The framework reads it with croner, a dependency of @frontmcp/sdk that loads when the first duty or workflow with a cron is built.

ExpressionRuns
0 9 * * 1-5At 09:00, Monday to Friday
*/15 * * * *Every 15 minutes
0 0 1 * *At midnight on the first of each month
0 8-18/2 * * MON,WED,FRIEvery second hour from 08:00 to 18:00 on three weekdays
*/10 * * * * *Every 10 seconds (six fields)
@dailyAt midnight; @hourly works too
  • Fields. Lists (1,15), ranges (1-5), steps (*/15, 8-18/2), month and day names; 0 and 7 are both Sunday. When both day-of-month and day-of-week are set, the duty runs on either: 0 0 13 * FRI runs on the 13th and on every Friday.
  • Time zone. The expression is read in timezone, "UTC" by default. A local time the clocks skip in spring (30 2 * * * in Europe/Berlin on the last Sunday of March) runs once, at 03:00 when the clocks resume. A time they repeat in autumn runs once, the first time.
  • First start. A cron duty does not run when the server starts. It waits for its next scheduled time.
  • Catching up. The lease store keeps the time the schedule was last taken, without expiry. A process that gets the lease after a restart or a takeover compares it with the clock: when a scheduled time passed since, it runs once now, however many were missed, then continues on schedule.
  • Skipped while running. A scheduled time that comes while the last run is still running is skipped: with * * * * * * and a run of 2.5 seconds, the duty ran every third second.
  • At most once. A scheduled time is taken before its run starts. A holder that dies after taking it loses that run: the process that takes over runs only the scheduled times after it. A scheduled workflow, whose run is a record in the job store, is recovered instead.

An expression that can't be read stops startup: a wrong field, a seventh (year) field, a date, or one that never matches a date, such as 0 0 30 2 *. See errors.

Scopes and leases

Every copy of the server registers the duty. The one whose id is stored under the lease key runs it; the others try to take the lease at each check.

ScopeOne holder amongNeeds
"machine"The processes of one machine that run a server with the same info.name@frontmcp/storage-sqlite, or a top-level redis
"workspace"Those of them that run from the same project root: the nearest folder at or above the working directory with a package.jsonThe same
"cluster"Every process, on every machine, that shares the server's top-level redis. New in 1.12.0.A top-level redis that is a Redis provider. Without one the server does not start.

Where the lease lives:

ServerScopeStoreKey
No top-level redis"machine", "workspace"The SQLite file ~/.frontmcp/duties.sqlite, or $FRONTMCP_HOME/duties.sqlitefrontmcp:duty:<info.name>:<duty name>
A top-level redis"machine", "workspace"That Redisfrontmcp:duty:<hostname>:<info.name>:<duty name>
A top-level redis"cluster"That Redisfrontmcp:cluster:duty:<info.name>:<duty name>

A top-level redis here is a Redis server. Vercel KV keeps no lease: with it as the top-level redis, "machine" and "workspace" leases stay in the SQLite file, and a "cluster" duty stops startup as it does without redis. In a key, info.name and the duty's name are percent-encoded, as encodeURIComponent() writes them: a server named Help Desk has Help%20Desk there.

A "workspace" key ends with : and the SHA-256 of the project root. Next to each lease, <key>:ran records the last run: for an interval it expires after one interval, for a cron it holds the time the schedule was last taken and does not expire. With a top-level redis, "machine" means one hostname, so containers and pods, which have hostnames of their own, each run a "machine" duty: use "cluster" to run it once among them.

  • Renewing. The holder extends the lease every third of leaseMs, and again right before each run. A holder that can't renew for two thirds of leaseMs stops holding the duty, aborts the run in flight and contends again.
  • Taking over. A holder that shuts down aborts the run in flight, waits for it, then deletes the lease, so another process takes over at its next check. One that is killed or hangs is taken over once the lease expires: within leaseMs plus a third of it. With leaseMs: 3000, a second process took over about three seconds after the holder was killed.
  • An interval's first run. A process that gets the lease runs at once when no process started a run within the last interval, and otherwise once that interval has passed.
  • The lease store opens at the first lease check. When it can't be opened (a missing @frontmcp/storage-sqlite, an unreachable Redis, an unsafe folder), the server still starts. Each lease check logs Duty "<name>": the lease store failed: <cause> and tries again, and the duty runs once the store opens and this process gets the lease, without a restart. Changed in 1.12.0: before, a duty whose lease store failed to open at startup never ran in that process.

A lease gives one holder at a time, not an exactly-once guarantee for what run() does: a process paused longer than its lease finds the lease gone when it wakes, while the process that took over already runs. Make the work safe to repeat.

Health

New in 1.12.0. Each duty the server started adds a check named duty:<name> to /readyz. It is healthy with details: { holdsLease }, which says whether this process holds the lease now. While the lease store cannot be opened it is unhealthy with error: "the lease store cannot be opened: <cause>", and /readyz answers 503. A run that fails is logged, not reported here.

{"duty:refresh-ticket-index":{"status":"healthy","details":{"holdsLease":true}}}

Errors

An invalid option throws InvalidDecoratorMetadataError (INVALID_DECORATOR_METADATA) when the class is decorated, with a message that starts @Duty invalid metadata for "<field>":.

MistakeField and message
A malformed every"every": every must be milliseconds or a duration such as "30s", "5m", "1h"
Both every and cron"cron": set either every or cron, not both
Neither"every": a duty needs every (an interval) or cron (a cron expression)
An empty cron"cron": cron must be a cron expression such as "0 9 * * 1-5"
An unknown time zone"timezone": timezone must be an IANA time zone such as "Europe/Berlin"
timezone with every"timezone": timezone applies to cron; a duty with every has none
An unknown scope"scope": scope must be 'machine', 'workspace' or 'cluster'
A class without run()"run": <Class> has no run() method

Two mistakes are found when the server starts, in the duty's onBootstrap() phase. The server, or createContainer(), fails with ProviderBootstrapError (PROVIDER_BOOTSTRAP_FAILED) whose originalError is:

ErrorCodeMessage
InvalidDutyCronErrorINVALID_DUTY_CRONDuty "<name>" has a cron expression that can't be read ("<cron>"): <reason>
ClusterScopeNeedsRedisErrorCLUSTER_SCOPE_NEEDS_REDISDuty "<name>" has scope 'cluster', which keeps one lease for every machine in Redis, and none is configured: set a top-level redis (@FrontMcp({ redis }) or createContainer({ redis })), or use scope 'machine'

The cluster check runs only where duties start: not in a serverless deployment, and not in a container without runBackground. Both errors are new in 1.12.0.

A duty's name belongs to one class in its server, whatever the scopes. The second class to start with it fails with DutyNameConflictError (DUTY_NAME_CONFLICT), logged as Provider "<Class>" failed in onReady(): Duty "<name>" of server "<server>" is declared by two classes in this process (A and B): give one of them its own name with @Duty({ name }). The server stays up and the first class runs; createContainer() rejects with the error. Changed in 1.12.1: before, only duties with one lease conflicted, so two of one name, one "workspace" and the other "machine" or "cluster", both ran.

Caveats

  • Duties need a long-lived Node process. A serverless deployment logs Duty "<name>" does not run in a serverless or edge deployment: it needs a long-lived process and does not run it. FrontMCP's browser build, which the Playground uses, starts none either.
  • The SQLite file and its folder are created owner-only. A folder the group or others can write to, or one that belongs to another user, is refused with UnsafeDutyStoreError.
  • Side effects should tolerate an interrupted holder: a process that ignores an aborted signal can continue working after losing its lease.
  • A lazy app cannot have a duty: duties start with the server.
  • A "cluster" cron duty reads the schedule by the clock of the machine that holds it. Keep the machines' clocks in sync.

createContainer() does not run duties unless runBackground: true and info.name are set. runDuties: true, the older name, does the same.

Usage

Refreshing an index periodically

refresh-index.duty.ts
import { Duty, DutyRunContext, Provider } from "@frontmcp/sdk";

@Provider()
@Duty({ name: "refresh-ticket-index", every: "5m", scope: "workspace" })
export class RefreshTicketIndex {
  async run({ signal }: DutyRunContext) {
    if (signal.aborted) return;
    // Refresh the index here, passing signal to cancellable work.
  }
}

Register RefreshTicketIndex in the app's providers. Every server copy registers it; the lease chooses the holder. The holder logs Duty "refresh-ticket-index" runs in this process every 300000 ms, and the others Duty "refresh-ticket-index" already runs elsewhere (lease "<key>"); this one takes it over if that one stops.

Running on a calendar schedule

Give the duty cron in place of every, and the time zone the schedule is meant in:

weekday-report.duty.ts
import { Duty, DutyRunContext, Provider } from "@frontmcp/sdk";

@Provider()
@Duty({ name: "weekday-report", cron: "0 9 * * 1-5", timezone: "Europe/Berlin", scope: "machine" })
export class WeekdayReport {
  async run({ signal }: DutyRunContext) {
    // Build and send the report, passing signal to cancellable work.
  }
}

The holder logs Duty "weekday-report" runs in this process on cron "0 9 * * 1-5" (Europe/Berlin). Nothing runs at startup. After a restart or a takeover, the duty runs once at once if a scheduled time passed since the schedule was last taken, then continues on schedule.

Running one duty among several machines

scope: "machine" gives one holder per machine, so three replicas send three reports. scope: "cluster" keeps one lease for all of them in the server's Redis:

main.ts
@Provider()
@Duty({ name: "weekday-report", cron: "0 9 * * 1-5", timezone: "Europe/Berlin", scope: "cluster" })
class WeekdayReport {
  async run({ signal }: DutyRunContext) { /* … */ }
}

@App({ id: "help-desk", name: "Help Desk", providers: [WeekdayReport] })
class HelpDesk {}

@FrontMcp({
  info: { name: "help-desk", version: "1.0.0" },
  apps: [HelpDesk],
  redis: { url: process.env.REDIS_URL }, // the same Redis on every instance
})
export default class Server {}

Every server with the same info.name on that Redis, and the same Redis database, shares the lease frontmcp:cluster:duty:help-desk:weekday-report. With two processes on a per-three-seconds cron and leaseMs: 3000, one ran each scheduled time; three seconds after it was killed, the other took over, ran once for the time that was missed, and continued on schedule. High availability lists what else instances share.

Publishing an event from a duty

A duty tells the clients subscribed to an event what it found. It takes the server's publisher, which the EVENT_PUBLISHER token provides. A factory provider injects it, which works whether or not the build emits constructor types:

clock.duty.ts
import { AsyncProvider, Duty, EVENT_PUBLISHER, type DutyInterface, type EventPublisher } from "@frontmcp/sdk";
import { clockTick } from "./clock.event";

@Duty({ name: "clock-tick", cron: "* * * * *", scope: "machine" })
class ClockTickDuty implements DutyInterface {
  constructor(private readonly events: EventPublisher) {}

  async run(): Promise<void> {
    await this.events.publish(clockTick, { time: new Date().toISOString() });
  }
}

export const clockTickDuty = AsyncProvider({
  provide: ClockTickDuty,
  name: "clock-tick-duty",
  inject: () => [EVENT_PUBLISHER] as const,
  useFactory: (events) => new ClockTickDuty(events),
});

Register clockTickDuty in providers in place of the class, and the event in an app's events. The duty runs in the one process that holds its lease, so each run publishes once among the copies of the server. On a server without events, publish() is refused with EventsNotEnabledError, and the run is logged as failed. A container from createContainer() has no publisher, so a duty that takes one cannot be built there. @Worker shows the same with a class-typed constructor.

Running duties from a script

createContainer() builds a duty without starting it. To run duties and workers without serving MCP, ask for it:

sweep.ts
import { createContainer } from "@frontmcp/sdk";

const container = await createContainer({
  apps: [HelpDesk],
  runBackground: true, // starts the @Duty and @Worker providers
  info: { name: "help-desk" }, // the server's info.name, so the script shares its leases
  redis: { url: process.env.REDIS_URL }, // the server's redis, when it has one
});
// …
await container.dispose(); // stops the duties and releases their leases

Each duty's own onReady() runs before its first run, as in a server. Without info, the container is refused: runBackground needs info.name: duties and workers share their leases by server name. See createContainer().

Checking what a duty resolves to

@Duty checks its options when the class is decorated, so a mistake fails at import, before any lease is taken. dutyMetadataOf() shows what the decorator resolved: every in milliseconds or the cron and its time zone, and the lease it defaults to. This tool reads it from three duties that aren't registered, so nothing runs:

Open
import { App, Tool, ToolContext, dutyMetadataOf } from "@frontmcp/sdk";
import { FlushAuditLog, RefreshTicketIndex, WeekdayReport } from "./duties";

@Tool({ name: "describe_duties", description: "Show how each duty's options resolve", inputSchema: {} })
class DescribeDuties extends ToolContext {
  async execute() {
    const duties = [new RefreshTicketIndex(), new FlushAuditLog(), new WeekdayReport()];
    return { duties: duties.map((duty) => dutyMetadataOf(duty)) };
  }
}

@App({ id: "help-desk", name: "Help Desk", tools: [DescribeDuties] })
export class HelpDesk {}

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

The lease defaults to three intervals, kept between 3000 and 60000 ms: 60000 for every five minutes, 6000 for every two seconds. A cron duty's is 60000. The last test builds the duty in a container, which reads the expression without starting the duty.

Troubleshooting

@Duty invalid metadata for "every"

Use positive whole milliseconds or a duration such as "30s". Intervals must fit within 2147483647 ms. A duty with neither every nor cron fails with the same field. The class needs a run() method; unknown options and an invalid scope, timezone or leaseMs also fail decoration with InvalidDecoratorMetadataError. See errors.

Duty "…" has a cron expression that can't be read

The server did not start: InvalidDutyCronError names the expression and the reason, such as Invalid value for minute: 61 or it never matches a date. Use five fields, or six with seconds first. A year field and a date are refused.

Duty "…" has scope 'cluster', which keeps one lease for every machine in Redis, and none is configured

ClusterScopeNeedsRedisError stopped startup. Add a top-level redis to @FrontMcp(), or to createContainer() in a script, or use scope: "machine".

Duty "…": the lease store failed: …

The duty could not read or write its lease, and tries again at its next check. With Invalid sqlite configuration: the sqlite type needs @frontmcp/storage-sqlite. Install it with: npm install @frontmcp/storage-sqlite, install that package or set a top-level redis. Meanwhile /readyz answers 503 with duty:<name> unhealthy and the lease store cannot be opened: <cause>. The duty starts without a restart once the store opens.

Duty "…" of server "…" is declared by two classes in this process

Give one class its own name. Two classes can't give a duty of one server the same name, whatever their scopes.

Duty "…" already runs elsewhere with one server

Another server on the machine has the same info.name and a duty with the same name, so they share a lease. Give the server a distinctive info.name, or the duty its own name.

Refusing to keep duty leases under …

UnsafeDutyStoreError refuses unsafe ownership or permissions. Set FRONTMCP_HOME to a folder only the server's user can write.

A cron duty did not run at startup

It waits for its next scheduled time. Start the work another way when it must also run at startup.

A cron duty runs at the wrong hour

The expression is read in UTC unless timezone names the zone the schedule is meant in.

A takeover is slow after a crash

The lease has to expire first: leaseMs plus a third of it at most. A cron duty's default is 60000 ms. Lower leaseMs, to 1000 at least.

Report a docs issue · Report a security concern privately