# @Worker

> Keep a long-running background process supervised. The server starts its run() once it serves, runs it again with a growing wait when it ends, stops it at shutdown, and runs it in every process or in one under a lease.

Source: https://frontmcp.dev/reference/sdk/worker

[Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026

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](https://frontmcp.dev/reference/sdk/duty) for work that runs, ends, and runs again on a schedule.

```ts
@Worker({ name?, scope, restart?, leaseMs? })
class InboxWatcher {
  async run({ signal }: WorkerRunContext) { /* stay connected until signal aborts */ }
}
```



---

<a id="reference"></a>

## Reference

<a id="workeroptions"></a>

### `@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](https://frontmcp.dev/reference/sdk/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](https://frontmcp.dev/reference/sdk/worker#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.

<a id="scopes"></a>

#### 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](https://frontmcp.dev/reference/sdk/duty#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.

<a id="lifecycle"></a>

#### Lifecycle

- **Start.** `run()` starts once the server serves, after the worker's own `onReady()`. A leased worker starts when this process gets the lease. The server logs `Worker "<name>" runs in this process`.
- **Restart.** When `run()` returns or throws while `signal` is not aborted, the server runs it again after a wait: `minDelayMs` the first time, then `factor` times longer each time, up to `maxDelayMs`. With the defaults: 1, 2, 4 … 60 seconds. A run that lasted longer than `maxDelayMs` starts the waits over at `minDelayMs`.
- **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.** `signal` aborts 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 aborts `signal` a third of `leaseMs` before the store could give the lease to another process, so `run()` has that long to return.
- **Shutdown.** The server aborts `signal` and waits for `run()` to end, up to `lifecycle.shutdownHookTimeoutMs` (3000 ms by default), then moves on. A leased worker keeps renewing its lease while `run()` ends, then releases it, so another process takes over at its next check. The worker's own `onShutdown()` runs once `run()` 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.

<a id="health"></a>

#### Health

Each worker the server started adds a check named `worker:<name>` to [`/readyz`](https://frontmcp.dev/reference/deployment/health-and-metrics#background-work-and-events):

| `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`.

```json
{"worker:inbox-watcher":{"status":"degraded","details":{"state":"restarting","restarts":3,"lastError":"connection lost"},"error":"connection lost"}}
```

<a id="where-a-worker-runs"></a>

#### 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](https://frontmcp.dev/reference/sdk/frontmcp-instance#frontmcpinstancerunsharedconfigorclass-options), `FrontMcpInstance.runShared()` | Runs while a session is attached, and `idleTimeoutMs` (600000 ms) after the last one left. See [below](https://frontmcp.dev/reference/sdk/worker#keeping-a-worker-alive-under-the-shared-local-server). |
| 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()`](https://frontmcp.dev/reference/sdk/provider#createcontaineroptions) | Not started unless `runBackground: true`. |

A [lazy app](https://frontmcp.dev/reference/sdk/app#lazy-apps) cannot have a worker: the app is refused with `it has workers ("<name>"), which start with the server`.

<a id="errors"></a>

#### 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. |

<a id="caveats"></a>

#### 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`](https://frontmcp.dev/reference/sdk/offload).
- **`run()` must return promptly once `signal` aborts.** A run that ignores it holds shutdown up for `lifecycle.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 `/readyz` showed one `worker:<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.

---

<a id="usage"></a>

## Usage

<a id="keeping-a-connection-open"></a>

### Keeping a connection open

`run()` connects, handles what arrives, and closes the connection when `signal` aborts:

```ts inbox.worker.ts
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();
    }
  }
}
```

```ts mail.app.ts
@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.

<a id="restarting-after-a-failure"></a>

### Restarting after a failure

When the connection drops, let `run()` throw. The server logs the cause and the wait, and runs it again:

```text
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:

```ts
@Worker({ name: "inbox-watcher", scope: "machine", restart: { minDelayMs: 300, maxDelayMs: 1000, factor: 3 } }) // waits 300, 900, 1000, 1000 ms
```

```ts
@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"`.

<a id="running-one-worker-among-several-machines"></a>

### Running one worker among several machines

`scope: "cluster"` keeps one lease for every machine in the server's top-level `redis`:

```ts main.ts
@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.

<a id="publishing-events-from-a-worker"></a>

### Publishing events from a worker

A worker that watches something tells the clients subscribed to an [event](https://frontmcp.dev/reference/sdk/event) about it. It takes the server's publisher in its constructor, by the `EventPublisher` class, and publishes from `run()`:

```ts inbox.worker.ts
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:

```ts inbox.worker.ts
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),
});
```

```ts mail.app.ts
@App({ id: "mail", name: "Mail", events: [mailReceived], providers: [Mailbox, inboxWatcher] })
export class MailApp {}
```

- The event must be in the `events` of an app. On a server without events, `publish()` is refused with `EventsNotEnabledError`; the run then fails and is run again after its wait, like any error.
- With a leased `scope`, one process publishes. With `scope: "process"`, every copy of the server publishes its own occurrence of the same thing.
- A published event also starts the workflows with [`trigger: "event"`](https://frontmcp.dev/reference/sdk/workflow#starting-from-a-published-event) that listen to its name.
- A container from `createContainer()` has no publisher, so a worker that takes one cannot be built there.

<a id="watching-files"></a>

### 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:

```ts drop-folder.worker.ts
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 }`, with `path` absolute. `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 `debounceMs` are one `change`, and a file created and removed within it yields nothing.
- The iteration ends when `signal` aborts or the loop is left with `break` or `return`.
- It needs Node.js.

<a id="keeping-a-worker-alive-under-the-shared-local-server"></a>

### Keeping a worker alive under the shared local server

The [shared local server](https://frontmcp.dev/reference/sdk/frontmcp-instance#frontmcpinstancerunsharedconfigorclass-options) 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:

```ts shared.ts
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.

<a id="running-workers-from-a-script"></a>

### Running workers from a script

[`createContainer()`](https://frontmcp.dev/reference/sdk/provider#createcontaineroptions) builds a worker without starting it. To run workers and duties without serving MCP, ask for it:

```ts consume.ts
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 leases
```

A container has no `/readyz`, so its workers add no check.

<a id="checking-what-a-worker-resolves-to"></a>

### 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:

Initial call configuration:

```js
{ tool: "describe_workers", arguments: {} }
```

```ts workers.ts
import { Worker, type WorkerRunContext } from "@frontmcp/sdk";

const untilAborted = (signal: AbortSignal) => new Promise((resolve) => signal.addEventListener("abort", resolve, { once: true }));

@Worker({ name: "inbox-watcher", scope: "cluster" })
export class InboxWatcher {
  async run({ signal }: WorkerRunContext) {
    await untilAborted(signal);
  }
}

@Worker({ name: "cache-warmer", scope: "process", restart: { minDelayMs: 500, maxDelayMs: 10_000 } })
export class CacheWarmer {
  async run({ signal }: WorkerRunContext) {
    await untilAborted(signal);
  }
}

@Worker({ name: "import-archive", scope: "machine", restart: false, leaseMs: 5000 })
export class ImportArchive {
  async run() {}
}
```

```ts main.ts active
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 {}
```

```ts workers.test.ts
import { test, expect } from "@frontmcp/testing";
import { InvalidDecoratorMetadataError, Worker } from "@frontmcp/sdk";

const decorate = (options: Record<string, unknown>) => () => Worker(options as never)(class Inbox { async run() {} });

test("the defaults: restarts from 1 s to 60 s, and a 15 s lease", async ({ mcp }) => {
  const { workers } = (await mcp.tools.call("describe_workers", {})).json();
  expect(workers).toEqual([
    { name: "inbox-watcher", scope: "cluster", leaseMs: 15000, restart: { minDelayMs: 1000, maxDelayMs: 60000, factor: 2 } },
    { name: "cache-warmer", scope: "process", leaseMs: 15000, restart: { minDelayMs: 500, maxDelayMs: 10000, factor: 2 } },
    { name: "import-archive", scope: "machine", leaseMs: 5000, restart: false },
  ]);
});

test("a worker needs a scope and a run() method", () => {
  expect(decorate({})).toThrow(InvalidDecoratorMetadataError);
  expect(decorate({})).toThrow(`@Worker invalid metadata for "scope": scope must be 'process', 'machine', 'workspace' or 'cluster'`);
  expect(() => Worker({ scope: "process" })(class Inbox {} as never)).toThrow('@Worker invalid metadata for "run": Inbox has no run() method');
});

test("restart is false or the waits, and the waits must make sense", () => {
  expect(decorate({ scope: "process", restart: true })).toThrow('@Worker invalid metadata for "restart": restart must be false or { minDelayMs, maxDelayMs, factor }');
  expect(decorate({ scope: "process", restart: { minDelayMs: 0 } })).toThrow("restart.minDelayMs must be at least 1");
  expect(decorate({ scope: "process", restart: { minDelayMs: 5000, maxDelayMs: 1000 } })).toThrow("restart.minDelayMs must not be greater than restart.maxDelayMs");
  expect(decorate({ scope: "process", restart: { factor: 0.5 } })).toThrow("restart.factor must be at least 1");
});

test("a lease is at least a second, and a process worker has none", () => {
  expect(decorate({ scope: "machine", leaseMs: 500 })).toThrow("leaseMs must be at least 1000 (stores keep a TTL in whole seconds)");
  expect(decorate({ scope: "process", leaseMs: 5000 })).toThrow("leaseMs applies to a leased scope; a 'process' worker has no lease");
});
```

<a id="testing-run-without-a-server"></a>

### 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.

**Hidden fixture/test file (runs with the example):**

```ts main.ts hidden
import { App } from "@frontmcp/sdk";
@App({ name: "Mail" })
export class MailApp {}
```

```ts inbox.worker.ts
import { Worker, type WorkerRunContext } from "@frontmcp/sdk";
import { Mailbox } from "./mailbox";

@Worker({ name: "inbox-watcher", scope: "machine" })
export class InboxWatcher {
  constructor(private readonly mailbox: Mailbox) {}

  async run({ signal }: WorkerRunContext) {
    for await (const message of this.mailbox.messages(signal)) {
      this.mailbox.stored.push(message);
    }
  }
}
```

```ts mailbox.ts
/** A stand-in for a mail connection: messages arrive with deliver(), and the connection drops with fail(). */
export class Mailbox {
  readonly stored: string[] = [];
  open = false;
  private arrived: string[] = [];
  private failure?: Error;
  private wake: () => void = () => {};

  deliver(message: string) {
    this.arrived.push(message);
    this.wake();
  }

  fail(error: Error) {
    this.failure = error;
    this.wake();
  }

  async *messages(signal: AbortSignal): AsyncGenerator<string> {
    this.open = true;
    signal.addEventListener("abort", () => this.wake(), { once: true });
    try {
      while (!signal.aborted) {
        if (this.failure) throw this.failure;
        const message = this.arrived.shift();
        if (message === undefined) await new Promise<void>((resolve) => (this.wake = resolve));
        else yield message;
      }
    } finally {
      this.open = false;
    }
  }
}
```

```ts inbox.test.ts active
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);
});
```

---

<a id="troubleshooting"></a>

## Troubleshooting

<a id="the-worker-never-starts"></a>

### 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.

<a id="worker--failed--it-runs-again-in--ms-over-and-over"></a>

### `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.

<a id="the-worker-stops-a-few-minutes-after-the-last-client-left"></a>

### 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](https://frontmcp.dev/reference/sdk/worker#keeping-a-worker-alive-under-the-shared-local-server).

<a id="worker--has-scope-cluster-which-keeps-one-lease-for-every-machine-in-redis-and-none-is-configured"></a>

### `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"`.

<a id="worker--of-server--is-declared-by-two-classes-in-this-process"></a>

### `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`.

<a id="worker--already-runs-elsewhere-with-one-server"></a>

### `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`.

<a id="provider--onshutdown-did-not-finish-within-3000-ms"></a>

### `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.

<a id="provider-inboxwatcher-depends-on-object-which-is-not-registered-local-or-parent"></a>

### `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](https://frontmcp.dev/reference/sdk/worker#publishing-events-from-a-worker).

<a id="readyz-answers-503-because-of-a-worker"></a>

### `/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`.

<a id="two-processes-run-the-worker-for-a-moment"></a>

### 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`.
