Event subscriptions and delivery
A client receives a server's events 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.
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 } }
Reference
Delivery modes
| Mode | Request | How occurrences arrive | Use it when |
|---|---|---|---|
poll | events/poll | 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 | 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 | As signed HTTP POSTs 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
deliveryinevents/listnames the modes a client may use for it. A request in another mode is answeredUnsupported. - Which modes a server performs depends on its auth mode and where it runs: see Events options. In short,
pollandpushwork everywhere but serverless (pollonly), andwebhookneeds an auth mode that signs callers in, since a subscription belongs to a caller. - ChatGPT implements the webhook mode, in an older dialect that FrontMCP also answers.
- Claude Code sends none of these requests. To tell a Claude Code session, give the event the
channeloption. - FrontMCP's own client picks a mode for you:
client.events.subscribe()ofconnect()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".
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.
{ "method": "events/poll", "params": { "name": "ticket.created", "arguments": {}, "cursor": null, "maxEvents": 50 } }
{
"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 (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.
Events that are published
An event without check() is read from a buffer of what publish() published: the last 10000 occurrences of each event, for 10 minutes (events.buffer). 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(), or use the webhook mode.
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, withsubscription.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.maxPerPrincipalleases (100). One more is answeredResourceExhausted, withdata.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.
events/stream
Opens one subscription that stays open. The server sends notifications on it until the client cancels or disconnects:
{ "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 (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
POSTis 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 withnotifications/cancelledfor the request'sid. - A refusal is a JSON-RPC error answer, and no stream opens. The checks are those of
events/poll. - A
cursorreplays what the buffer still holds after it, then goes on live. Thecursorof aneventor aheartbeatis 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
activewithtruncated: true. - An event with
check()is read by calling it when the stream opens, and then at itsnextPollMs. onSubscribe()runs when the stream opens, withsubscription.mode"push", andonUnsubscribe(…, "closed")when it ends.- A caller may hold
subscriptions.maxPerPrincipalopen streams (100). One more is answeredResourceExhausted, withdata.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, on a server that also performs the webhook mode: its auth mode signs callers in, and events.webhook.enabled isn't false.
events/subscribe
Creates a webhook subscription: from now on the server POSTs each occurrence to delivery.url, signed with delivery.secret.
{
"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
}
}
{ "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. |
cursor, maxAgeMs | Used by an event with check(): see events with check() over webhook. Ignored otherwise. |
The client keeps id and calls events/subscribe again before refreshBefore.
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(5 minutes); - replaces the stored owner (roles, permissions, scopes, claims, tenant) with the caller as it is now;
- makes a suspended subscription active again;
- adds
deliveryStatusto the answer:{ active, lastDeliveryAt, lastError, failedSince }.
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 | CallbackEndpointError | { reason } |
On a server that performs no webhook mode, events/subscribe and events/unsubscribe don't exist: they answer -32601 (Method not found).
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:
- The URL is under one of
events.webhook.allowedCallbacks. - The same caller verified the same URL less than an hour ago (
verification.cacheTtlMs). - The callback's origin serves
/.well-known/mcp-webhook-receiver.jsonwith{ "receivers": ["/hooks/"] }, and the callback's path starts with one of those prefixes. The server reads the document once per origin every 5 minutes. - The callback answers a challenge. The server
POSTs{ "type": "verification", "challenge": "<nonce>" }, signed with the subscription's secret like a delivery, withwebhook-id: msg_verification_…. The callback must answer2xxwith{ "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.
Lifetime
ttlMs in the request | Granted |
|---|---|
| Left out | subscriptions.defaultTtlMs (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 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.
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.
Webhook deliveries
Each delivery is one POST to the subscription's callback. The body is the occurrence:
{ "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: 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 has the code.
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.
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:
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 changes each number.
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:
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.
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. 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:
{ "type": "terminated", "error": { "code": -32024, "message": "Forbidden", "data": { "reason": "Access revoked" } } }
Subscriptions created in the sketch dialect get the verification envelope only.
Events with check() over webhook
A webhook subscription to an event with check() 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/subscribewithcursor: null, or none, starts from now. With a cursor, the firstcheck()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.
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 (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.
Errors
A refusal is a JSON-RPC error. Each has two codes, one per dialect:
| 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. 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 and error codes 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.
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:
compat | Dialect |
|---|---|
"auto" (the default) | The sketch for a caller FrontMCP recognizes 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.
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 onwebhook-id). - A gap isn't an error.
truncated: truemeans 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 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, andevents:publishandevents:deliveron the server's side. See Flows and stages and Hook decorators. - 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.
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() and sends it web Requests, as an MCP 2026-07-28 client would over HTTP.
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.
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" });
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
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:
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" } });
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
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:
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" });
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
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.
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:
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:
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":
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 awhsec_secret. Pass several keys to accept any of them; a header with two signatures verifies when one matches."stale"means awebhook-timestampmore thanWEBHOOK_SIGNATURE_TOLERANCE_SECONDS(300) from the third argument, the time in milliseconds,Date.now()by default.generateStandardWebhookSecret()makes a secret forevents/subscribe,whsec_and the base64 of 32 random bytes, andisStandardWebhookSecret()checks one.webhookSignatureHeaders({ id, timestamp, body }, keys)signs a message as the server does,generateWebhookMessageId(kind?)makes amsg_…id, andWEBHOOK_ID_HEADER,WEBHOOK_TIMESTAMP_HEADERandWEBHOOK_SIGNATURE_HEADERare the header names.
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:
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);
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
A message a client reads never carries what a non-public error said: ECONNREFUSED 10.0.0.7:5432 stays on the server.
Troubleshooting
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 does. A session opened with initialize under an earlier revision needs no such header.
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 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.
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().
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 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.
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.
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").
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 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.
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 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-ids you handled and skip a repeat. createEventWebhookReceiver() remembers the last 10000 per subscription.
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.
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.
The limit of … per caller is reached
ResourceExhausted. One caller holds subscriptions.maxPerPrincipal 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 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.