@Worker
Some work never ends by itself: a mail connection that stays open, a folder to watch, an upstream socket, a queue to consume. A loop started in a provider's onReady() has nothing to run it again when it throws, nothing to stop it at shutdown, and runs in every copy of the server. @Worker supervises it: the server starts run() once it serves, runs it again after a wait when it returns or throws, and aborts its signal at shutdown. With a scope other than "process", one process holds the worker's lease and runs it, and another takes it over when the holder stops. New in 1.12.0. Use a duty for work that runs, ends, and runs again on a schedule.
@Worker({ name?, scope, restart?, leaseMs? })
class InboxWatcher {
async run({ signal }: WorkerRunContext) { /* stay connected until signal aborts */ }
}
Reference
@Worker(options)
Decorate a class with a run(context) method and register it in providers, of an @App, of @FrontMcp or of a plugin. @Worker marks the class as a GLOBAL provider: its constructor gets its dependencies injected, and it can implement onBootstrap(), onReady() and onShutdown().
| Option | Type | Default | Description |
|---|---|---|---|
name | string | class name | The worker's name in logs, in its /readyz check and in its lease. Set it explicitly when a build renames classes. |
scope | "process" | "machine" | "workspace" | "cluster" | required | Whether every process runs the worker, or one under a lease. See scopes. |
restart | false | { minDelayMs?, maxDelayMs?, factor? } | { minDelayMs: 1000, maxDelayMs: 60000, factor: 2 } | The waits before run() runs again. false runs it once. |
leaseMs | number | 15000 | Lease lifetime, which is how soon another process takes over from a holder that died; renewed every third of it. Minimum 1000 ms. Not with scope: "process". |
run({ signal }) returns void or a promise that stays pending for as long as the worker works. signal aborts at shutdown, and when this process loses the worker's lease: pass it to what run() awaits, or listen to its abort event, and return.
workerMetadataOf(instance) returns its class's ResolvedWorkerMetadata (name, scope, restart, leaseMs), or undefined when it has none. workerMetadataSchema validates the decorator options. The types WorkerInterface (a class with run()), WorkerRunContext, WorkerMetadata, WorkerRestartOptions and WorkerScope are exported from @frontmcp/sdk too.
Scopes
| Scope | Runs in | Lease |
|---|---|---|
"process" | Every server process, each its own instance | None |
"machine" | One process of the machine, among servers with the same info.name | The SQLite file, or Redis per hostname |
"workspace" | One process per project root: the nearest folder at or above the working directory with a package.json | The same |
"cluster" | One process among the machines that share the server's top-level redis | Redis, which it requires |
A leased worker uses the store and the mechanism of duties: see scopes and leases. Its keys have a prefix of their own, so a worker and a duty with one name do not share a lease:
| Server | Scope | Store | Key |
|---|---|---|---|
No top-level redis | "machine", "workspace" | The SQLite file ~/.frontmcp/duties.sqlite, or $FRONTMCP_HOME/duties.sqlite. It needs @frontmcp/storage-sqlite. | frontmcp:worker:<info.name>:<worker name> |
A top-level redis | "machine", "workspace" | That Redis | frontmcp:worker:<hostname>:<info.name>:<worker name> |
A top-level redis | "cluster" | That Redis | frontmcp:cluster:worker:<info.name>:<worker name> |
As for duties, a top-level redis that is Vercel KV keeps no lease, and the names in a key are percent-encoded. scope: "process" needs neither store.
Lifecycle
- Start.
run()starts once the server serves, after the worker's ownonReady(). A leased worker starts when this process gets the lease. The server logsWorker "<name>" runs in this process. - Restart. When
run()returns or throws whilesignalis not aborted, the server runs it again after a wait:minDelayMsthe first time, thenfactortimes longer each time, up tomaxDelayMs. With the defaults: 1, 2, 4 … 60 seconds. A run that lasted longer thanmaxDelayMsstarts the waits over atminDelayMs. - Errors. What
run()throws is logged with the worker's name and never reaches the server: a failing worker does not crash it, and does not stop other workers. restart: false.run()runs once. When it ends, the worker stays stopped. A leased one keeps its lease, so no other process runs it while this one is up; a process that takes the lease over later runs it once.- Abort.
signalaborts at shutdown, and when this process loses the lease. An error thrown after that is not logged as a failure. A process that cannot renew the lease abortssignala third ofleaseMsbefore the store could give the lease to another process, sorun()has that long to return. - Shutdown. The server aborts
signaland waits forrun()to end, up tolifecycle.shutdownHookTimeoutMs(3000 ms by default), then moves on. A leased worker keeps renewing its lease whilerun()ends, then releases it, so another process takes over at its next check. The worker's ownonShutdown()runs oncerun()has ended. - One at a time. A process that gets the lease back while its last run is still ending waits for it before it starts the next.
Health
Each worker the server started adds a check named worker:<name> to /readyz:
details.state | Meaning | Status |
|---|---|---|
running | run() is running | healthy |
standby | Another process holds the lease, or this one has not got it yet | healthy |
restarting | run() ended and the server waits to run it again | degraded |
stopped | run() ended and restart: false keeps it so | unhealthy after an error, healthy after a return |
details also holds restarts, how many times run() was started again, and lastError, the message of the last error it threw, until a run returns. error repeats lastError when the status is not healthy. While a leased worker's lease store cannot be opened, the check is unhealthy with error: "the lease store cannot be opened: <cause>"; each lease check tries again, and the worker runs once the store opens and this process gets the lease. Only unhealthy makes /readyz answer 503.
{"worker:inbox-watcher":{"status":"degraded","details":{"state":"restarting","restarts":3,"lastError":"connection lost"},"error":"connection lost"}}
Where a worker runs
A worker runs for as long as its server process does.
| How the server runs | The worker |
|---|---|
A long-lived Node process: node dist/main.js, a container | Runs until the process stops. Something else restarts the process: a container's restart policy, a service manager. |
The shared local server, FrontMcpInstance.runShared() | Runs while a session is attached, and idleTimeoutMs (600000 ms) after the last one left. See below. |
| A stdio server an MCP client starts | Runs only while its client is connected. |
| A serverless or edge deployment, a browser | Not started. The server logs Worker "<name>" does not run in a serverless or edge deployment: it needs a long-lived process. |
createContainer() | Not started unless runBackground: true. |
A lazy app cannot have a worker: the app is refused with it has workers ("<name>"), which start with the server.
Errors
An invalid option throws InvalidDecoratorMetadataError (INVALID_DECORATOR_METADATA) when the class is decorated, with a message that starts @Worker invalid metadata for "<field>":.
| Mistake | Field and message |
|---|---|
An unknown or missing scope | "scope": scope must be 'process', 'machine', 'workspace' or 'cluster' |
restart: true, or another value that is not false or an object | "restart": restart must be false or { minDelayMs, maxDelayMs, factor } |
| A wait below 1 ms | "restart.minDelayMs": restart.minDelayMs must be at least 1 |
minDelayMs above maxDelayMs | "restart.minDelayMs": restart.minDelayMs must not be greater than restart.maxDelayMs |
A factor below 1 | "restart.factor": restart.factor must be at least 1 |
leaseMs below 1000 | "leaseMs": leaseMs must be at least 1000 (stores keep a TTL in whole seconds) |
leaseMs with scope: "process" | "leaseMs": leaseMs applies to a leased scope; a 'process' worker has no lease |
A class without run() | "run": <Class> has no run() method |
Found when the server starts:
| Error | Code | When |
|---|---|---|
ClusterScopeNeedsRedisError | CLUSTER_SCOPE_NEEDS_REDIS | A "cluster" worker and no top-level redis. The server, or a container that runs workers, fails with ProviderBootstrapError, whose originalError it is. |
WorkerNameConflictError | WORKER_NAME_CONFLICT | Two classes give a worker of one server the same name, whatever their scopes, "process" included. Logged as Provider "<Class>" failed in onReady(): Worker "<name>" of server "<server>" is declared by two classes in this process (A and B): give one of them its own name with @Worker({ name }). The server stays up, and the second class does not run. createContainer() rejects with it. |
Caveats
- A worker runs on the server's event loop, not in a worker thread. For CPU-heavy work that should leave the event loop free, see
this.offload. run()must return promptly oncesignalaborts. A run that ignores it holds shutdown up forlifecycle.shutdownHookTimeoutMs, and after a lost lease it still runs when the next holder starts.- A lease gives one holder at a time, not exactly-once work. A process paused longer than its lease finds the lease gone when it wakes and aborts
signal, while the process that took over already runs. Make what the worker does safe to resume from another process. - A worker's name belongs to one class in its server, whatever the scopes: a second class with it fails with
WorkerNameConflictError. Changed in 1.12.1: before, only leased workers conflicted, so two"process"workers of one name both ran, and/readyzshowed oneworker:<name>entry for the two. - Don't write a retry loop inside
run(). Let it throw or return: the server already waits, grows the wait and reports the state to/readyz. - No worker starts in the Playground, which runs FrontMCP's browser build. The behavior on this page was seen with FrontMCP's Node server, one to three processes sharing a lease in the SQLite file and in Redis.
Usage
Keeping a connection open
run() connects, handles what arrives, and closes the connection when signal aborts:
import { Worker, type WorkerRunContext } from "@frontmcp/sdk";
import { connectToMailbox } from "./mailbox";
@Worker({ name: "inbox-watcher", scope: "machine" })
export class InboxWatcher {
async run({ signal }: WorkerRunContext) {
const connection = await connectToMailbox({ signal });
try {
for await (const message of connection.messages({ signal })) {
await connection.store(message);
}
} finally {
await connection.close();
}
}
}@App({ id: "mail", name: "Mail", providers: [InboxWatcher] })
export class MailApp {}Started twice on one machine, the first process logs Worker "inbox-watcher" runs in this process, and its /readyz shows "state": "running". The second logs Worker "inbox-watcher" already runs elsewhere (lease "<key>"); this one takes it over if that one stops, and shows "state": "standby". When the first is stopped with SIGTERM, its run() sees the abort and returns, its onShutdown() runs, and the second takes the worker over at its next lease check. When the first is killed, the second takes over once the lease expires: with leaseMs: 3000, within four seconds.
Restarting after a failure
When the connection drops, let run() throw. The server logs the cause and the wait, and runs it again:
Worker "inbox-watcher" runs in this process
Worker "inbox-watcher" failed: connection lost; it runs again in 1000 ms
Worker "inbox-watcher" failed: connection lost; it runs again in 2000 ms
Worker "inbox-watcher" failed: connection lost; it runs again in 4000 ms
Between two runs /readyz shows the worker degraded, with "state": "restarting", the count of restarts and the lastError, and still answers 200. A run() that returns before its signal aborted is run again the same way, logged as a warning: Worker "inbox-watcher" returned before its signal was aborted; it runs again in 1000 ms.
Set the waits with restart, or turn restarts off:
@Worker({ name: "inbox-watcher", scope: "machine", restart: { minDelayMs: 300, maxDelayMs: 1000, factor: 3 } }) // waits 300, 900, 1000, 1000 ms
@Worker({ name: "import-archive", scope: "machine", restart: false }) // runs once
With restart: false, a run that throws logs Worker "import-archive" failed: <cause>; it does not run again (restart: false), and the check turns unhealthy, so /readyz answers 503 until the server restarts. A run that returns leaves it healthy with "state": "stopped".
Running one worker among several machines
scope: "cluster" keeps one lease for every machine in the server's top-level redis:
@Worker({ name: "inbox-watcher", scope: "cluster" })
class InboxWatcher {
async run({ signal }: WorkerRunContext) { /* … */ }
}
@FrontMcp({
info: { name: "mail", version: "1.0.0" },
apps: [MailApp],
redis: { url: process.env.REDIS_URL }, // the same Redis on every instance
})
export default class Server {}One instance shows "state": "running" in /readyz and the others "state": "standby". When the holder's process ends, another takes the worker over. Without redis, the server does not start: Worker "inbox-watcher" has scope 'cluster', which keeps one lease for every machine in Redis, and none is configured. Use scope: "process" for work every instance needs for itself, like refreshing a cache in its own memory.
Publishing events from a worker
A worker that watches something tells the clients subscribed to an event about it. It takes the server's publisher in its constructor, by the EventPublisher class, and publishes from run():
import { EventPublisher, Worker, type WorkerRunContext } from "@frontmcp/sdk";
import { mailReceived } from "./mail-received.event";
import { Mailbox } from "./mailbox";
@Worker({ name: "inbox-watcher", scope: "cluster" })
export class InboxWatcher {
constructor(
private readonly mailbox: Mailbox,
private readonly events: EventPublisher,
) {}
async run({ signal }: WorkerRunContext) {
for await (const message of this.mailbox.messages({ signal })) {
await this.events.publish(mailReceived, { messageId: message.id, from: message.from });
}
}
}Import EventPublisher as a value, not with import type: FrontMCP injects by the class. Where the build emits no constructor types (tsx, esbuild), build the worker with a factory provider that injects the EVENT_PUBLISHER token, and register the factory in providers in place of the class. A worker built by a factory is supervised like one registered by its class:
import { AsyncProvider, EVENT_PUBLISHER } from "@frontmcp/sdk";
export const inboxWatcher = AsyncProvider({
provide: InboxWatcher,
name: "inbox-watcher",
inject: () => [Mailbox, EVENT_PUBLISHER] as const,
useFactory: (mailbox, events) => new InboxWatcher(mailbox, events),
});@App({ id: "mail", name: "Mail", events: [mailReceived], providers: [Mailbox, inboxWatcher] })
export class MailApp {}- The event must be in the
eventsof an app. On a server without events,publish()is refused withEventsNotEnabledError; the run then fails and is run again after its wait, like any error. - With a leased
scope, one process publishes. Withscope: "process", every copy of the server publishes its own occurrence of the same thing. - A published event also starts the workflows with
trigger: "event"that listen to its name. - A container from
createContainer()has no publisher, so a worker that takes one cannot be built there.
Watching files
watchFiles() from @frontmcp/utils yields what happens to the files of a folder, as an async iterator a worker loops over until its signal aborts:
import { EventPublisher, Worker, type WorkerRunContext } from "@frontmcp/sdk";
import { watchFiles } from "@frontmcp/utils";
import { fileDropped } from "./file-dropped.event";
@Worker({ name: "drop-folder", scope: "machine" })
export class DropFolderWatcher {
constructor(private readonly events: EventPublisher) {}
async run({ signal }: WorkerRunContext) {
for await (const { type, path } of watchFiles("./drop", { events: ["add", "change"], signal })) {
await this.events.publish(fileDropped, { path, change: type });
}
}
}watchFiles(paths, options?) takes one path or several, files or directories, relative to the working directory or absolute. @frontmcp/utils is installed with @frontmcp/sdk; add it to your own dependencies, at the same version, to import it.
| Option | Type | Default | Description |
|---|---|---|---|
events | ("add" | "change" | "unlink")[] | all three | The kinds of event to yield. |
debounceMs | number | 100 | How long the directory of a path must stay quiet before its changes are yielded. |
signal | AbortSignal | none | Ends the iteration and closes the watchers when it aborts. Pass the worker's. |
- Each event is
{ type, path }, withpathabsolute.add: a file appeared.change: it was written to or replaced.unlink: it is gone. - A directory is watched for its direct files. Its subdirectories, and what they hold, are left out.
- A path that does not exist yet is watched from the moment it appears, as a file or as a directory.
- The files that are there when the watch starts are not yielded. A worker that must handle those lists the folder first.
- Several writes to one file within
debounceMsare onechange, and a file created and removed within it yields nothing. - The iteration ends when
signalaborts or the loop is left withbreakorreturn. - It needs Node.js.
Keeping a worker alive under the shared local server
The shared local server exits when it is idle. Idle means no request and no attached session: a running worker does not count as activity. Changed in 1.12.0: before, the server exited idleTimeoutMs after its last request, also under attached sessions; it now stays up while a session is attached, and exits idleTimeoutMs after the last one left, 10 minutes by default. So a worker there stops, with its server, ten minutes after the last client went away, and starts again when a session's next request starts a new server.
For a worker that must keep running without a client, turn the idle exit off:
import { FrontMcpInstance } from "@frontmcp/sdk";
import { config } from "./config";
await FrontMcpInstance.runShared(config, { key: "mail", idleTimeoutMs: false });Or run the server as a long-lived process of its own, under something that restarts it. Do not rely on a stdio server that a client starts: the worker stops when the client disconnects.
Running workers from a script
createContainer() builds a worker without starting it. To run workers and duties without serving MCP, ask for it:
import { createContainer } from "@frontmcp/sdk";
const container = await createContainer({
apps: [MailApp],
runBackground: true, // starts the @Worker and @Duty providers
info: { name: "mail" }, // 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: scope "cluster" needs it
});
// …
await container.dispose(); // aborts the workers, waits for them, and releases their leasesA container has no /readyz, so its workers add no check.
Checking what a worker resolves to
@Worker checks its options when the class is decorated, so a mistake fails at import, before anything runs. workerMetadataOf() shows what the decorator resolved. This tool reads it from three workers that aren't registered, so none starts:
import { App, Tool, ToolContext, workerMetadataOf } from "@frontmcp/sdk";
import { CacheWarmer, ImportArchive, InboxWatcher } from "./workers";
@Tool({ name: "describe_workers", description: "Show how each worker's options resolve", inputSchema: {} })
class DescribeWorkers extends ToolContext {
async execute() {
const workers = [new InboxWatcher(), new CacheWarmer(), new ImportArchive()];
return { workers: workers.map((worker) => workerMetadataOf(worker)) };
}
}
@App({ id: "mail", name: "Mail", tools: [DescribeWorkers] })
export class MailApp {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Testing run() without a server
A worker is a class: a test can build it and call run() with a signal of its own. That checks the two things the server relies on, without waiting for a real connection: run() returns when its signal aborts, and it leaves by throwing when its work fails.
import { test, expect } from "@frontmcp/testing";
import { InboxWatcher } from "./inbox.worker";
import { Mailbox } from "./mailbox";
test("run() handles messages until its signal aborts, then returns", async () => {
const mailbox = new Mailbox();
const controller = new AbortController();
const running = new InboxWatcher(mailbox).run({ signal: controller.signal });
mailbox.deliver("m1");
mailbox.deliver("m2");
await new Promise((resolve) => setTimeout(resolve, 10));
expect(mailbox.stored).toEqual(["m1", "m2"]);
expect(mailbox.open).toBe(true);
controller.abort();
await running;
expect(mailbox.open).toBe(false);
});
test("a lost connection leaves run() by throwing, which is what makes the server run it again", async () => {
const mailbox = new Mailbox();
const running = new InboxWatcher(mailbox).run({ signal: new AbortController().signal });
mailbox.fail(new Error("connection lost"));
await expect(running).rejects.toThrow("connection lost");
expect(mailbox.open).toBe(false);
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Troubleshooting
The worker never starts
It is not in a providers array, the server runs serverless or on the edge, or a createContainer() was built without runBackground: true. A leased worker whose /readyz check says standby runs in another process.
Worker "…" failed: …; it runs again in … ms, over and over
run() throws on every start. Read the cause in the log line, or in lastError in /readyz. A run() that returns right away loops the same way, with returned before its signal was aborted: keep it pending until signal aborts. Raise restart.minDelayMs to slow the attempts down.
The worker stops a few minutes after the last client left
It runs under the shared local server, which exited idle. Pass idleTimeoutMs: false to runShared(), or run a long-lived server: see keeping a worker alive.
Worker "…" 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".
Worker "…" of server "…" is declared by two classes in this process
Two classes give a worker of the server the same name, and the second one did not start, whatever their scopes. Give one of them its own name.
Worker "…" already runs elsewhere with one server
Another server on the machine has the same info.name and a worker with the same name. Give the server a distinctive info.name, or the worker its own name.
Provider "…" onShutdown() did not finish within 3000 ms
run() did not end when signal aborted, so shutdown waited for lifecycle.shutdownHookTimeoutMs and moved on, and the worker's own onShutdown() did not run before the process exited. Pass signal to what run() awaits, or return on its abort event.
Provider InboxWatcher depends on Object, which is not registered (local or parent).
The worker's constructor names EventPublisher, and it was imported with import type, so the build recorded Object in its place. Import it as a value, or build the worker with a factory that injects EVENT_PUBLISHER: see publishing events.
/readyz answers 503 because of a worker
A restart: false worker ended on an error: fix the cause and restart the server, or let it restart. Or its lease store cannot be opened (the lease store cannot be opened: <cause>): with Invalid sqlite configuration: the sqlite type needs @frontmcp/storage-sqlite, install that package or set a top-level redis. The worker starts at the next lease check once the store opens. In production the answer leaves the checks out unless health.includeDetails is true.
Two processes run the worker for a moment
The old holder was paused past its lease, or its run() ignores signal. Return on signal, keep the event loop free, or raise leaseMs.