# Event subscriptions and delivery

> How an MCP client receives a FrontMCP server's events. The poll, push and webhook delivery modes, events/poll, events/stream and events/subscribe, signed webhook deliveries with retries and suspension, the errors a client gets, and the two dialects.

Source: https://frontmcp.dev/reference/sdk/event-delivery

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

A client receives a server's [events](https://frontmcp.dev/reference/sdk/event) in one of three ways: it asks again and again (`events/poll`), it holds one request open (`events/stream`), or it gives the server a URL to call (`events/subscribe`). This page is the client's side of MCP Events: what each request takes and answers, what a webhook delivery looks like and how it's signed and retried, the errors, and the older dialect ChatGPT speaks. MCP Events (SEP-3415) is a draft extension of MCP, so the requests on this page can still change. New in 1.12.0.

```ts
events/list                              // the event types this caller may subscribe to
events/poll        { name, arguments?, cursor?, maxEvents?, maxAgeMs? }
events/stream      { name, arguments?, cursor?, maxAgeMs? }
events/subscribe   { name, arguments?, delivery: { url, secret }, ttlMs?, cursor?, maxAgeMs? }
events/unsubscribe { name, arguments?, delivery: { url } }
```



---

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

## Reference

<a id="delivery-modes"></a>

### Delivery modes

