# Events options

> The events option of @FrontMcp: which delivery modes a server performs, subscription lifetimes and limits, webhook delivery and retries, the subscription store, the HTTP publish endpoint, and the dialect callers are answered in.

Source: https://frontmcp.dev/reference/sdk/events-options

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

A server serves [events](https://frontmcp.dev/reference/sdk/event) as soon as one of its apps declares one, with no option set. `@FrontMcp({ events })` changes the defaults: which [delivery modes](https://frontmcp.dev/reference/sdk/event-delivery#delivery-modes) the server performs, how long a subscription lasts, how webhook deliveries are retried, where subscriptions are kept, whether other services may publish over HTTP, and which dialect callers are answered in. New in 1.12.0.

```ts
@FrontMcp({
  events: {
    enabled?, compat?, bridge?,
    poll?, push?, buffer?,             // reading by request and by stream
    webhook?, subscriptions?, store?,  // webhook subscriptions and where they're kept
    publishEndpoint?,                  // POST /events/publish
  },
})
```



---

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

## Reference

<a id="events"></a>

### `events`

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `enabled` | `boolean` | not set | Events are on once an app declares one. `false` turns them off: nothing is served, and `publish()` throws `EventsNotEnabledError`. `true` starts events on a server that declares none. |
| `compat` | `"auto" \| "sep-3415" \| "sketch"` | `"auto"` | The [dialect](https://frontmcp.dev/reference/sdk/event-delivery#dialects) callers are answered in. `"auto"` picks per caller: the sketch for a caller recognized as OpenAI, SEP-3415 for everyone else. |
| `bridge` | `boolean` | `true` | Also emits each published occurrence on the server's event bus, under the event's name, where a [workflow](https://frontmcp.dev/reference/sdk/workflow#workflow-triggers) with `trigger: "event"` listens. |
| `poll` | object | on | [`events/poll`](https://frontmcp.dev/reference/sdk/events-options#eventspoll-eventspush-and-eventsbuffer). |
| `push` | object | on | [`events/stream`](https://frontmcp.dev/reference/sdk/events-options#eventspoll-eventspush-and-eventsbuffer). |
| `buffer` | object | 10 minutes, 10000 per event | [What a poll or a stream can still read](https://frontmcp.dev/reference/sdk/events-options#eventspoll-eventspush-and-eventsbuffer) of published occurrences. |
| `webhook` | object | on, where callers sign in | [Webhook subscriptions and their deliveries](https://frontmcp.dev/reference/sdk/events-options#eventswebhook-and-eventswebhookdelivery). |
| `subscriptions` | object | 1 hour, 100 per caller | [Lifetimes and limits](https://frontmcp.dev/reference/sdk/events-options#eventssubscriptions). |
| `store` | object | memory | [Where subscriptions and pending deliveries are kept](https://frontmcp.dev/reference/sdk/events-options#eventsstore). |
| `publishEndpoint` | object | off | [Publishing over HTTP](https://frontmcp.dev/reference/sdk/events-options#eventspublishendpoint). |

<a id="which-delivery-modes-a-server-performs"></a>

### Which delivery modes a server performs

An event is offered in the modes its server performs, within the event's own `delivery`:

| Mode | Performed when |
| --- | --- |
| `poll` | Always, unless `events.poll.enabled` is `false`. On every runtime and in every auth mode. |
| `push` | Unless `events.push.enabled` is `false`, and except in a serverless deployment, where no process lives long enough to hold a stream. |
| `webhook` | When the server's [auth mode](https://frontmcp.dev/reference/auth/modes) signs callers in (any `auth.mode` other than `public`), unless `events.webhook.enabled` is `false`. |

A subscription belongs to a caller, which a server in `public` auth mode doesn't have. Such a server logs at startup, and offers its events by poll and push:

```text
Webhook event delivery is off: the server runs in public auth mode, so a subscription would have no owner. Configure an auth mode that signs callers in to deliver events by webhook.
```

A server that offers no event in any mode serves no events: it doesn't advertise the capability, and `events/list` answers `-32601`. That is a server that performs no mode, or none that its events' own `delivery` allows. Its events are still registered and checked at startup, and `publish()` still runs.

A server that serves events advertises them in two places, on every transport, so a client of either [dialect](https://frontmcp.dev/reference/sdk/event-delivery#dialects) finds them:

```json
{ "capabilities": { "events": {}, "extensions": { "io.modelcontextprotocol/events": {} } } }
```

<a id="eventspoll-eventspush-and-eventsbuffer"></a>

### `events.poll`, `events.push` and `events.buffer`

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `poll.enabled` | `boolean` | `true` | `false` turns `events/poll` off. |
| `poll.nextPollMs` | `number` | `30000` | The wait between two polls the server recommends. Also how often an event's `check()` is called for a stream or a webhook subscription. |
| `poll.maxEvents` | `number` | `100` | The most occurrences one poll returns, and the cap of a request's `maxEvents`. |
| `push.enabled` | `boolean` | `true` | `false` turns `events/stream` off. |
| `push.heartbeatMs` | `number` | `25000` | How often an open stream sends a heartbeat with its cursor. |
| `buffer.maxAgeMs` | `number` | `600000` (10 minutes) | How long a published occurrence can still be polled, or replayed on a stream. |
| `buffer.maxEvents` | `number` | `10000` | How many occurrences are kept for one event. |

The buffer is in the memory of the process that published. It isn't in the [store](https://frontmcp.dev/reference/sdk/events-options#eventsstore), so it doesn't survive a restart and isn't shared between processes. An event with [`check()`](https://frontmcp.dev/reference/sdk/event#reading-an-upstream-that-can-replay) doesn't use it.

<a id="eventswebhook-and-eventswebhookdelivery"></a>

### `events.webhook` and `events.webhook.delivery`

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `enabled` | `boolean` | `true` | `false` turns webhook delivery off. |
| `allowedCallbacks` | `string[]` | `[]` | Callback URLs accepted without a [verification](https://frontmcp.dev/reference/sdk/event-delivery#callback-verification) request: a URL, or a prefix that ends at a `/`. For receivers you run yourself. |
| `verification.cacheTtlMs` | `number` | `3600000` (1 hour) | How long a callback a caller proved stays verified for that caller. |
| `verification.timeoutMs` | `number` | `10000` | How long the callback has to answer the verification request. |
| `verification.maxAttemptsPerHost` | `number` | `10` | Verification attempts one callback host may get in a minute, whatever its port. |
| `rotationGraceMs` | `number` | `300000` (5 minutes) | How long deliveries are also signed with a secret that a refresh replaced. |
| `unsafeAllowLocalCallbacks` | `boolean` | `false` | For tests only: also accepts `http:` callbacks and loopback or private addresses. The server warns at startup when it's on. |

`events.webhook.delivery`, for [each delivery](https://frontmcp.dev/reference/sdk/event-delivery#retries):

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `timeoutMs` | `number` | `10000` | How long a callback has to answer one attempt. |
| `maxAttempts` | `number` | `5` | How many times one delivery is attempted. |
| `retryWindowMs` | `number` | `900000` (15 minutes) | How long after its first attempt a delivery is still retried. |
| `backoffMs` | `number` | `1000` | The wait before the second attempt. It doubles with each attempt. Must not exceed `maxBackoffMs`. |
| `maxBackoffMs` | `number` | `60000` | The longest wait between two attempts. |
| `concurrency` | `number` | `16` | How many deliveries are in flight at once in one process. |

In a long-lived process, deliveries happen after `publish()` returned. On a serverless or edge runtime, where nothing runs after the response, the first attempt of each delivery is made before `publish()` resolves, so `publish()` can take as long as the slowest callback, up to `timeoutMs`. A retry there runs during a later `publish()`.

<a id="eventssubscriptions"></a>

### `events.subscriptions`

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `defaultTtlMs` | `number` | `3600000` (1 hour) | The [lifetime](https://frontmcp.dev/reference/sdk/event-delivery#lifetime) of a webhook subscription that asks for none. |
| `maxTtlMs` | `number` | `86400000` (24 hours) | The longest lifetime granted. |
| `minTtlMs` | `number` | `60000` (1 minute) | The shortest lifetime granted, whatever a subscription asks for. |
| `allowNoExpiry` | `boolean` | `false` | Grants `ttlMs: null`, a subscription that never expires, for an event without a `ttl.maxMs` of its own. Needs `store.redis` or `store.sqlite`. |
| `maxPerPrincipal` | `number` | `100` | How many webhook subscriptions one caller may hold. Also its limit of open streams, and of [poll leases](https://frontmcp.dev/reference/sdk/event-delivery#the-poll-subscription), each counted by itself. |
| `reauthorizeEveryMs` | `number` | `300000` (5 minutes) | How often a subscription's owner is [checked again](https://frontmcp.dev/reference/sdk/event-delivery#access-over-a-subscriptions-life) against the event's `authorities` and `authorize()`. |
| `suspendedTtlMs` | `number` | `604800000` (7 days) | How long a [suspended](https://frontmcp.dev/reference/sdk/event-delivery#suspension) subscription without expiry is kept before it's ended. |

The three lifetimes must satisfy `minTtlMs <= defaultTtlMs <= maxTtlMs` once the defaults are applied. A server that lowers `maxTtlMs` below one hour sets `defaultTtlMs` too. An event's own [`ttl`](https://frontmcp.dev/reference/sdk/event#options) narrows these for that event.

<a id="eventsstore"></a>

### `events.store`

Where webhook subscriptions, their pending deliveries, and the answers of [repeated publish requests](https://frontmcp.dev/reference/sdk/events-options#repeated-requests) are kept:

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `sqlite` | `{ path, … }` | none | A SQLite file. `path` is required. See [SQLite](https://frontmcp.dev/reference/deployment/sqlite). |
| `redis` | Redis options | none | A Redis server. See [Redis](https://frontmcp.dev/reference/deployment/redis). Vercel KV is refused: it has no atomic compare-and-set, which subscription updates need. |
| `keyPrefix` | `string` | `mcp:events:` and a hash of the server's name, then `:` | The prefix of every key the store writes, so servers that share a store don't see each other's subscriptions. |

`sqlite` or `redis`, not both. Without either, the store is the process's memory:

| | Memory (the default) | `sqlite` or `redis` |
| --- | --- | --- |
| Subscriptions | End with the process. Clients subscribe again | Kept, and shared by every process of the server |
| Pending deliveries | End with the process | Survive a restart. Another process takes over those of one that died |
| An event's `check()` position, for webhook | Forgotten. The client's next `events/subscribe` replays from the cursor it sends | Kept. A restart continues from it |
| Streams across processes | A stream carries what its own process publishes | With `redis`, each process relays what it publishes to the others |

The relay between processes runs on the subscription store, so it needs a server that performs the webhook mode, and the push mode. In `public` auth mode, or with `webhook.enabled: false`, `store.redis` relays nothing, and each stream carries what its own process publishes. A server whose streams nothing relays says so at startup, at `info` level, and why:

| The server has | The line |
| --- | --- |
| No `store.redis` | `Event streams carry what this process publishes. With several processes, set events.store.redis so an event published on one reaches the streams the others hold.` |
| `store.redis`, in `public` auth mode | `Event streams carry what this process publishes. events.store.redis is set, but it relays events between processes only with webhook delivery, which is off: the server runs in public auth mode, so configure an auth mode that signs callers in. Then an event published on one process reaches the streams the others hold.` |
| `store.redis` and `webhook.enabled: false` | The same, with the reason `events.webhook.enabled is false, so remove that setting`. With both, both reasons, separated by `;`. |

The three lines were read in Node, from servers made with `createFetchHandler()`, with a Redis store that was never reached. Changed in 1.12.1: before, a server with `store.redis` got the first line, which tells it to set what it has.

A store that outlives the process holds webhook secrets, so it encrypts them, and needs a secret to do that with: the `MCP_EVENTS_SECRET` environment variable, else `MCP_SESSION_SECRET`, else `MCP_SERVER_SECRET`. Without one the server doesn't start. [Configuration files](https://frontmcp.dev/reference/server/config-files#environment-variables) lists the environment variables FrontMCP reads.

<a id="eventspublishendpoint"></a>

### `events.publishEndpoint`

Lets another service publish an event with one HTTP `POST`, without linking the SDK: a backend, a queue consumer, a cron container. Off by default.

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `enabled` | `boolean` | `false` | Serves the endpoint. |
| `path` | `string` | `/events/publish` | Where it's served, at the root of the server, not under the MCP endpoint's path. Starts with `/`, with literal segments only. |
| `secret` | `string` | none | At least 32 characters. Every request is then signed with it. Without it, a caller presents the bearer credentials of the MCP endpoint. |
| `authorities` | profile name, names, or a rule | none | The rule a bearer caller must satisfy, with the request's body as the rule's input. Not together with `secret`. |

The request body is JSON, and `POST` is the only method:

| Field | Type | Description |
| --- | --- | --- |
| `name` | `string` | Required. The name of a registered event. |
| `data` | `object` | Required. Checked against the event's `payloadSchema`. |
| `eventId` | `string` | 1 to 255 visible ASCII characters, with no space. Makes the request [repeatable](https://frontmcp.dev/reference/sdk/events-options#repeated-requests). |
| `timestamp` | `string` | A date, such as `2026-11-02T12:00:00Z`. |
| `audience` | `{ sub?, tenantId?, roles?: { any?, all? } }` | As the `audience` option of [`publish()`](https://frontmcp.dev/reference/sdk/event#thiseventspublishevent-data-options). |
| `subscriptionId` | `string` | As the `subscriptionId` option of `publish()`. |

The answer is `202` with what `publish()` returns: `{ "eventId": "evt_…", "matched": 0 }`. A key the endpoint doesn't know is refused with `400`, so a misspelled `audience` never turns into a publish to everyone.

<a id="who-may-publish"></a>

#### Who may publish

| | With `secret` | Without `secret` |
| --- | --- | --- |
| A request carries | `X-FrontMCP-Timestamp`: the time of signing, in Unix seconds. `X-FrontMCP-Signature`: `v1=` and the hex HMAC-SHA256, keyed with the secret, of the timestamp, a `.`, and the body's bytes as sent | `Authorization: Bearer …`, the credentials the MCP endpoint takes |
| Refused when | The timestamp is more than 5 minutes from the server's clock, the signature is wrong, or the same signature was accepted before | The token doesn't verify, the caller is anonymous, or `authorities` refuses it |
| Works in `public` auth mode | Yes | No: the server doesn't start |

The signature is the one a [workflow webhook](https://frontmcp.dev/reference/sdk/workflow#workflow-triggers) takes. To send a request again, sign it again.

Without `secret` and without `authorities`, every signed-in caller may publish every event, to any `audience`, and the server warns about it at startup. Set `authorities` unless every signed-in caller is trusted to publish.

<a id="what-the-endpoint-answers"></a>

#### What the endpoint answers

The first check that fails answers:

| Status | Body | When |
| --- | --- | --- |
| `415` | `{ "error": "The body must be application/json" }` | The `Content-Type` isn't `application/json`. |
| `413` | `{ "error": "Payload too large" }` | The body is over 262144 bytes, what one delivery may carry. |
| `401` | `{ "error": "Unauthorized" }` | With `secret`: unsigned, outside the 5 minutes, a wrong signature, or sent before. Without: no token, or one the server can't verify. |
| `400` | `{ "error": "Invalid publish request", "issues": [{ path, message }] }` | The body isn't a JSON object of the fields above. |
| `403` | `{ "error": "Forbidden" }` | `authorities` refuses the caller. |
| `404` | `{ "error": "Event \"…\" is not registered" }` | The server has no event of that name. |
| `422` | `{ "error": "data does not match the payloadSchema of event \"…\"", "issues": […] }` | `data` doesn't match `payloadSchema`. |
| `409` | `{ "error": "Event \"…\" with eventId \"…\" is being published; retry for its answer" }` | Another request with the same `eventId` is publishing right now. |
| `202` | `{ eventId, matched }` | Published, or already published with this `eventId`. |

`issues` say where a problem is and what it is. They never repeat a value of the request. With a `secret`, every refusal of a signature is the same `401`, and the server's log says which check refused it. The server's global rate limit and IP filter ([`throttle`](https://frontmcp.dev/reference/sdk/guard)) apply before all of these.

<a id="repeated-requests"></a>

#### Repeated requests

A request that names an `eventId` is idempotent for 10 minutes, per event name: a repeat within them is answered `202` with the answer of the first request, and nothing is published again. So a sender that retries after a timeout sends the same `eventId`, and signs the retry again.

- The answers are kept in the [store](https://frontmcp.dev/reference/sdk/events-options#eventsstore). With `redis` or `sqlite`, every process of the server sees them.
- A publish that fails gives its `eventId` back: the retry publishes.
- While the first request is still publishing, a repeat is answered `409`.
- A request without an `eventId` gets a generated one, and is never deduplicated.

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

#### Caveats

- **A misspelled key under `events` stops startup**, at any level: `events: { subscriptions: { maxPerPrincipl: 2 } }` fails with a `ZodError` whose issue is `Unrecognized key: "maxPerPrincipl"`, at `path: ["events", "subscriptions"]`. So does a value of the wrong type, and a combination that can't work stops it with the option's name. Changed in 1.12.1: before, an unknown key was dropped and its default applied, so `events: { pol: { enabled: false } }` started a server that still polled.
- **`events.enabled: false` isn't the way to hide one event.** It turns every event off. Use the event's own [`hideFromDiscovery`, `availableWhen` or `authorities`](https://frontmcp.dev/reference/sdk/event#what-eventslist-shows).
- **On a `splitByApp` server**, each app serves its own publish endpoint under its route base, such as `/billing/events/publish`, for the events of that app.
- **`this.scope.events`** is the server's event registry, with `getEvents()`, `findByName(name)`, `deliveryModesOf(event)` and `servesEvents()`. It's `undefined` when events are off. [Scope and registries](https://frontmcp.dev/reference/sdk/scope) covers the scope.
- **Counters, traces and the readiness check** that events add are listed in [Observability and telemetry](https://frontmcp.dev/reference/server/observability) and [Health checks and metrics](https://frontmcp.dev/reference/deployment/health-and-metrics).

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

## Usage

<a id="turning-delivery-modes-on-and-off"></a>

### Turning delivery modes on and off

Each mode has its own switch. Turning one off takes it out of every event's `delivery`, and its request stops existing:

```ts modes.test.ts active
import { test, expect } from "@frontmcp/testing";
import { App, event, z } from "@frontmcp/sdk";
import { serverWith } from "./client";

// Webhook only, and a public server performs no webhook mode.
const invoicePaid = event({ name: "invoice.paid", payloadSchema: { invoiceId: z.string() }, delivery: ["webhook"] });

@App({ id: "billing", name: "Billing", events: [invoicePaid] })
class BillingApp {}

test("by default a public server polls and streams", async () => {
  const rpc = serverWith({});
  expect((await rpc("events/list")).result.events[0].delivery).toEqual(["poll", "push"]);
});

test("without poll, events are offered by push only, and events/poll doesn't exist", async () => {
  const rpc = serverWith({ poll: { enabled: false } });
  expect((await rpc("events/list")).result.events[0].delivery).toEqual(["push"]);
  expect((await rpc("events/poll", { name: "ticket.created" })).error).toEqual({ code: -32601, message: "Method not found: events/poll" });
});

test("with no mode left, the server serves no events, but publishing still runs", async () => {
  const rpc = serverWith({ poll: { enabled: false }, push: { enabled: false } });
  expect((await rpc("events/list")).error).toEqual({ code: -32601, message: "Method not found: events/list" });
  expect((await rpc("server/discover")).result.capabilities.events).toBeUndefined();

  const created = await rpc("tools/call", { name: "create_ticket", arguments: {} });
  expect(created.result.structuredContent).toMatchObject({ eventId: expect.stringMatching(/^evt_/), matched: 0 });
});

test("events that allow only a mode the server doesn't perform aren't served either", async () => {
  const rpc = serverWith({}, [BillingApp]);
  expect((await rpc("events/list")).error).toEqual({ code: -32601, message: "Method not found: events/list" });
  expect((await rpc("server/discover")).result.capabilities.events).toBeUndefined();
});

test("events.enabled: false turns everything off, publishing included", async () => {
  const rpc = serverWith({ enabled: false });
  expect((await rpc("events/list")).error.code).toBe(-32601);

  const created = await rpc("tools/call", { name: "create_ticket", arguments: {} });
  expect(created.result.structuredContent).toEqual({
    refused: "Events are not enabled on this server, so nothing can be published. List the event in an app's `events`, and remove events.enabled: false if it is set.",
  });
});

test("poll options change what a poll answers", async () => {
  const rpc = serverWith({ poll: { nextPollMs: 5000 } });
  expect((await rpc("events/poll", { name: "ticket.created" })).result.nextPollMs).toBe(5000);
});
```

```ts main.ts
import { App, Tool, ToolContext, event, z } from "@frontmcp/sdk";

export const ticketCreated = event({ name: "ticket.created", payloadSchema: { ticketId: z.string() } });

@Tool({ name: "create_ticket", description: "Open a support ticket", inputSchema: {} })
class CreateTicket extends ToolContext {
  async execute() {
    try {
      return await this.events.publish(ticketCreated, { ticketId: "T-4" });
    } catch (error) {
      return { refused: (error as Error).message };
    }
  }
}

@App({ id: "help-desk", name: "Help Desk", tools: [CreateTicket], events: [ticketCreated] })
export class HelpDeskApp {}
```

```ts client.ts
import { FrontMcpInstance } from "@frontmcp/sdk";
import { HelpDeskApp } from "./main";

/** Builds a server with these events options and apps, and returns a function that sends it one request. */
export function serverWith(events: Record<string, unknown>, apps = [HelpDeskApp]) {
  const server = FrontMcpInstance.createFetchHandler({ info: { name: "help-desk", version: "1.0.0" }, apps, events });
  return async (method: string, params: Record<string, unknown> = {}) => {
    const response = await (await server)(
      new Request("https://desk.example.com/", {
        method: "POST",
        headers: {
          "content-type": "application/json",
          "mcp-protocol-version": "2026-07-28",
          "mcp-method": method,
          ...(typeof params.name === "string" ? { "mcp-name": params.name } : {}),
        },
        body: JSON.stringify({
          jsonrpc: "2.0",
          id: 1,
          method,
          params: { ...params, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } },
        }),
      }),
    );
    return response.json();
  };
}
```

<a id="publishing-over-http"></a>

### Publishing over HTTP

With `publishEndpoint.enabled` and a `secret`, a service that holds the secret publishes with one signed `POST`. The request goes through the same `publish()` as `this.events.publish()`, so a client that polls afterwards reads the occurrence:

```ts publish.test.ts active
import { test, expect } from "@frontmcp/testing";
import { publishOverHttp, rpc } from "./client";

test("a signed request publishes, and a polling client reads the occurrence", async () => {
  const start = (await rpc("events/poll", { name: "ticket.created", cursor: null })).result.cursor;

  const published = await publishOverHttp({ name: "ticket.created", data: { ticketId: "T-9" } });
  expect(published).toEqual({ status: 202, body: { eventId: expect.stringMatching(/^evt_/), matched: 0 } });

  const { events } = (await rpc("events/poll", { name: "ticket.created", cursor: start })).result;
  expect(events).toMatchObject([{ eventId: published.body.eventId, data: { ticketId: "T-9" } }]);
});

test("the same eventId sent twice is published once", async () => {
  const start = (await rpc("events/poll", { name: "ticket.created", cursor: null })).result.cursor;
  const publication = { name: "ticket.created", data: { ticketId: "T-10" }, eventId: "crm-change-771", timestamp: "2026-11-02T12:00:00Z" };

  const first = await publishOverHttp(publication);
  // A second later, so the retry has another timestamp and another signature.
  await new Promise((resolve) => setTimeout(resolve, 1100));
  const retry = await publishOverHttp(publication);
  expect(first).toEqual({ status: 202, body: { eventId: "crm-change-771", matched: 0 } });
  expect(retry).toEqual(first);

  const { events } = (await rpc("events/poll", { name: "ticket.created", cursor: start })).result;
  expect(events).toMatchObject([{ eventId: "crm-change-771", timestamp: "2026-11-02T12:00:00.000Z" }]);
});

test("a wrong secret, or an old timestamp, is unauthorized", async () => {
  const publication = { name: "ticket.created", data: { ticketId: "T-11" } };
  const wrongSecret = await publishOverHttp(publication, { secret: "not-the-secret-this-server-was-given" });
  const tenMinutesAgo = await publishOverHttp(publication, { timestamp: Math.floor(Date.now() / 1000) - 600 });
  expect(wrongSecret).toEqual({ status: 401, body: { error: "Unauthorized" } });
  expect(tenMinutesAgo).toEqual(wrongSecret);
});

test("each mistake in the body has its own status", async () => {
  const misspelled = await publishOverHttp({ name: "ticket.created", data: { ticketId: "T-12" }, audiense: { sub: "nour" } });
  expect(misspelled).toEqual({
    status: 400,
    body: { error: "Invalid publish request", issues: [{ path: "", message: 'Unrecognized key: "audiense"' }] },
  });

  const unknown = await publishOverHttp({ name: "ticket.closed", data: {} });
  expect(unknown).toEqual({ status: 404, body: { error: 'Event "ticket.closed" is not registered' } });

  const invalid = await publishOverHttp({ name: "ticket.created", data: { ticketId: 12 } });
  expect(invalid).toEqual({
    status: 422,
    body: {
      error: 'data does not match the payloadSchema of event "ticket.created"',
      issues: [{ path: "ticketId", message: "Invalid input: expected string, received number" }],
    },
  });
});
```

```ts client.ts
import { FrontMcpInstance } from "@frontmcp/sdk";
import { PUBLISH_SECRET, config } from "./main";

let server: ReturnType<typeof FrontMcpInstance.createFetchHandler> | undefined;
const encoder = new TextEncoder();

/** The hex HMAC-SHA256 of "<timestamp>.<body>", keyed with the secret. */
async function sign(secret: string, timestamp: number, body: string) {
  const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const mac = await crypto.subtle.sign("HMAC", key, encoder.encode(`${timestamp}.${body}`));
  return [...new Uint8Array(mac)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
}

/** What another service does to publish: one signed POST. */
export async function publishOverHttp(publication: unknown, options: { secret?: string; timestamp?: number } = {}) {
  server ??= FrontMcpInstance.createFetchHandler(config);
  const body = JSON.stringify(publication);
  const timestamp = options.timestamp ?? Math.floor(Date.now() / 1000);
  const response = await (await server)(
    new Request("https://desk.example.com/events/publish", {
      method: "POST",
      headers: {
        "content-type": "application/json",
        "x-frontmcp-timestamp": String(timestamp),
        "x-frontmcp-signature": `v1=${await sign(options.secret ?? PUBLISH_SECRET, timestamp, body)}`,
      },
      body,
    }),
  );
  return { status: response.status, body: await response.json() };
}

/** Sends one MCP request, as a 2026-07-28 client would over HTTP. */
export async function rpc(method: string, params: Record<string, unknown> = {}) {
  server ??= FrontMcpInstance.createFetchHandler(config);
  const response = await (await server)(
    new Request("https://desk.example.com/", {
      method: "POST",
      headers: {
        "content-type": "application/json",
        "mcp-protocol-version": "2026-07-28",
        "mcp-method": method,
        ...(typeof params.name === "string" ? { "mcp-name": params.name } : {}),
      },
      body: JSON.stringify({
        jsonrpc: "2.0",
        id: 1,
        method,
        params: { ...params, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } },
      }),
    }),
  );
  return response.json();
}
```

```ts main.ts
import { App, event, z } from "@frontmcp/sdk";

export const ticketCreated = event({ name: "ticket.created", payloadSchema: { ticketId: z.string() } });

@App({ id: "help-desk", name: "Help Desk", events: [ticketCreated] })
export class HelpDeskApp {}

// In your project, read it from the environment: process.env.EVENTS_PUBLISH_SECRET
export const PUBLISH_SECRET = "an-example-secret-of-at-least-32-characters";

export const config = {
  info: { name: "help-desk", version: "1.0.0" },
  apps: [HelpDeskApp],
  events: { publishEndpoint: { enabled: true, secret: PUBLISH_SECRET } },
};
```

From a shell, the same request:

```bash
body='{"name":"ticket.created","data":{"ticketId":"T-9"}}'
timestamp=$(date +%s)
signature=$(printf '%s.%s' "$timestamp" "$body" | openssl dgst -sha256 -hmac "$EVENTS_PUBLISH_SECRET" -r | cut -d' ' -f1)
curl -X POST https://desk.example.com/events/publish \
  -H 'Content-Type: application/json' \
  -H "X-FrontMCP-Timestamp: $timestamp" \
  -H "X-FrontMCP-Signature: v1=$signature" \
  --data-binary "$body"
```

<a id="letting-signed-in-callers-publish"></a>

### Letting signed-in callers publish

Without a `secret`, the endpoint takes the bearer credentials of the MCP endpoint, so a service publishes with the token it already has. `authorities` then decides what each caller may publish. Its rule reads the request's body as `input`, so this one lets callers publish `ticket.created` and nothing else:

```ts bearer.test.ts active
import { test, expect } from "@frontmcp/testing";
import { publishAs } from "./client";

test("a caller with a key publishes the event the rule allows", async () => {
  const published = await publishAs("crm-sync-key", { name: "ticket.created", data: { ticketId: "T-9" } });
  expect(published).toMatchObject({ status: 202, body: { matched: 0 } });
});

test("the same caller is refused another event", async () => {
  const refused = await publishAs("crm-sync-key", { name: "ticket.closed", data: { ticketId: "T-9" } });
  expect(refused).toEqual({ status: 403, body: { error: "Forbidden" }, challenge: null });
});

test("a request without a token, or with a wrong one, is unauthorized", async () => {
  const publication = { name: "ticket.created", data: { ticketId: "T-9" } };
  expect(await publishAs(undefined, publication)).toEqual({ status: 401, body: { error: "Unauthorized" }, challenge: 'Bearer realm="mcp"' });
  expect(await publishAs("not-a-key", publication)).toMatchObject({ status: 401, body: { error: "Unauthorized" } });
});
```

```ts main.ts
import { App, event, z } from "@frontmcp/sdk";

const payloadSchema = { ticketId: z.string() };
export const ticketCreated = event({ name: "ticket.created", payloadSchema });
export const ticketClosed = event({ name: "ticket.closed", payloadSchema });

@App({ id: "help-desk", name: "Help Desk", events: [ticketCreated, ticketClosed] })
export class HelpDeskApp {}

// In your project: @FrontMcp(config) export default class Server {}
export const config = {
  info: { name: "help-desk", version: "1.0.0" },
  apps: [HelpDeskApp],
  auth: { mode: "static" as const, tokens: ["crm-sync-key"] },
  // An endpoint rule needs the server's authorities turned on, as a rule on a tool does.
  authorities: { claimsMapping: { roles: "roles" } },
  events: {
    publishEndpoint: {
      enabled: true,
      path: "/hooks/publish",
      authorities: { attributes: { conditions: [{ path: "input.name", op: "eq", value: "ticket.created" }] } },
    },
  },
};
```

```ts client.ts
import { FrontMcpInstance } from "@frontmcp/sdk";
import { config } from "./main";

let server: ReturnType<typeof FrontMcpInstance.createFetchHandler> | undefined;

export async function publishAs(key: string | undefined, publication: unknown) {
  server ??= FrontMcpInstance.createFetchHandler(config);
  const response = await (await server)(
    new Request("https://desk.example.com/hooks/publish", {
      method: "POST",
      headers: { "content-type": "application/json", ...(key ? { authorization: `Bearer ${key}` } : {}) },
      body: JSON.stringify(publication),
    }),
  );
  return { status: response.status, body: await response.json(), challenge: response.headers.get("www-authenticate") };
}
```

With an identity provider, a rule can compare the event's name with a claim of the caller's token, such as `{ path: "input.name", op: "eq", value: { fromClaims: "publishes" } }`. [Authorities](https://frontmcp.dev/reference/auth/authorities#rules-on-the-calls-arguments) covers rules on input.

<a id="keeping-subscriptions-across-restarts"></a>

### Keeping subscriptions across restarts

In memory, a restart ends every webhook subscription, and each client has to subscribe again. Name a store, and set the secret it encrypts webhook secrets with:

```ts main.ts
@FrontMcp({
  info: { name: "help-desk", version: "1.0.0" },
  apps: [HelpDeskApp],
  auth: { mode: "transparent", provider: "https://auth.example.com" },
  events: {
    // One file on one machine. With several machines: store: { redis: { host: "redis.internal" } }
    store: { sqlite: { path: "./data/events.sqlite" } },
    subscriptions: { allowNoExpiry: true },
  },
})
export default class Server {}
```

```bash
MCP_EVENTS_SECRET=$(openssl rand -hex 32)
```

> **Note**
>
> SQLite and Redis don't run in a browser, so this isn't a running example: the store's behaviour on this page comes from FrontMCP's source and its tests. What does run here is the check that refuses a store without a secret, in [the first Troubleshooting entry](https://frontmcp.dev/reference/sdk/events-options#event-subscription-store-the-sqlite-store-keeps-webhook-signing-secrets).

<a id="changing-lifetimes-and-limits"></a>

### Changing lifetimes and limits

`subscriptions` bounds what a client may ask for, and an event's `ttl` narrows it for one event. This server grants at most two hours, half an hour by default, and two subscriptions per caller:

```ts lifetimes.test.ts active
import { test, expect } from "@frontmcp/testing";
import { rpc } from "./client";

const secret = `whsec_${btoa("0123456789012345678901234567890123")}`;
const delivery = { url: "https://hooks.example.com/mcp/desk", secret };
const minutes = (refreshBefore: string) => Math.round((Date.parse(refreshBefore) - Date.now()) / 60_000);
const subscribe = async (name: string, extra: Record<string, unknown> = {}) => (await rpc("events/subscribe", { name, delivery, ...extra })).result;

test("a subscription that asks for nothing gets the default", async () => {
  expect(minutes((await subscribe("ticket.created")).refreshBefore)).toBe(30);
});

test("a request is kept between the minimum and the maximum", async () => {
  expect(minutes((await subscribe("ticket.created", { ttlMs: 1_000 })).refreshBefore)).toBe(1);
  expect(minutes((await subscribe("ticket.created", { ttlMs: 86_400_000 })).refreshBefore)).toBe(120);
});

test("ttlMs: null gets the maximum, since this server grants no subscription without expiry", async () => {
  expect(minutes((await subscribe("ticket.created", { ttlMs: null })).refreshBefore)).toBe(120);
});

test("an event's own ttl narrows the server's", async () => {
  expect(minutes((await subscribe("ticket.escalated")).refreshBefore)).toBe(5);
  expect(minutes((await subscribe("ticket.escalated", { ttlMs: 3_600_000 })).refreshBefore)).toBe(10);
});

test("a third subscription is over the caller's limit", async () => {
  await subscribe("ticket.created");
  await subscribe("ticket.escalated");
  const third = await rpc("events/subscribe", { name: "ticket.created", arguments: { queue: "billing" }, delivery });
  expect(third.error).toMatchObject({
    code: -32025,
    message: "The limit of 2 webhook subscriptions per caller is reached. Remove one with events/unsubscribe, then retry.",
    data: { limit: "subscriptions", max: 2 },
  });
});

test("poll leases are counted by themselves, up to the same limit", async () => {
  await subscribe("ticket.created");
  await subscribe("ticket.escalated");
  const poll = (queue: string) => rpc("events/poll", { name: "ticket.watched", arguments: { queue } });

  expect((await poll("billing")).result.events).toEqual([]);
  expect((await poll("login")).result.events).toEqual([]);
  expect((await poll("returns")).error).toMatchObject({ code: -32025, data: { limit: "pollLeases", max: 2 } });
});
```

```ts main.ts
import { App, event, z } from "@frontmcp/sdk";

const payloadSchema = { ticketId: z.string() };

export const ticketCreated = event({ name: "ticket.created", inputSchema: { queue: z.string().optional() }, payloadSchema });

// Escalations matter for minutes, not hours.
export const ticketEscalated = event({
  name: "ticket.escalated",
  payloadSchema,
  ttl: { defaultMs: 5 * 60_000, maxMs: 10 * 60_000 },
});

// An event with a lifecycle method keeps a lease per poller.
export const ticketWatched = event({ name: "ticket.watched", inputSchema: { queue: z.string() }, payloadSchema, onSubscribe() {} });

@App({ id: "help-desk", name: "Help Desk", events: [ticketCreated, ticketEscalated, ticketWatched] })
export class HelpDeskApp {}

export const config = {
  info: { name: "help-desk", version: "1.0.0" },
  apps: [HelpDeskApp],
  auth: { mode: "static" as const, tokens: ["agent-nour-key"] },
  events: {
    subscriptions: { defaultTtlMs: 30 * 60_000, maxTtlMs: 120 * 60_000, maxPerPrincipal: 2 },
    webhook: { allowedCallbacks: ["https://hooks.example.com/mcp/"] },
  },
};
```

```ts client.ts
import { FrontMcpInstance } from "@frontmcp/sdk";
import { config } from "./main";

let server: ReturnType<typeof FrontMcpInstance.createFetchHandler> | undefined;

export async function rpc(method: string, params: Record<string, unknown> = {}) {
  server ??= FrontMcpInstance.createFetchHandler(config);
  const response = await (await server)(
    new Request("https://desk.example.com/", {
      method: "POST",
      headers: {
        "content-type": "application/json",
        "mcp-protocol-version": "2026-07-28",
        "mcp-method": method,
        authorization: "Bearer agent-nour-key",
        ...(typeof params.name === "string" ? { "mcp-name": params.name } : {}),
      },
      body: JSON.stringify({
        jsonrpc: "2.0",
        id: 1,
        method,
        params: { ...params, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } },
      }),
    }),
  );
  return response.json();
}
```

`maxPerPrincipal` counts each kind of subscription by itself. In the last test the caller already holds two webhook subscriptions, and still gets two [poll leases](https://frontmcp.dev/reference/sdk/event-delivery#the-poll-subscription) before the third is refused, with `limit: "pollLeases"`. An open stream over the limit gets `limit: "streams"`. Each limit has [its own message](https://frontmcp.dev/reference/sdk/event-delivery#the-limit-of--per-caller-is-reached).

<a id="pinning-the-dialect"></a>

### Pinning the dialect

With `compat: "auto"`, FrontMCP decides per caller. Pin a dialect when every client of a server speaks the same one, or to see what the other looks like:

```ts compat.test.ts active
import { test, expect } from "@frontmcp/testing";
import { serverWith } from "./client";

const notFound = async (compat: string | undefined, clientName: string) => {
  const rpc = serverWith(compat ? { compat } : {});
  return (await rpc("events/poll", { name: "ticket.closed" }, clientName)).error.code;
};

test("auto answers each caller in its own dialect", async () => {
  expect(await notFound(undefined, "desk-agent")).toBe(-32023);
  expect(await notFound(undefined, "ChatGPT")).toBe(-32011);
});

test("sep-3415 answers every caller with SEP-3415's codes", async () => {
  expect(await notFound("sep-3415", "ChatGPT")).toBe(-32023);
});

test("sketch answers every caller with the sketch's codes", async () => {
  expect(await notFound("sketch", "desk-agent")).toBe(-32011);
});

test("the capability is advertised in both places, whatever the dialect", async () => {
  const rpc = serverWith({ compat: "sketch" });
  const { capabilities } = (await rpc("server/discover", {}, "desk-agent")).result;
  expect(capabilities).toMatchObject({ events: {}, extensions: { "io.modelcontextprotocol/events": {} } });
});
```

```ts main.ts
import { App, event, z } from "@frontmcp/sdk";

export const ticketCreated = event({ name: "ticket.created", payloadSchema: { ticketId: z.string() } });

@App({ id: "help-desk", name: "Help Desk", events: [ticketCreated] })
export class HelpDeskApp {}
```

```ts client.ts
import { FrontMcpInstance } from "@frontmcp/sdk";
import { HelpDeskApp } from "./main";

/** Builds a server with these events options, and returns a function that sends it one request as a named client. */
export function serverWith(events: Record<string, unknown>) {
  const server = FrontMcpInstance.createFetchHandler({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], events });
  return async (method: string, params: Record<string, unknown>, clientName: string) => {
    const response = await (await server)(
      new Request("https://desk.example.com/", {
        method: "POST",
        headers: {
          "content-type": "application/json",
          "mcp-protocol-version": "2026-07-28",
          "mcp-method": method,
          ...(typeof params.name === "string" ? { "mcp-name": params.name } : {}),
        },
        body: JSON.stringify({
          jsonrpc: "2.0",
          id: 1,
          method,
          params: {
            ...params,
            _meta: {
              "io.modelcontextprotocol/protocolVersion": "2026-07-28",
              "io.modelcontextprotocol/clientInfo": { name: clientName, version: "1.0.0" },
            },
          },
        }),
      }),
    );
    return response.json();
  };
}
```

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

## Troubleshooting

<a id="event-subscription-store-the-sqlite-store-keeps-webhook-signing-secrets"></a>

### `Event subscription store: the sqlite store keeps webhook signing secrets…`

`events.store` names SQLite or Redis, and no secret is set to encrypt the stored webhook secrets with (`EventSubscriptionStoreError`, `EVENT_SUBSCRIPTION_STORE`). Set `MCP_EVENTS_SECRET`. The server also refuses `store` with both `sqlite` and `redis`, `allowNoExpiry` without either, and a key the `events` option doesn't know:

```ts startup.test.ts active
import { test, expect } from "@frontmcp/testing";
import { FrontMcpInstance } from "@frontmcp/sdk";
import { HelpDeskApp } from "./main";

const start = (events: Record<string, unknown>) =>
  FrontMcpInstance.createFetchHandler({
    info: { name: "help-desk", version: "1.0.0" },
    apps: [HelpDeskApp],
    auth: { mode: "static", tokens: ["agent-nour-key"] },
    events,
  });

test("a store that outlives the process needs a secret", async () => {
  await expect(start({ store: { sqlite: { path: "./events.sqlite" } } })).rejects.toThrow(
    "Event subscription store: the sqlite store keeps webhook signing secrets, so it needs a secret to encrypt them with: set MCP_EVENTS_SECRET (or MCP_SESSION_SECRET / MCP_SERVER_SECRET).",
  );
});

test("the store is sqlite or redis, not both", async () => {
  await expect(start({ store: { sqlite: { path: "./events.sqlite" }, redis: { host: "localhost" } } })).rejects.toThrow(
    "events.store takes redis or sqlite, not both",
  );
});

test("a subscription without expiry needs a store that keeps it", async () => {
  await expect(start({ subscriptions: { allowNoExpiry: true } })).rejects.toThrow(
    "events.subscriptions.allowNoExpiry needs events.store.redis or events.store.sqlite",
  );
});

test("a key the events option doesn't know stops startup", async () => {
  await expect(start({ subscriptions: { maxPerPrincipl: 2 } })).rejects.toMatchObject({
    issues: [{ code: "unrecognized_keys", path: ["events", "subscriptions"], message: 'Unrecognized key: "maxPerPrincipl"' }],
  });
});

test("the three lifetimes have to be in order", async () => {
  await expect(start({ subscriptions: { maxTtlMs: 30 * 60_000 } })).rejects.toThrow(
    "events.subscriptions needs minTtlMs <= defaultTtlMs <= maxTtlMs; set the three together",
  );
});

test("the publish endpoint has to know who publishes", async () => {
  await expect(start({ publishEndpoint: { enabled: true, secret: "too-short" } })).rejects.toThrow(
    "events.publishEndpoint.secret must be at least 32 characters (make one with: openssl rand -hex 32)",
  );
  const publicServer = FrontMcpInstance.createFetchHandler({
    info: { name: "help-desk", version: "1.0.0" },
    apps: [HelpDeskApp],
    events: { publishEndpoint: { enabled: true } },
  });
  await expect(publicServer).rejects.toThrow(
    "Event publish endpoint: the server runs in public auth mode, so nothing tells who publishes.",
  );
});
```

```ts main.ts
import { App, event, z } from "@frontmcp/sdk";

export const ticketCreated = event({ name: "ticket.created", payloadSchema: { ticketId: z.string() } });

@App({ id: "help-desk", name: "Help Desk", events: [ticketCreated] })
export class HelpDeskApp {}
```

<a id="eventssubscriptions-needs-minttlms--defaultttlms--maxttlms-set-the-three-together"></a>

### `events.subscriptions needs minTtlMs <= defaultTtlMs <= maxTtlMs; set the three together`

One of the three lifetimes was changed and is now out of order with the defaults of the others. Lowering `maxTtlMs` below one hour puts it under the default `defaultTtlMs`: set `defaultTtlMs` as well.

<a id="unrecognized-key-at-path-events-"></a>

### `Unrecognized key` at `path: ["events", …]`

A key under `events` isn't an option, often a misspelling, and the server doesn't start. The issue's `path` says where the key is, and its message which one: `Unrecognized key: "maxPerPrincipl"` at `["events", "subscriptions"]`. Fix the spelling with the [tables above](https://frontmcp.dev/reference/sdk/events-options#reference). Changed in 1.12.1: before, the key was dropped and its default applied.

<a id="webhook-event-delivery-is-off-the-server-runs-in-public-auth-mode"></a>

### `Webhook event delivery is off: the server runs in public auth mode`

A warning at startup, not an error: the server polls and streams. Webhook subscriptions need an [auth mode](https://frontmcp.dev/reference/auth/modes) that signs callers in, since each one belongs to a caller. A client that sends `events/subscribe` anyway gets `-32601`.

<a id="event-publish-endpoint-the-server-runs-in-public-auth-mode-so-nothing-tells-who-publishes"></a>

### `Event publish endpoint: the server runs in public auth mode, so nothing tells who publishes`

`publishEndpoint.enabled` without a `secret`, on a server in public auth mode (`EventPublishEndpointError`, `EVENT_PUBLISH_ENDPOINT`). Set `events.publishEndpoint.secret`, or an auth mode that signs callers in. The same error class names a `path` the server already uses: the MCP endpoint, a health or metrics path, or a route of your own.

<a id="eventspublishendpointsecret-must-be-at-least-32-characters"></a>

### `events.publishEndpoint.secret must be at least 32 characters`

Make one with `openssl rand -hex 32`. `events.publishEndpoint takes secret or authorities, not both` means both were set: a signed request names no caller for a rule to check.

<a id="post-eventspublish-answers-401"></a>

### `POST /events/publish` answers `401`

With a `secret`: the signature must be over `<timestamp>.<body>` with the body's bytes exactly as sent, the timestamp must be within 5 minutes of the server's clock, and a signature is accepted once, so sign a retry again. Without a `secret`: the request needs the `Authorization: Bearer …` header the MCP endpoint takes, from a caller who isn't anonymous.

<a id="post-eventspublish-answers-404"></a>

### `POST /events/publish` answers `404`

Read the body. `{ "error": "Event \"…\" is not registered" }` names an event no app declares. Any other `404` means nothing serves that path: `publishEndpoint.enabled` isn't `true`, the `path` differs, or the request isn't a `POST`.

<a id="post-eventspublish-answers-409"></a>

### `POST /events/publish` answers `409`

Another request with the same `eventId` is publishing right now. Retry: the answer is then the first request's.

<a id="events-are-disabled-eventsenabled-false-so-the--events-apps-declare-are-not-served"></a>

### `Events are disabled (events.enabled: false), so the … event(s) apps declare are not served`

A warning at startup. `events.enabled` is `false`, so no event is served and `publish()` throws. Remove the option to serve them.