| Mode | Request | How occurrences arrive | Use it when |
| --- | --- | --- | --- |
| `poll` | [`events/poll`](https://frontmcp.dev/reference/sdk/event-delivery#eventspoll) | In the answer to each request | The client can't hold a connection or be called: a script, a scheduled function. Nothing is kept on the server between polls. |
| `push` | [`events/stream`](https://frontmcp.dev/reference/sdk/event-delivery#eventsstream) | As notifications on one request that stays open | The client is connected anyway and wants each occurrence as it happens: a desktop app, an agent runtime. |
| `webhook` | [`events/subscribe`](https://frontmcp.dev/reference/sdk/event-delivery#eventssubscribe) | As signed HTTP `POST`s to a URL the client names | The client isn't connected when things happen: a hosted assistant such as ChatGPT, or a backend. |

- An event's `delivery` in [`events/list`](https://frontmcp.dev/reference/sdk/event#what-eventslist-shows) names the modes a client may use for it. A request in another mode is answered [`Unsupported`](https://frontmcp.dev/reference/sdk/event-delivery#errors).
- Which modes a server performs depends on its auth mode and where it runs: see [Events options](https://frontmcp.dev/reference/sdk/events-options#which-delivery-modes-a-server-performs). In short, `poll` and `push` work everywhere but serverless (`poll` only), and `webhook` needs an auth mode that signs callers in, since a subscription belongs to a caller.
- ChatGPT implements the webhook mode, in [an older dialect](https://frontmcp.dev/reference/sdk/event-delivery#dialects) that FrontMCP also answers.
- Claude Code sends none of these requests. To tell a Claude Code session, give the event [the `channel` option](https://frontmcp.dev/reference/sdk/event#the-channel-option).
- FrontMCP's own client picks a mode for you: `client.events.subscribe()` of [`connect()`](https://frontmcp.dev/reference/sdk/connect) uses webhook when it was given a receiver, else push when its transport can hold a stream, else poll.

Under MCP 2026-07-28, `events/poll`, `events/stream` and `events/subscribe` name their event in the `Mcp-Name` header too, as `tools/call` names its tool, and every result has `resultType: "complete"`.

<a id="eventspoll"></a>

### `events/poll`

Reads the occurrences of one event since a cursor. There's no subscribe step: each request names the event, its arguments and the cursor the last answer returned.

```json
{ "method": "events/poll", "params": { "name": "ticket.created", "arguments": {}, "cursor": null, "maxEvents": 50 } }
```

```json
{
  "events": [
    { "eventId": "evt_Zk3…", "name": "ticket.created", "timestamp": "2026-11-02T12:00:00.000Z", "data": { "ticketId": "T-4", "priority": "high" } }
  ],
  "cursor": "5f0c…a1.42",
  "truncated": false,
  "hasMore": false,
  "nextPollMs": 30000
}
```

| Parameter | Description |
| --- | --- |
| `name` | The event. |
| `arguments` | The subscription's arguments, checked against the event's `inputSchema`. |
| `cursor` | Where to read from. `null`, or none, means "from now": the answer has no events and the current position. |
| `maxEvents` | The most occurrences in one answer, within the server's [`events.poll.maxEvents`](https://frontmcp.dev/reference/sdk/events-options#eventspoll-eventspush-and-eventsbuffer) (100). |
| `maxAgeMs` | With a cursor, skips what's older, and sets `truncated: true` when it skipped something. |

| Result field | Description |
| --- | --- |
| `events` | The occurrences, oldest first: `{ eventId, name, timestamp, data }`. |
| `cursor` | Send it with the next poll. |
| `hasMore` | `true` when more are waiting: poll again at once, from `cursor`. |
| `nextPollMs` | How long to wait before the next poll otherwise: the server's `events.poll.nextPollMs` (30 seconds), or what the event's `check()` returned. |
| `truncated` | `true` when occurrences were skipped. It's never an error: the answer carries a cursor to continue from. |

An anonymous caller may poll on a server in `public` auth mode. Its `subscriber` has an empty `sub` and no roles, so an event with `authorities`, or an occurrence published with an `audience`, isn't for it. Every poll checks the caller again: the event's `authorities`, then the arguments, then `authorize()`. A caller who loses access is refused at its next poll.

<a id="events-that-are-published"></a>

#### Events that are published

An event without `check()` is read from a buffer of what [`publish()`](https://frontmcp.dev/reference/sdk/event#thiseventspublishevent-data-options) published: the last 10000 occurrences of each event, for 10 minutes ([`events.buffer`](https://frontmcp.dev/reference/sdk/events-options#eventspoll-eventspush-and-eventsbuffer)). Each poll applies, for its own caller and arguments, what a webhook delivery applies: the publish's `audience`, `match()` and `transform()`.

The buffer is in the memory of one process, and its cursor is `<process id>.<sequence>`:

- After a restart, or on another process, a cursor can't be placed: the answer has no events, a fresh cursor and `truncated: true`.
- A cursor older than what the buffer still holds is answered with what's left and `truncated: true`.

Behind a load balancer each process has its own buffer, so a poll can miss what another process published. Where that matters, give the event [`check()`](https://frontmcp.dev/reference/sdk/event#reading-an-upstream-that-can-replay), or use the webhook mode.

<a id="the-poll-subscription"></a>

#### The poll subscription

Poll has no goodbye. So that an event with `onSubscribe()` or `onUnsubscribe()` still hears about its pollers, the server keeps a lease per caller, event and arguments:

- `onSubscribe(args, subscription)` runs at the first poll, with `subscription.mode` `"poll"`.
- Each poll renews the lease. It lasts five poll intervals, and at least five minutes.
- `onUnsubscribe(args, subscription, "expired")` runs when no poll renewed it in time.
- A caller may hold [`subscriptions.maxPerPrincipal`](https://frontmcp.dev/reference/sdk/events-options#eventssubscriptions) leases (100). One more is answered `ResourceExhausted`, with `data.limit` `"pollLeases"`. The anonymous callers of a public server count as one caller.

Leases are in memory: after a restart, the next poll runs `onSubscribe()` again.

<a id="eventsstream"></a>

### `events/stream`

Opens one subscription that stays open. The server sends notifications on it until the client cancels or disconnects:

```json
{ "jsonrpc": "2.0", "id": 1, "method": "events/stream", "params": { "name": "ticket.created", "cursor": null } }
```

| Notification | When | `params` |
| --- | --- | --- |
| `notifications/events/active` | First, and again when a gap is found | `{ cursor, truncated }` |
| `notifications/events/event` | For each occurrence this reader may receive | The occurrence, with the `cursor` after it |
| `notifications/events/heartbeat` | Every [`events.push.heartbeatMs`](https://frontmcp.dev/reference/sdk/events-options#eventspoll-eventspush-and-eventsbuffer) (25 seconds) | `{ cursor }` |
| `notifications/events/error` | An event's `check()` failed. The stream stays open | `{ error }` |
| `notifications/events/terminated` | The server ends the subscription. The stream closes | `{ error }` |

Every notification has `params._meta["io.modelcontextprotocol/subscriptionId"]`, the `id` of the `events/stream` request.

- **Over Streamable HTTP under 2026-07-28**, the response of the `POST` is an SSE stream, and the client ends it by closing the connection.
- **On a session opened with `initialize`, and over stdio**, the notifications are sent on the session, and the client ends the stream with `notifications/cancelled` for the request's `id`.
- **A refusal** is a JSON-RPC error answer, and no stream opens. The checks are those of `events/poll`.
- **A `cursor`** replays what the [buffer](https://frontmcp.dev/reference/sdk/event-delivery#events-that-are-published) still holds after it, then goes on live. The `cursor` of an `event` or a `heartbeat` is the one to open the next stream, or to poll, from.
- **A slow reader** gets a gap, not a growing queue: past 1000 waiting notifications, they're replaced by one `active` with `truncated: true`.
- **An event with `check()`** is read by calling it when the stream opens, and then at its `nextPollMs`.
- `onSubscribe()` runs when the stream opens, with `subscription.mode` `"push"`, and `onUnsubscribe(…, "closed")` when it ends.
- A caller may hold [`subscriptions.maxPerPrincipal`](https://frontmcp.dev/reference/sdk/events-options#eventssubscriptions) open streams (100). One more is answered `ResourceExhausted`, with `data.limit` `"streams"`, and no stream opens.

A stream is held by one process. An occurrence published on another process reaches it only with [`events.store.redis`](https://frontmcp.dev/reference/sdk/events-options#eventsstore), on a server that also performs the webhook mode: its auth mode signs callers in, and `events.webhook.enabled` isn't `false`.

<a id="eventssubscribe"></a>

### `events/subscribe`

Creates a webhook subscription: from now on the server `POST`s each occurrence to `delivery.url`, signed with `delivery.secret`.

```json
{
  "method": "events/subscribe",
  "params": {
    "name": "ticket.created",
    "arguments": { "priority": "high" },
    "delivery": { "mode": "webhook", "url": "https://hooks.example.com/mcp/desk", "secret": "whsec_MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMw==" },
    "ttlMs": 3600000
  }
}
```

```json
{ "id": "sub_82ab5b510282bf98da64f4131367c461", "refreshBefore": "2026-11-02T13:00:00.000Z", "cursor": null, "truncated": false }
```

| Parameter | Description |
| --- | --- |
| `name`, `arguments` | The event and the subscription's arguments. |
| `delivery.url` | Where deliveries go. `https`, no credentials in the URL, and a host that isn't local, private or a cloud metadata address. |
| `delivery.secret` | What deliveries are signed with: `whsec_` followed by base64 that decodes to 24 to 64 bytes. The client makes it up. |
| `delivery.mode` | May be left out. `webhook` is the only mode this request takes. |
| `ttlMs` | How long the subscription should last. See [Lifetime](https://frontmcp.dev/reference/sdk/event-delivery#lifetime). |
| `cursor`, `maxAgeMs` | Used by an event with `check()`: see [events with `check()` over webhook](https://frontmcp.dev/reference/sdk/event-delivery#events-with-check-over-webhook). Ignored otherwise. |

The client keeps `id` and calls `events/subscribe` again before `refreshBefore`.

<a id="identity-and-refresh"></a>

#### Identity and refresh

A subscription is identified by its owner, its callback URL, the event's name and its arguments. The `id` is derived from those four, never taken from the request, so another caller, another URL or other arguments make another subscription. Arguments are compared after `inputSchema` parsed them, so another key order is the same subscription.

Subscribing again with the same identity refreshes the subscription instead of creating a second one. A refresh:

- grants the lifetime again, and answers the new `refreshBefore`;
- replaces the secret. When it differs, deliveries are signed with both for [`rotationGraceMs`](https://frontmcp.dev/reference/sdk/events-options#eventswebhook-and-eventswebhookdelivery) (5 minutes);
- replaces the stored owner (roles, permissions, scopes, claims, tenant) with the caller as it is now;
- makes a [suspended](https://frontmcp.dev/reference/sdk/event-delivery#suspension) subscription active again;
- adds `deliveryStatus` to the answer: `{ active, lastDeliveryAt, lastError, failedSince }`.

<a id="what-is-checked"></a>

#### What is checked

In this order. The first check that fails answers the request:

| Check | Error | `data` |
| --- | --- | --- |
| The event exists, and is offered on the caller's surface | `NotFound` | `{ kind: "event", name }` |
| The mode is `webhook`, and the event is offered by webhook | `Unsupported` | `{ feature: "deliveryMode", value, supported }` |
| The caller is signed in | `Forbidden` | `{ reason }` |
| The event's `authorities` allow the caller, with the arguments as the rule's input | `Forbidden` | `{ reason }` |
| The arguments match `inputSchema` | `-32602` (invalid params) | |
| The event's `authorize()` doesn't throw | `Forbidden` | `{ reason }` |
| The URL and the secret are well formed | `-32602` (invalid params) | |
| A new subscription keeps the caller within `subscriptions.maxPerPrincipal` | `ResourceExhausted` | `{ limit: "subscriptions", max }` |
| The callback's host got fewer than 10 verification attempts in the last minute | `ResourceExhausted` | `{ limit: "verifications", max }` |
| The callback [proves it accepts deliveries](https://frontmcp.dev/reference/sdk/event-delivery#callback-verification) | `CallbackEndpointError` | `{ reason }` |

On a server that performs no webhook mode, `events/subscribe` and `events/unsubscribe` don't exist: they answer `-32601` (Method not found).

<a id="callback-verification"></a>

#### Callback verification

Before a subscription is stored, its callback must prove it accepts MCP deliveries, so a caller can't point the server at someone else's URL. The first of these that holds is enough:

1. The URL is under one of [`events.webhook.allowedCallbacks`](https://frontmcp.dev/reference/sdk/events-options#eventswebhook-and-eventswebhookdelivery).
2. The same caller verified the same URL less than an hour ago (`verification.cacheTtlMs`).
3. The callback's origin serves `/.well-known/mcp-webhook-receiver.json` with `{ "receivers": ["/hooks/"] }`, and the callback's path starts with one of those prefixes. The server reads the document once per origin every 5 minutes.
4. The callback answers a challenge. The server `POST`s `{ "type": "verification", "challenge": "<nonce>" }`, signed with the subscription's secret like a delivery, with `webhook-id: msg_verification_…`. The callback must answer `2xx` with `{ "challenge": "<nonce>" }`.

A failed verification answers `CallbackEndpointError` with a category only, never what the callback said: `challenge_failed`, `timeout`, `connection_refused`, `tls_error`, `http_4xx` or `http_5xx`.

<a id="lifetime"></a>

#### Lifetime

| `ttlMs` in the request | Granted |
| --- | --- |
| Left out | [`subscriptions.defaultTtlMs`](https://frontmcp.dev/reference/sdk/events-options#eventssubscriptions) (1 hour), or the event's `ttl.defaultMs` |
| A number | That many milliseconds, kept between `minTtlMs` (1 minute) and `maxTtlMs` (24 hours) |
| `null` | No expiry (`refreshBefore: null`) when the server allows it, otherwise the maximum |

An event's `ttl.maxMs` lowers the maximum for that event. No expiry is granted only with `subscriptions.allowNoExpiry: true`, a [store](https://frontmcp.dev/reference/sdk/events-options#eventsstore) that outlives the process, and an event without `ttl.maxMs`.

A subscription whose lifetime is over gets no more deliveries, and its event's `onUnsubscribe(args, subscription, "expired")` runs once. A long-lived process looks for expired subscriptions every 60 seconds.

<a id="eventsunsubscribe"></a>

### `events/unsubscribe`

Takes the same `name`, `arguments` and `delivery.url`, and answers `{}`. It answers `{}` as well when no such subscription exists, so a client can repeat it. The event's `onUnsubscribe(…, "unsubscribed")` runs once.

<a id="webhook-deliveries"></a>

### Webhook deliveries

Each delivery is one `POST` to the subscription's callback. The body is the occurrence:

```json
{ "eventId": "evt_78z35TIDgPwoUw9xXMMC0wvo", "name": "ticket.created", "timestamp": "2026-11-02T12:00:00.129Z", "data": { "ticketId": "T-4", "priority": "high" } }
```

| Header | Value |
| --- | --- |
| `webhook-id` | The same on every attempt of one delivery, and for the same `eventId` on the same subscription. Deduplicate on it. |
| `webhook-timestamp` | The Unix time of this attempt, in seconds. |
| `webhook-signature` | `v1,<base64>`. Two of them, separated by a space, while a secret rotates. |
| `X-MCP-Subscription-Id` | The subscription's `id`. |
| `Content-Type` | `application/json` |

The signature follows [Standard Webhooks](https://www.standardwebhooks.com): an HMAC-SHA256, keyed with the secret's bytes (the base64 after `whsec_`, decoded), of `<webhook-id>.<webhook-timestamp>.<body>`. The body is serialized once, and the same bytes are signed and sent on every attempt, so verify over the bytes you received, before parsing them. [Receiving and verifying a delivery](https://frontmcp.dev/reference/sdk/event-delivery#receiving-and-verifying-a-delivery) has the code.

<a id="what-a-response-means"></a>

#### What a response means

| Response | What the server does |
| --- | --- |
| `2xx` | The delivery is done. |
| `410` or `413` | The delivery is dropped. It's never retried. |
| Any other status, a redirect, a timeout, no connection | The attempt failed. The delivery is retried. |

Delivery is at least once: a receiver can get the same delivery twice, after a lost `2xx`, and occurrences can arrive out of order. A tool the receiver calls in response should be safe to call twice.

<a id="retries"></a>

#### Retries

A delivery is attempted up to 5 times within 15 minutes of its first attempt. The wait before the next attempt starts at 1 second and doubles each time, up to 60 seconds, shortened by a random part of up to half. A delivery that used its attempts or its time is abandoned, and the server logs it:

```text
Delivery dlv_… of event "ticket.created" to subscription sub_… is abandoned after 5 attempt(s): http_5xx
```

Each attempt has 10 seconds, follows no redirect, and connects only to a public address over `https`. [`events.webhook.delivery`](https://frontmcp.dev/reference/sdk/events-options#eventswebhook-and-eventswebhookdelivery) changes each number.

<a id="suspension"></a>

#### Suspension

After 20 failed attempts in a row, a subscription is suspended: `publish()` leaves it out, and its pending deliveries wait. The server logs it:

```text
Subscription sub_… to event "ticket.created" is suspended after 20 failed deliveries in a row (http_5xx). Its next events/subscribe reactivates it.
```

The client's next refresh makes it active again, so a client that refreshes on time recovers by itself once its callback works. A delivery the callback acknowledges ends the count. A subscription without expiry that stayed suspended for more than 7 days is ended the next time its event is published.

<a id="control-envelopes"></a>

#### Control envelopes

A body with a top-level `type` isn't an occurrence. There are three, each signed like a delivery:

| Body | `webhook-id` | When |
| --- | --- | --- |
| `{ "type": "verification", "challenge": "…" }` | `msg_verification_…` | [Callback verification](https://frontmcp.dev/reference/sdk/event-delivery#callback-verification). Answer `2xx` with `{ "challenge": "…" }`. |
| `{ "type": "terminated", "error": { … } }` | `msg_terminated_…` | The server ended the subscription. The `error` says why. |
| `{ "type": "gap", "cursor": "…" }` | `msg_gap_…` | An event with `check()` reported that its upstream skipped occurrences. |

A `terminated` envelope for an owner who lost access:

```json
{ "type": "terminated", "error": { "code": -32024, "message": "Forbidden", "data": { "reason": "Access revoked" } } }
```

Subscriptions created in the [sketch dialect](https://frontmcp.dev/reference/sdk/event-delivery#dialects) get the `verification` envelope only.

<a id="events-with-check-over-webhook"></a>

#### Events with `check()` over webhook

A webhook subscription to an event with [`check()`](https://frontmcp.dev/reference/sdk/event#reading-an-upstream-that-can-replay) needs nobody to call `publish()`. One process of the server runs a loop that calls `check()` for each such subscription, every `events.poll.nextPollMs` or the `nextPollMs` the event returned, and queues each item as a delivery.

- `events/subscribe` with `cursor: null`, or none, starts from now. With a cursor, the first `check()` replays from it.
- Each delivered body carries a `cursor`, and so does the answer to a refresh. It's a position that is safe to keep: every item at or before it was acknowledged, dropped or abandoned. It's never ahead of a delivery the callback hasn't acknowledged, so it can be behind the item that carries it.
- The loop needs a long-lived process. On a serverless deployment, an edge runtime and in a browser, an event with `check()` isn't offered by webhook, and the server says so at startup.

<a id="access-over-a-subscriptions-life"></a>

### Access over a subscription's life

A caller is checked when it subscribes, and again while its subscription lives:

| Mode | When access is checked again | What a refusal does |
| --- | --- | --- |
| `poll` | On every poll | The poll is answered `Forbidden`. |
| `push` | At the first heartbeat after [`reauthorizeEveryMs`](https://frontmcp.dev/reference/sdk/events-options#eventssubscriptions) (5 minutes) | The stream ends with `notifications/events/terminated` and the reason `Access revoked`. |
| `webhook` | When a publish reaches a subscription whose last check is older than `reauthorizeEveryMs` | The subscription is removed, `onUnsubscribe(…, "terminated")` runs, and the callback gets a `terminated` envelope. |

The check is the event's `authorities` first, then its `authorize(args, subscriber)`, with the stored owner and arguments of the subscription. A webhook subscription's owner is the caller as it was at its last `events/subscribe`, which is one more reason to refresh.

A check that couldn't be made isn't a refusal. When the rule's evaluation throws, or `authorize()` throws an error that isn't a `PublicMcpError` (an upstream that's down, a timeout), the subscription is kept, that occurrence isn't delivered to it, and the next publish checks again. So throw a `PublicMcpError` from `authorize()` for "no", and let an upstream failure throw as it is.

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

### Errors

A refusal is a JSON-RPC error. Each has two codes, one per [dialect](https://frontmcp.dev/reference/sdk/event-delivery#dialects):

| Error | SEP-3415 | Sketch | `data` | Meaning |
| --- | --- | --- | --- | --- |
| `NotFound` | `-32023` | `-32011` | `{ kind: "event", name }` | No such event, or it isn't offered to this caller's surface. |
| `Forbidden` | `-32024` | `-32012` | `{ reason }` | The caller is anonymous where it may not be, or `authorities` or `authorize()` refused it. |
| `ResourceExhausted` | `-32025` | `-32013` | `{ limit, max }` | Too many webhook subscriptions (`limit: "subscriptions"`), poll leases (`"pollLeases"`) or open streams (`"streams"`) for this caller, or too many verification attempts for one host (`"verifications"`). |
| `Unsupported` | `-32026` | `-32014` | `{ feature: "deliveryMode", value, supported }` | The event isn't offered in the mode the request uses. `supported` lists the modes that work. |
| `CallbackEndpointError` | `-32027` | `-32015` | `{ reason }` | The callback failed [verification](https://frontmcp.dev/reference/sdk/event-delivery#callback-verification). `reason` is a category. |
| Invalid params | `-32602` | `-32602` | | The arguments don't match `inputSchema`, or the URL or the secret is malformed. |
| Method not found | `-32601` | `-32601` | | The server doesn't perform the mode this request belongs to, or serves no events. |
| Header mismatch | `-32020` | `-32020` | | Under 2026-07-28, the `Mcp-Name` header is missing or differs from `params.name`. |

The five named errors are classes of `@frontmcp/sdk`: `EventNotFoundError`, `EventForbiddenError`, `EventResourceExhaustedError`, `EventUnsupportedError` and `EventCallbackEndpointError`. [Error classes](https://frontmcp.dev/reference/sdk/error-classes) and [error codes](https://frontmcp.dev/reference/errors) list them with the SDK's other errors.

A server whose auth mode refuses anonymous requests, like `static`, answers them `401` at the HTTP level before any of this.

<a id="dialects"></a>

### Dialects

MCP Events exists in two revisions, and FrontMCP answers both:

| | SEP-3415 | Sketch |
| --- | --- | --- |
| What it is | The draft extension, `io.modelcontextprotocol/events` | The design sketch that came before it, which ChatGPT implements |
| Where the capability is | `capabilities.extensions["io.modelcontextprotocol/events"]` | `capabilities.events` |
| Error codes | `-32023` to `-32027` | `-32011` to `-32015` |
| `webhook-id` of a delivery | An id of the message, `msg_…` | The occurrence's `eventId` |
| `terminated` and `gap` envelopes | Sent | Not sent. After a gap, the next refresh answers `truncated: true` once |

A server advertises the capability in both places, on every transport. Which dialect a caller is answered in is decided per request by [`events.compat`](https://frontmcp.dev/reference/sdk/events-options#events):

| `compat` | Dialect |
| --- | --- |
| `"auto"` (the default) | The sketch for a caller FrontMCP [recognizes](https://frontmcp.dev/reference/ui/hosts#how-frontmcp-recognizes-the-client) as OpenAI, SEP-3415 for every other caller |
| `"sep-3415"` | SEP-3415 for every caller |
| `"sketch"` | The sketch for every caller |

A webhook subscription keeps the dialect it was created in: its deliveries use that dialect's `webhook-id` and envelopes.

> **Note: Run against ChatGPT**
>
> On 2026-11-11, ChatGPT was connected to a FrontMCP 1.12.0-rc.1 server in `local` auth mode, with the in-memory store, behind an HTTPS tunnel. It listed the server's events, subscribed to one with `events/subscribe` under MCP 2026-07-28, received three webhook deliveries a minute apart, and unsubscribed with `events/unsubscribe`. That run didn't cover a refresh at `refreshBefore`, a failed delivery and its retry, a subscription with arguments, or a restart with a store that outlives the process.

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

#### Caveats

- **Deduplicate and tolerate reordering.** Webhook delivery is at least once, and a client that reconnects a stream or polls from an older cursor reads occurrences again. Deduplicate on `eventId` (or on `webhook-id`).
- **A gap isn't an error.** `truncated: true` means occurrences were skipped. When a gap matters, read the current state with a tool, then continue from the cursor.
- **Pending deliveries are kept with the subscriptions.** In memory, they end with the process. With a [store](https://frontmcp.dev/reference/sdk/events-options#eventsstore) they survive a restart, and another process takes over the deliveries of one that died.
- **Each request runs a flow** that hooks can attach to: `events:list`, `events:poll`, `events:stream`, `events:subscribe`, `events:unsubscribe`, and `events:publish` and `events:deliver` on the server's side. See [Flows and stages](https://frontmcp.dev/reference/server/flows) and [Hook decorators](https://frontmcp.dev/reference/sdk/hooks).
- **In the Playground**, the server runs in your browser, where nothing can call it and it calls nothing. Polling, streaming and subscribing run on this page. A delivery to a callback doesn't, so that part of the page shows code that was checked in Node.

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

## Usage

The Playgrounds below build each request by hand, so the headers and bodies a client sends are on screen. `client.ts` creates the server with [`createFetchHandler()`](https://frontmcp.dev/reference/sdk/create-fetch-handler) and sends it web `Request`s, as an MCP 2026-07-28 client would over HTTP.

<a id="polling-for-events"></a>

### Polling for events

Three requests make a poll loop: one without a cursor to find out where "now" is, then one per interval from the cursor of the last answer.

Initial call configuration:

```js
{ tool: "create_ticket", arguments: { priority: "high" } }
```

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

test("a poll without a cursor answers no events, and where now is", async () => {
  const { result } = await rpc("events/poll", { name: "ticket.created", cursor: null });
  expect(result).toMatchObject({ events: [], cursor: expect.any(String), truncated: false, hasMore: false, nextPollMs: 30000 });
});

test("the next poll answers what was published since", async () => {
  const start = (await rpc("events/poll", { name: "ticket.created", cursor: null })).result.cursor;
  await rpc("tools/call", { name: "create_ticket", arguments: { priority: "high" } });

  const { result } = await rpc("events/poll", { name: "ticket.created", cursor: start });
  expect(result.events).toEqual([
    { eventId: expect.stringMatching(/^evt_/), name: "ticket.created", timestamp: expect.any(String), data: { ticketId: expect.any(String), priority: "high" } },
  ]);

  const again = await rpc("events/poll", { name: "ticket.created", cursor: result.cursor });
  expect(again.result.events).toEqual([]);
});

test("maxEvents caps one answer, and hasMore says to poll again at once", async () => {
  const start = (await rpc("events/poll", { name: "ticket.created", cursor: null })).result.cursor;
  for (const priority of ["high", "normal", "high"]) await rpc("tools/call", { name: "create_ticket", arguments: { priority } });

  const first = (await rpc("events/poll", { name: "ticket.created", cursor: start, maxEvents: 2 })).result;
  expect(first.events).toHaveLength(2);
  expect(first.hasMore).toBe(true);

  const rest = (await rpc("events/poll", { name: "ticket.created", cursor: first.cursor })).result;
  expect(rest.events).toHaveLength(1);
  expect(rest.hasMore).toBe(false);
});

test("a cursor the server can't place is a gap, not an error", async () => {
  const { result } = await rpc("events/poll", { name: "ticket.created", cursor: "another-process.12" });
  expect(result).toMatchObject({ events: [], truncated: true });
  expect(result.cursor).not.toBe("another-process.12");
});

test("the event's name goes in the Mcp-Name header too", async () => {
  const { error } = await rpc("events/poll", { name: "ticket.created", cursor: null }, { withoutNameHeader: true });
  expect(error).toEqual({ code: -32020, message: "Header mismatch: the mcp-name header is required for events/poll" });
});
```

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

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

/** Sends one request as an MCP 2026-07-28 client would over HTTP. */
export async function rpc(method: string, params: Record<string, unknown> = {}, options: { withoutNameHeader?: boolean } = {}) {
  server ??= FrontMcpInstance.createFetchHandler(config);
  const named = typeof params.name === "string" && !options.withoutNameHeader;
  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,
        ...(named ? { "mcp-name": String(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, Tool, ToolContext, event, z } from "@frontmcp/sdk";

export const ticketCreated = event({
  name: "ticket.created",
  payloadSchema: { ticketId: z.string(), priority: z.enum(["high", "normal"]) },
});

let nextId = 4;

@Tool({ name: "create_ticket", description: "Open a support ticket", inputSchema: { priority: z.enum(["high", "normal"]) } })
class CreateTicket extends ToolContext {
  async execute({ priority }: { priority: "high" | "normal" }) {
    return this.events.publish(ticketCreated, { ticketId: `T-${nextId++}`, priority });
  }
}

@App({ id: "help-desk", name: "Help Desk", tools: [CreateTicket], events: [ticketCreated] })
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] };
```

<a id="holding-a-stream-open"></a>

### Holding a stream open

`events/stream` answers with an SSE stream that stays open. The first message is `active`, with the position the stream starts from. Each occurrence follows as it's published:

Initial call configuration:

```js
{ tool: "create_ticket", arguments: { priority: "high" } }
```

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

const subscriptionMeta = { "io.modelcontextprotocol/subscriptionId": 1 };

test("a stream says it's active, then sends each occurrence as it's published", async () => {
  const stream = await openStream({ name: "ticket.created" });
  expect(await stream.next()).toEqual({
    jsonrpc: "2.0",
    method: "notifications/events/active",
    params: { cursor: expect.any(String), truncated: false, _meta: subscriptionMeta },
  });

  await rpc("tools/call", { name: "create_ticket", arguments: { priority: "high" } });
  expect(await stream.next()).toEqual({
    jsonrpc: "2.0",
    method: "notifications/events/event",
    params: {
      eventId: expect.stringMatching(/^evt_/),
      name: "ticket.created",
      timestamp: expect.any(String),
      data: { ticketId: expect.any(String), priority: "high" },
      cursor: expect.any(String),
      _meta: subscriptionMeta,
    },
  });
  await stream.close();
});

test("a cursor replays what was published before the stream opened", async () => {
  const before = (await rpc("events/poll", { name: "ticket.created", cursor: null })).result.cursor;
  await rpc("tools/call", { name: "create_ticket", arguments: { priority: "normal" } });

  const stream = await openStream({ name: "ticket.created", cursor: before });
  const active = await stream.next();
  const replayed = await stream.next();
  expect(active.method).toBe("notifications/events/active");
  expect(replayed).toMatchObject({ method: "notifications/events/event", params: { data: { priority: "normal" } } });
  await stream.close();
});

test("a quiet stream sends a heartbeat with its cursor", async () => {
  const stream = await openStream({ name: "ticket.created" });
  const active = await stream.next();
  expect(await stream.next()).toEqual({
    jsonrpc: "2.0",
    method: "notifications/events/heartbeat",
    params: { cursor: active.params.cursor, _meta: subscriptionMeta },
  });
  await stream.close();
});

test("a refusal is an ordinary error answer, and no stream opens", async () => {
  const refused = await rpc("events/stream", { name: "ticket.closed" });
  expect(refused.error).toMatchObject({ code: -32023, data: { kind: "event", name: "ticket.closed" } });
});
```

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

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

async function send(method: string, params: Record<string, unknown>) {
  server ??= FrontMcpInstance.createFetchHandler(config);
  return (await server)(
    new Request("https://desk.example.com/", {
      method: "POST",
      headers: {
        "content-type": "application/json",
        accept: "application/json, text/event-stream",
        "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" } },
      }),
    }),
  );
}

export async function rpc(method: string, params: Record<string, unknown> = {}) {
  return (await send(method, params)).json();
}

/** Opens events/stream and reads its SSE messages one at a time. */
export async function openStream(params: Record<string, unknown>) {
  const response = await send("events/stream", params);
  const reader = response.body!.getReader();
  const decoder = new TextDecoder();
  let buffered = "";
  return {
    async next() {
      while (!buffered.includes("\n\n")) {
        const { value, done } = await reader.read();
        if (done) throw new Error("The stream ended");
        buffered += decoder.decode(value, { stream: true });
      }
      const end = buffered.indexOf("\n\n");
      const message = buffered.slice(0, end);
      buffered = buffered.slice(end + 2);
      const data = message.split("\n").find((line) => line.startsWith("data:")) ?? "data:null";
      return JSON.parse(data.slice("data:".length));
    },
    // Closing the connection is how a 2026-07-28 client ends the subscription.
    close: () => reader.cancel(),
  };
}
```

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

export const ticketCreated = event({
  name: "ticket.created",
  payloadSchema: { ticketId: z.string(), priority: z.enum(["high", "normal"]) },
});

let nextId = 4;

@Tool({ name: "create_ticket", description: "Open a support ticket", inputSchema: { priority: z.enum(["high", "normal"]) } })
class CreateTicket extends ToolContext {
  async execute({ priority }: { priority: "high" | "normal" }) {
    return this.events.publish(ticketCreated, { ticketId: `T-${nextId++}`, priority });
  }
}

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

export const config = {
  info: { name: "help-desk", version: "1.0.0" },
  apps: [HelpDeskApp],
  // A short heartbeat, so the test doesn't wait 25 seconds for one.
  events: { push: { heartbeatMs: 1000 } },
};
```

<a id="subscribing-with-a-webhook"></a>

### Subscribing with a webhook

A webhook subscription needs a server that knows its callers. This one checks static keys, and accepts callbacks under one prefix without a verification request, so the example makes no outbound call. Nothing is published while a subscription exists, for the same reason:

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

const NOUR = "agent-nour-key";
const SAM = "agent-sam-key";
const url = "https://hooks.example.com/mcp/desk";
// The client makes the secret up: whsec_ and 24 to 64 random bytes, in base64.
const secret = `whsec_${btoa("0123456789012345678901234567890123")}`;
const subscription = { name: "ticket.created", arguments: { priority: "high" }, delivery: { mode: "webhook", url, secret } };

test("a signed-in caller is offered the webhook mode", async () => {
  const { result } = await rpc("events/list", {}, NOUR);
  expect(result.events[0].delivery).toEqual(["poll", "push", "webhook"]);
});

test("subscribing answers an id and when to refresh", async () => {
  const { result } = await rpc("events/subscribe", subscription, NOUR);
  expect(result).toMatchObject({ id: expect.stringMatching(/^sub_[0-9a-f]{32}$/), cursor: null, truncated: false });
  const lifetimeMs = Date.parse(result.refreshBefore) - Date.now();
  expect(Math.round(lifetimeMs / 60_000)).toBe(60);
  await rpc("events/unsubscribe", subscription, NOUR);
});

test("subscribing again refreshes the same subscription, and reports its deliveries", async () => {
  const first = (await rpc("events/subscribe", subscription, NOUR)).result;
  const refreshed = (await rpc("events/subscribe", { ...subscription, ttlMs: 120_000 }, NOUR)).result;
  expect(refreshed.id).toBe(first.id);
  expect(refreshed.deliveryStatus).toEqual({ active: true, lastDeliveryAt: null, lastError: null, failedSince: null });
  expect(Math.round((Date.parse(refreshed.refreshBefore) - Date.now()) / 60_000)).toBe(2);
  await rpc("events/unsubscribe", subscription, NOUR);
});

test("another caller, or other arguments, is another subscription", async () => {
  const nour = (await rpc("events/subscribe", subscription, NOUR)).result;
  const sam = (await rpc("events/subscribe", subscription, SAM)).result;
  const normal = (await rpc("events/subscribe", { ...subscription, arguments: { priority: "normal" } }, NOUR)).result;
  expect(new Set([nour.id, sam.id, normal.id]).size).toBe(3);

  await rpc("events/unsubscribe", subscription, NOUR);
  await rpc("events/unsubscribe", subscription, SAM);
  await rpc("events/unsubscribe", { ...subscription, arguments: { priority: "normal" } }, NOUR);
});

test("unsubscribing answers {}, also when there's nothing to remove", async () => {
  await rpc("events/subscribe", subscription, NOUR);
  const once = await rpc("events/unsubscribe", subscription, NOUR);
  const twice = await rpc("events/unsubscribe", subscription, NOUR);
  expect(once.result).toEqual({ resultType: "complete", _meta: expect.any(Object) });
  expect(twice.result).toEqual(once.result);
});

test("a callback that isn't https, or a secret in another format, is refused", async () => {
  const http = await rpc("events/subscribe", { ...subscription, delivery: { url: "http://hooks.example.com/mcp/desk", secret } }, NOUR);
  expect(http.error).toMatchObject({ code: -32602, message: "Invalid delivery.url: it must use https" });

  const local = await rpc("events/subscribe", { ...subscription, delivery: { url: "https://127.0.0.1/mcp/desk", secret } }, NOUR);
  expect(local.error).toMatchObject({ code: -32602, message: "Invalid delivery.url: its host is local, private or a metadata service" });

  const weak = await rpc("events/subscribe", { ...subscription, delivery: { url, secret: "hunter2" } }, NOUR);
  expect(weak.error).toMatchObject({
    code: -32602,
    message: 'Invalid delivery.secret: expected "whsec_" followed by base64 that decodes to 24 to 64 bytes',
  });
});

test("a request without a key never reaches events", async () => {
  expect(await rpc("events/subscribe", subscription)).toEqual({ error: "Unauthorized" });
});
```

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

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

/** Sends one request as an MCP 2026-07-28 client would over HTTP, with this key. */
export async function rpc(method: string, params: Record<string, unknown> = {}, key?: string) {
  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 } : {}),
        ...(key ? { authorization: `Bearer ${key}` } : {}),
      },
      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",
  inputSchema: { priority: z.enum(["high", "normal"]).optional() },
  payloadSchema: { ticketId: z.string(), priority: z.enum(["high", "normal"]) },
});

@App({ id: "help-desk", name: "Help Desk", events: [ticketCreated] })
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],
  // Two agents, each with a key: webhook delivery needs callers the server can tell apart.
  auth: { mode: "static" as const, tokens: ["agent-nour-key", "agent-sam-key"] },
  events: { webhook: { allowedCallbacks: ["https://hooks.example.com/mcp/"] } },
};
```

The Playground's own client sends no key, so its server is built from the app alone, in public auth mode: the Capabilities tab is that server. The tests build the one in `config`.

<a id="receiving-and-verifying-a-delivery"></a>

### Receiving and verifying a delivery

The other half of a webhook subscription is the HTTP endpoint the server calls. `createEventWebhookReceiver()` is that endpoint's logic, without a web framework: it checks the signature and its freshness, answers verification challenges, ignores a `webhook-id` it already acknowledged, and hands each occurrence to `onEvent()`. Give it every request with its exact body:

```ts receiver.ts
import { createServer } from "node:http";
import { createEventWebhookReceiver } from "@frontmcp/sdk";

const receiver = createEventWebhookReceiver({
  // The secret this client sent in events/subscribe.
  secrets: [process.env.MCP_WEBHOOK_SECRET!],
  async onEvent(occurrence, { subscriptionId, webhookId }) {
    console.log(`${occurrence.name} ${occurrence.eventId} for ${subscriptionId}`, occurrence.data);
  },
  onTerminated(error) {
    console.warn(`The server ended the subscription: ${error.message}`);
  },
});

createServer(async (request, response) => {
  const chunks: Buffer[] = [];
  for await (const chunk of request) chunks.push(chunk as Buffer);
  // The signature covers the body's bytes: hand over the text as it arrived, not parsed JSON.
  const rawBody = Buffer.concat(chunks).toString("utf8");
  const { status, body } = await receiver.handle({ headers: request.headers, rawBody });
  response.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body ?? {}));
}).listen(8787);
```

| The receiver answers | When |
| --- | --- |
| `200` with `{ challenge }` | A `verification` envelope. |
| `200` | An occurrence or an envelope, once its callback settled, and a `webhook-id` it already acknowledged. |
| `401` | The signature is missing, doesn't verify, or its `webhook-timestamp` is more than 5 minutes off. |
| `500` | The callback threw. The server retries the delivery. |
| `503` | It holds no secret for that subscription. The server retries. |
| `400` | The body is neither an occurrence nor an envelope. |

To verify a delivery without the SDK, compute the signature over the three parts, joined by dots:

```ts verify.ts
import { createHmac, timingSafeEqual } from "node:crypto";

export function verifies(secret: string, headers: Record<string, string | string[] | undefined>, rawBody: string) {
  const key = Buffer.from(secret.slice("whsec_".length), "base64");
  const signed = `${headers["webhook-id"]}.${headers["webhook-timestamp"]}.${rawBody}`;
  const expected = Buffer.from(createHmac("sha256", key).update(signed).digest("base64"));
  // While a secret rotates, the header holds two signatures separated by a space.
  return String(headers["webhook-signature"])
    .split(" ")
    .some((candidate) => {
      const [version, signature] = candidate.split(",");
      const given = Buffer.from(signature ?? "");
      return version === "v1" && given.length === expected.length && timingSafeEqual(given, expected);
    });
}
```

Also refuse a `webhook-timestamp` far from your clock, so a recorded delivery can't be sent again later.

`@frontmcp/utils` has that check, with the timestamp's too, as `verifyWebhookSignature()`. It takes the three headers as they arrived and the body's text, and answers `"valid"`, `"missing"`, `"stale"` or `"mismatch"`:

```ts verify-with-utils.ts
import { signingKeyOf, verifyWebhookSignature } from "@frontmcp/utils";

export function verifies(secret: string, headers: Record<string, string | undefined>, rawBody: string) {
  const signed = { id: headers["webhook-id"], timestamp: headers["webhook-timestamp"], signature: headers["webhook-signature"], body: rawBody };
  return verifyWebhookSignature(signed, [signingKeyOf(secret)]) === "valid";
}
```

- `signingKeyOf(secret)` is the key of a `whsec_` secret. Pass several keys to accept any of them; a header with two signatures verifies when one matches.
- `"stale"` means a `webhook-timestamp` more than `WEBHOOK_SIGNATURE_TOLERANCE_SECONDS` (300) from the third argument, the time in milliseconds, `Date.now()` by default.
- `generateStandardWebhookSecret()` makes a secret for `events/subscribe`, `whsec_` and the base64 of 32 random bytes, and `isStandardWebhookSecret()` checks one.
- `webhookSignatureHeaders({ id, timestamp, body }, keys)` signs a message as the server does, `generateWebhookMessageId(kind?)` makes a `msg_…` id, and `WEBHOOK_ID_HEADER`, `WEBHOOK_TIMESTAMP_HEADER` and `WEBHOOK_SIGNATURE_HEADER` are the header names.

> **Note**
>
> Nothing can call a server that runs in a browser tab, so these files aren't a running example. The helpers of `@frontmcp/utils` were run in Node on 1.12.1, for each of the four answers and a header with two signatures. The first two files were run in Node against FrontMCP 1.12.0-rc.1: a server delivering to this receiver over HTTP, with the challenge answered, the occurrence handed to `onEvent()`, and `verifies()` true for the verification request and for the delivery. In tests, `@frontmcp/testing` has a receiver that listens on a local port: see [the testing reference](https://frontmcp.dev/reference/testing).

<a id="reading-a-refusal"></a>

### Reading a refusal

Every refusal names what went wrong in its code and says what to do in `data`. A caller that FrontMCP recognizes as ChatGPT gets the same errors under the sketch's codes:

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

test("NotFound: no such event", async () => {
  const { error } = await rpc("events/poll", { name: "ticket.closed" });
  expect(error).toMatchObject({
    code: -32023,
    message: 'Event "ticket.closed" is not served. Call events/list for the events this server offers.',
    data: { kind: "event", name: "ticket.closed" },
  });
});

test("Unsupported: the event isn't offered in this mode", async () => {
  const { error } = await rpc("events/poll", { name: "ticket.streamed" });
  expect(error).toMatchObject({
    code: -32026,
    message: '"poll" is not a supported deliveryMode. Supported: push.',
    data: { feature: "deliveryMode", value: "poll", supported: ["push"] },
  });
});

test("Forbidden: authorize() refused, and its public message is the reason", async () => {
  const { error } = await rpc("events/poll", { name: "ticket.created", arguments: { queue: "vip" } });
  expect(error).toMatchObject({
    code: -32024,
    message: 'Subscribing to "ticket.created" is not allowed: The vip queue is for supervisors.',
    data: { reason: "The vip queue is for supervisors." },
  });
});

test("Forbidden: any other error from authorize() says nothing of itself", async () => {
  const { error } = await rpc("events/poll", { name: "ticket.created", arguments: { queue: "broken" } });
  expect(error.data.reason).toBe("the event refused it");
});

test("invalid params: the arguments don't match inputSchema", async () => {
  const { error } = await rpc("events/poll", { name: "ticket.created", arguments: { queue: 7 } });
  expect(error.code).toBe(-32602);
  expect(error.message).toContain("Invalid subscription arguments");
});

test("ResourceExhausted: one caller holds too many poll leases", async () => {
  await rpc("events/poll", { name: "ticket.watched", arguments: { queue: "billing" } });
  const { error } = await rpc("events/poll", { name: "ticket.watched", arguments: { queue: "login" } });
  expect(error).toMatchObject({ code: -32025, data: { limit: "pollLeases", max: 1 } });
});

test("ResourceExhausted: one caller holds too many open streams", async () => {
  const open = await openStream({ name: "ticket.streamed" });
  const { error } = await rpc("events/stream", { name: "ticket.streamed" });
  expect(error).toMatchObject({
    code: -32025,
    message: "The limit of 1 open event streams per caller is reached. Close one, then retry.",
    data: { limit: "streams", max: 1 },
  });
  await open.cancel();
});

test("Method not found: this server performs no webhook mode", async () => {
  const { error } = await rpc("events/subscribe", { name: "ticket.created", delivery: { url: "https://hooks.example.com/mcp", secret: "whsec_x" } });
  expect(error).toEqual({ code: -32601, message: "Method not found: events/subscribe" });
});

test("a caller recognized as ChatGPT gets the sketch's codes", async () => {
  const asChatGpt = { clientName: "ChatGPT" };
  expect((await rpc("events/poll", { name: "ticket.closed" }, asChatGpt)).error.code).toBe(-32011);
  expect((await rpc("events/poll", { name: "ticket.created", arguments: { queue: "vip" } }, asChatGpt)).error.code).toBe(-32012);
  expect((await rpc("events/poll", { name: "ticket.streamed" }, asChatGpt)).error.code).toBe(-32014);
});
```

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

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

export const ticketCreated = event({
  name: "ticket.created",
  inputSchema: { queue: z.string().optional() },
  payloadSchema,
  authorize(args) {
    if (args.queue === "vip") throw new PublicMcpError("The vip queue is for supervisors.");
    if (args.queue === "broken") throw new Error("ECONNREFUSED 10.0.0.7:5432");
  },
});

export const ticketStreamed = event({ name: "ticket.streamed", payloadSchema, delivery: ["push"] });

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

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

export const config = {
  info: { name: "help-desk", version: "1.0.0" },
  apps: [HelpDeskApp],
  events: { subscriptions: { maxPerPrincipal: 1 } },
};
```

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

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

/** Sends one request as an MCP 2026-07-28 client would over HTTP, under the client name given. */
async function send(method: string, params: Record<string, unknown>, options: { clientName?: string }) {
  server ??= FrontMcpInstance.createFetchHandler(config);
  return (await server)(
    new Request("https://desk.example.com/", {
      method: "POST",
      headers: {
        "content-type": "application/json",
        accept: "application/json, text/event-stream",
        "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: options.clientName ?? "desk-agent", version: "1.0.0" },
          },
        },
      }),
    }),
  );
}

export async function rpc(method: string, params: Record<string, unknown> = {}, options: { clientName?: string } = {}) {
  return (await send(method, params, options)).json();
}

/** Opens events/stream and keeps it open until its reader is cancelled. */
export async function openStream(params: Record<string, unknown>) {
  return (await send("events/stream", params, {})).body!.getReader();
}
```

A message a client reads never carries what a non-public error said: `ECONNREFUSED 10.0.0.7:5432` stays on the server.

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

## Troubleshooting

<a id="header-mismatch-the-mcp-name-header-is-required-for-eventspoll"></a>

### `Header mismatch: the mcp-name header is required for events/poll`

Under MCP 2026-07-28, a request that names its target in `params.name` repeats it in the `Mcp-Name` header, and FrontMCP refuses one that doesn't with `-32020`. `events/poll`, `events/stream` and `events/subscribe` are such requests. Send `Mcp-Name: <the event's name>`, as [polling for events](https://frontmcp.dev/reference/sdk/event-delivery#polling-for-events) does. A session opened with `initialize` under an earlier revision needs no such header.

<a id="method-not-found-eventssubscribe"></a>

### `Method not found: events/subscribe`

The server performs no webhook mode, so the request doesn't exist there. The usual cause is `public` auth mode: a subscription belongs to a caller, and a public server has none. The server says so at startup: `Webhook event delivery is off: the server runs in public auth mode, so a subscription would have no owner.` Configure an [auth mode](https://frontmcp.dev/reference/auth/modes) that signs callers in, or use `events/poll` or `events/stream`. The same answer for `events/poll` or `events/stream` means that mode is turned off, or, for a stream, that the deployment is serverless.

<a id="eventspoll-answers-truncated-true"></a>

### `events/poll` answers `truncated: true`

The server restarted, another process answered, or the cursor is older than the 10 minutes the buffer holds. Nothing failed: continue from the cursor of the answer, and read the current state with a tool if the gap matters. To make cursors survive a restart, give the event [`check()`](https://frontmcp.dev/reference/sdk/event#reading-an-upstream-that-can-replay).

<a id="a-poll-or-a-stream-misses-events-behind-a-load-balancer"></a>

### A poll or a stream misses events behind a load balancer

Each process buffers what it published, and holds its own streams. For polling, give the event `check()`. For streams, set [`events.store.redis`](https://frontmcp.dev/reference/sdk/events-options#eventsstore) on a server that performs the webhook mode (its auth signs callers in, and `events.webhook.enabled` isn't `false`), so each process relays what it publishes to the others. Or use the webhook mode, whose subscriptions every process shares through the store.

<a id="invalid-deliveryurl-it-must-use-https"></a>

### `Invalid delivery.url: it must use https`

The callback is `http:`. Deliveries go to `https` URLs on public addresses only. `Invalid delivery.url: its host is local, private or a metadata service` is the same protection for the host. For a receiver on `localhost` in a test, the server sets [`events.webhook.unsafeAllowLocalCallbacks`](https://frontmcp.dev/reference/sdk/events-options#eventswebhook-and-eventswebhookdelivery).

<a id="invalid-deliverysecret-expected-whsec_-followed-by-base64"></a>

### `Invalid delivery.secret: expected "whsec_" followed by base64…`

The secret must be `whsec_` and base64 that decodes to 24 to 64 bytes. Generate 32 random bytes and encode them: `"whsec_" + randomBytes(32).toString("base64")`.

<a id="the-callback-endpoint-could-not-be-verified-challenge_failed"></a>

### `The callback endpoint could not be verified (challenge_failed)`

`events/subscribe` answered `CallbackEndpointError`. The callback got the verification request and didn't answer `2xx` with the same `challenge`. Echo it, as [the receiver](https://frontmcp.dev/reference/sdk/event-delivery#receiving-and-verifying-a-delivery) does. Other reasons name where it failed: `connection_refused` (nothing listens there, or the address isn't public), `timeout`, `tls_error`, `http_4xx`, `http_5xx`.

<a id="the-signature-doesnt-verify-at-the-receiver"></a>

### The signature doesn't verify at the receiver

Almost always the body: a framework parsed the JSON and the receiver signed its own re-serialization. Verify over the raw bytes. Otherwise check the secret (the one sent in the last `events/subscribe`, base64-decoded after `whsec_`), and that the three parts are joined as `<webhook-id>.<webhook-timestamp>.<body>`.

<a id="a-receiver-gets-the-same-event-twice"></a>

### A receiver gets the same event twice

Delivery is at least once: the server retries an attempt whose `2xx` it didn't see. Keep the `webhook-id`s you handled and skip a repeat. `createEventWebhookReceiver()` remembers the last 10000 per subscription.

<a id="delivery--is-abandoned-after-5-attempts-in-the-servers-log"></a>

### `Delivery … is abandoned after 5 attempt(s)` in the server's log

The callback failed every attempt within the retry time. The category at the end of the line says how. Fix the callback: that occurrence isn't sent again.

<a id="subscription--is-suspended-after-20-failed-deliveries-in-a-row"></a>

### `Subscription … is suspended after 20 failed deliveries in a row`

The server stopped delivering to a callback that kept failing. Fix the callback, then have the client call `events/subscribe` again, which reactivates it. A client that refreshes before `refreshBefore` does this by itself.

<a id="the-limit-of--per-caller-is-reached"></a>

### `The limit of … per caller is reached`

`ResourceExhausted`. One caller holds [`subscriptions.maxPerPrincipal`](https://frontmcp.dev/reference/sdk/events-options#eventssubscriptions) of one kind, each kind counted by itself, and `data.limit` and the message say which:

| `data.limit` | Message | To free a place |
| --- | --- | --- |
| `"subscriptions"` | `The limit of 100 webhook subscriptions per caller is reached. Remove one with events/unsubscribe, then retry.` | `events/unsubscribe` one. |
| `"pollLeases"` | `The limit of 100 poll leases per caller is reached. A lease ends when its subscription is not polled for its lease time: stop polling one, then retry.` | Stop polling one. A [poll lease](https://frontmcp.dev/reference/sdk/event-delivery#the-poll-subscription) has no request that ends it: it lapses once nothing polled it for five poll intervals, and at least five minutes. |
| `"streams"` | `The limit of 100 open event streams per caller is reached. Close one, then retry.` | Close one. |

Or raise the limit. On a public server every anonymous caller counts as the same caller. Changed in 1.12.1: before, all three had `limit: "subscriptions"` and the webhook message, which names `events/unsubscribe` though it frees no lease or stream.
