Repository navigation
feat: Events extension (SEP-3415) #3209
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
KKonstantinov
wants to merge
42
commits into
main
Choose a base branch
from
feature/ext-events-sep-3415
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+24,536
−82
Draft
Changes from all commits
Commits
Show all changes
42 commits
Select commit
Hold shift + click to select a range
ea5e7c5
feat(core): Events extension (SEP-3415) wire schemas and core subpath
KKonstantinov 235ecfa
feat(core-internal): Events shared internals: EventsError, canonical …
KKonstantinov b25890a
feat(server): EventsExtension registration, attach, events/list and e…
KKonstantinov 65be2c3
feat(server): events/poll with emit buffer, cursors and poll leases
KKonstantinov ba9d898
feat(server): events/stream push delivery, streamed in every HTTP res…
KKonstantinov 367f4f8
fix(server): fresh cursor on a truncated events/stream batch
KKonstantinov a5804c1
feat(server): Events webhook delivery engine
KKonstantinov fb1a345
fix(server): retry webhook control envelopes, bound parked deliveries
KKonstantinov db11773
feat(server): Events webhook subscriptions, InMemoryWebhookSubscripti…
KKonstantinov 1491982
fix(server): count in-flight webhook creates and key ids on client ar…
KKonstantinov 6364fe8
feat(server): SSRF-hardened nodeWebhookSender at ext/events/node
KKonstantinov 3649309
fix(server): classify NAT64 well-known prefix by its embedded IPv4
KKonstantinov 199befc
feat(server): validate Mcp-Param headers on events requests
KKonstantinov d328c39
feat(client): internal long-lived request streams
KKonstantinov 49324ed
fix(client): end request streams from a snapshot and always run base …
KKonstantinov cc6791c
feat(client): EventsClientExtension with list, gating, mode selection…
KKonstantinov 9fad019
fix(client): end event subscriptions on close and recover from stale …
KKonstantinov 9aa9fbc
feat(client): Events push driver and shared recovery rules
KKonstantinov 4641d0d
fix(client): never re-arm the push dead-stream timer after the stream…
KKonstantinov 23225ed
feat(client): Events webhook driver, receiver and shared driver recovery
KKonstantinov 28a20fe
fix(client): serialize identical webhook subscriptions and release on…
KKonstantinov a387a34
fix(server): gate events on the session's era and defer module-scope …
KKonstantinov 3bd3c4d
test: Events integration and wire-behaviour suites
KKonstantinov 9459651
test(e2e): Events requirements and scenarios
KKonstantinov 2236e1e
test(e2e): keep shared Events requirement wording to the SEP, add SDK…
KKonstantinov 7533cd6
test(e2e): test the Events capability rule through the listen acknowl…
KKonstantinov b1eaf1f
fix(server): no SSE comment keepalive on events/stream
KKonstantinov e33b525
test(conformance): Events fixture and client scenarios (local until r…
KKonstantinov 847ce2d
fix(server): no truncated flag on a null cursor (non-replayable event…
KKonstantinov 6f42772
fix: export Events types that exported symbols reference (typedoc)
KKonstantinov 2cfacad
docs(events): example story, guides and changeset
KKonstantinov 707e9b6
fix(events): final review fixes — non-replayable poll delivery, verif…
KKonstantinov c3e6ed4
Merge origin/main into feature/ext-events-sep-3415
KKonstantinov 8d3ebd5
feat(events): install Events through the extensions option, drop attach
KKonstantinov 1ac5415
fix(events): address review findings on delivery, limits and DNS
KKonstantinov 0791753
fix(events): second review round — DNS deadline and pinning, delivery…
KKonstantinov 88f5c1b
fix(events): bound held webhook messages and throttle abandon reports
KKonstantinov 5ebb589
fix(events): third review round — auth and retry endings, gaps, backl…
KKonstantinov 3df6a72
fix(events): fourth review round — auth retries, stream and replay ed…
KKonstantinov 8b16af6
fix(events): fifth review round — broadcast-only emit, push backpress…
KKonstantinov f3bdeab
fix(events): sixth review round — client backpressure, paged checks, …
KKonstantinov cd74403
fix(events): seventh review round — bounded arguments, fair verificat…
KKonstantinov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| --- | ||
| '@modelcontextprotocol/core': minor | ||
| '@modelcontextprotocol/core-internal': minor | ||
| '@modelcontextprotocol/client': minor | ||
| '@modelcontextprotocol/server': minor | ||
| --- | ||
|
|
||
| author: @KKonstantinov | ||
|
|
||
| Add the Events extension (SEP-3415), reachable through new `ext/events` subpaths; package root exports are unchanged. The whole Events API is experimental and may change in a minor release. | ||
|
|
||
| - `@modelcontextprotocol/server/ext/events`: `EventsExtension`, whose `registerEvent(name, definition)` takes a `check` function or `emitOnly: true` and returns a handle with `update()`, `remove()` and `terminate()` (and `emit()` for emit-only types), and which serves `events/list`, `events/poll`, `events/stream`, `events/subscribe` and `events/unsubscribe` on every `McpServer` constructed with it in the `extensions` option; `InMemoryWebhookSubscriptionStore`; `EventsError`; the types `EventContext`, `CheckContext`, `EventInput`, `EventResult`, `EventDefinition`, `CheckEventDefinition`, `EmitOnlyEventDefinition`, `EventHandle`, `EmitOnlyEventHandle`, `EventsOptions`, `EventsErrorKind`, `WebhookSender`, `WebhookSendRequest`, `WebhookSendOutcome`, `WebhookSubscriptionStore` and `WebhookSubscriptionRecord`; and the wire types and constants. Push streams under every `createMcpHandler` `responseMode`, `'json'` included. Webhook delivery is on when `webhookTtlMs`, `webhookSender` and `getPrincipal` are all set; `trustedOrigins` exempts exact origins from the `https` and private-address rules, for development. | ||
| - `@modelcontextprotocol/server/ext/events/node`: `nodeWebhookSender()`, a `WebhookSender` for Node.js that requires `https`, resolves the host at every send, refuses IANA special-purpose addresses, follows no redirects and gives up after 5 seconds. | ||
| - `@modelcontextprotocol/client/ext/events`: `EventsClientExtension`, passed in one `Client`'s `extensions` option, with `list()`, `subscribe({ name, arguments, delivery?, cursor?, maxAgeMs?, onGap? })` and `createWebhookHandler()`; `NoCompatibleDeliveryModeError`; `EventsError`; the types `EventsClientOptions`, `SubscribeOptions`, `EventSubscription` (an async iterable with `cursor`, `deliveryMode`, `deliveryStatus` and `cancel()`) and `EventsErrorKind`; and the wire types and constants. A subscription prefers webhook (when configured), then push, then poll. | ||
| - `@modelcontextprotocol/core/ext/events`: the wire constants, a Zod schema and inferred type for every Events wire shape, and `EventsCapabilitySchema`, `EventsCapability` and `eventsCapabilityOf`. | ||
|
|
||
| Clients now send `Mcp-Name` on `events/poll`, `events/stream`, `events/subscribe` and `events/unsubscribe`, and `createMcpHandler` requires it on 2026-07-28 (`400` / `-32020` when it is missing or does not match `params.name`), whether or not the server serves Events. | ||
|
|
||
| Events is served and used on protocol 2026-07-28 only. Not included: `notifications/events/list_changed`, and webhook grants without expiry (`refreshBefore: null`). With several replicas sharing a `WebhookSubscriptionStore`, `emit()` reaches push streams and the poll buffer only on the emitting process, and the `check` loop of a webhook subscription may run on more than one replica. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| --- | ||
| shape: how-to | ||
| --- | ||
|
|
||
| # Events | ||
|
|
||
| ::: warning Experimental | ||
| Events is an MCP extension at the Beta stage, defined by SEP-3415; see [its specification](https://github.com/modelcontextprotocol/ext-events/blob/main/specification/beta/events/events.mdx). Its SDK API is new and may change in a minor release. | ||
| ::: | ||
|
|
||
| `EventsClientExtension` subscribes to a server's event types, and you read each **subscription** with `for await`. | ||
|
|
||
| ```ts source="../../examples/guides/clients/events.examples.ts#subscribe_basic" | ||
| import { Client } from '@modelcontextprotocol/client'; | ||
| import { EventsClientExtension } from '@modelcontextprotocol/client/ext/events'; | ||
|
|
||
| const events = new EventsClientExtension(); | ||
| const client = new Client({ name: 'ops-console', version: '1.0.0' }, { versionNegotiation: { mode: 'auto' }, extensions: [events] }); | ||
| await client.connect(transport); | ||
|
|
||
| const subscription = await events.subscribe({ name: 'ticket.updated', arguments: { queue: 'billing' } }); | ||
| for await (const event of subscription) { | ||
| console.log(event.name, event.data); | ||
| break; | ||
| } | ||
| ``` | ||
|
|
||
| When a ticket in the billing queue opens, it prints: | ||
|
|
||
| ```text | ||
| ticket.updated { ticketId: 'T-7', status: 'open' } | ||
| ``` | ||
|
|
||
| Pass the extension in the client's `extensions` option: the client calls its `setup` while it is constructed, which ties the extension to that one client. `subscribe()` resolves once its first exchange with the server succeeds, and the subscription starts from now unless you pass a `cursor`. `list()` returns the server's event types with their schemas and delivery modes. | ||
|
|
||
| Each subscription takes the first delivery mode the event type offers out of webhook (when you configure it), push and poll; `delivery` forces one, and `subscription.deliveryMode` says which it got. Without `delivery`, when a push subscription's first stream fails before its first `notifications/events/active` with anything but an `EventsError` (no valid `active` within the request timeout, say, behind a host that buffers whole responses, or a stream that ends before one), the client reports the failure to its `onerror` and subscribes by poll instead, if the event type offers poll. The loop is the same in every mode, drops a repeated `eventId`, and leaving it cancels the subscription. | ||
|
|
||
| When 1 000 events wait for your loop, delivery pauses. Until the loop has taken half of them, poll sends no `events/poll`, and push closes its stream at the next event that moves the cursor, to reopen it from there. The webhook receiver answers `503` to each event while 1 000 wait, and the server retries it; a loop that stays behind longer than the server retries gets those events as a gap, through `onGap`. Identical webhook subscriptions share one server subscription, so the receiver answers `503` only while every one of their loops is 1 000 behind; while one has room, a loop that is behind loses its oldest queued events instead, reported through `onGap` once until it has taken half of them. An event type that cannot resume may lose what happens while delivery pauses, as there is no cursor to recover it from: poll and webhook report each pause through `onGap` (with `null`), and push keeps its stream open and drops the loop's oldest queued events instead, reported the same way. | ||
|
|
||
| ::: info | ||
| Events is used on protocol 2026-07-28 only, so create the client with `versionNegotiation: { mode: 'auto' }` or a pin — see [Protocol versions](../protocol-versions.md). | ||
| ::: | ||
|
|
||
| ## Resume from a saved cursor | ||
|
|
||
| `subscription.cursor` is the newest cursor that is safe to save; pass it back as `cursor` to pick up where the loop stopped. | ||
|
|
||
| ```ts source="../../examples/guides/clients/events.examples.ts#subscribe_cursor" | ||
| // Save the cursor; it covers every event the loop finished with. | ||
| const saved = subscription.cursor; | ||
|
|
||
| // Later, maybe in a new process: resume from the saved cursor. | ||
| const resumed = await events.subscribe({ name: 'ticket.updated', arguments: { queue: 'billing' }, cursor: saved }); | ||
| for await (const event of resumed) { | ||
| console.log(event.name, event.data); | ||
| if (event.data.status === 'closed') break; | ||
| } | ||
| ``` | ||
|
|
||
| Meanwhile the ticket was closed. The resumed subscription delivers the event the first loop broke on again, then the change it missed: | ||
|
|
||
| ```text | ||
| ticket.updated { ticketId: 'T-7', status: 'open' } | ||
| ticket.updated { ticketId: 'T-7', status: 'closed' } | ||
| ``` | ||
|
|
||
| The cursor covers the events the loop finished with, and the loop finishes with an event when it asks for the next one, so a resumed subscription can repeat the last event: handle events idempotently, or skip an `eventId` you have handled. An event type that cannot resume has a `null` cursor, and there is nothing to save. | ||
|
|
||
| Pass `maxAgeMs` with a `cursor` that may be old: no event older than `maxAgeMs` before `subscribe()` is delivered, for the life of the subscription, and the server reports the events it skips as a gap. The server judges a `check` event's age by its `timestamp`, and an emitted event's by when `emit()` ran, so for a `check` type this holds only as far as its events carry the time they happened. | ||
|
|
||
| `onGap` receives the cursor delivery continues from when events may have been skipped: the server reported `truncated`, delivery started again from now after a schema change made the server refuse your cursor, your loop fell 1 000 events behind on a type that cannot resume (`null`), or a webhook loop that fell 1 000 behind dropped its oldest events while an identical subscription kept up. Closing the client, or connecting it again, ends every subscription, and the loop rejects with an `SdkError` (`ConnectionClosed`). After reconnecting, subscribe again and pass the cursor you saved. | ||
|
|
||
| ## Receive events by webhook | ||
|
|
||
| Give the extension a webhook URL and serve its receiver there. | ||
|
|
||
| ```ts source="../../examples/guides/clients/events.examples.ts#webhook_receiver" | ||
| import { Hono } from 'hono'; | ||
|
|
||
| const hooked = new EventsClientExtension({ webhook: { url: 'https://hooks.example.com/mcp/events' } }); | ||
| const handleWebhook = hooked.createWebhookHandler(); | ||
|
|
||
| // Serve the receiver at the webhook URL from any fetch-style server; here, Hono. | ||
| const app = new Hono(); | ||
| app.post('/mcp/events', c => handleWebhook(c.req.raw)); | ||
| ``` | ||
|
|
||
| With `webhook` set, a subscription prefers webhook wherever the event type offers it: the server POSTs each event to the URL, and the receiver checks the signature and routes the event into its subscription's loop. The client makes a `whsec_` secret for each server subscription (or takes one from `secretProvider`), answers the server's verification challenge, and refreshes the subscription before it expires. `subscription.deliveryStatus` holds the delivery health the server last reported. | ||
|
|
||
| Webhook subscriptions with the same name and arguments share one server subscription, which pauses only while every one of their loops is 1 000 events behind, and cancelling the last of them sends `events/unsubscribe`. The SDK's server accepts a webhook subscription only from an authenticated principal: it does not list webhook to a caller without one, so that client subscribes by push or poll. The receiver answers `503` to a subscription it does not know yet, and the server retries. | ||
|
|
||
| The receiver answers `2xx` once it has queued an event in memory, so events queued but not yet read by your loop are lost if the process exits. Subscribing again within the grant, while the server still delivers to the subscription, continues from the server's position rather than from your saved cursor. | ||
|
|
||
| ## Handle errors | ||
|
|
||
| Catch `EventsError` around `subscribe()` and the loop; `kind` says what went wrong. | ||
|
|
||
| ```ts source="../../examples/guides/clients/events.examples.ts#errors" | ||
| import { EventsError } from '@modelcontextprotocol/client/ext/events'; | ||
|
|
||
| try { | ||
| const refused = await events.subscribe({ name: 'ticket.updated', arguments: { queue: 42 } }); | ||
| for await (const event of refused) console.log(event.data); | ||
| } catch (error) { | ||
| if (!(error instanceof EventsError)) throw error; | ||
| console.log(error.kind); | ||
| } | ||
| ``` | ||
|
|
||
| The server rejects `queue: 42` against the event type's `inputSchema`, so it prints: | ||
|
|
||
| ```text | ||
| invalidParams | ||
| ``` | ||
|
|
||
| `subscribe()` rejects with an `EventsError` when the server does not list the event type or refuses the subscription (`notFound`, `invalidParams`, `forbidden`, `unsupported`, `resourceExhausted` or `callbackEndpointError`), with an `SdkError` when the exchange fails in the SDK, such as a closed connection, an HTTP error status other than `5xx` and `429`, or a push stream that ends before a valid `notifications/events/active` or sends none within the request timeout, and with any auth failure of the transport (such as `UnauthorizedError` for a `401` the `authProvider` cannot resolve, or an error the `authProvider` throws while it fetches a token), so a misconfigured provider fails here, or a `ProtocolError` `-32601` from a server that does not serve the method; other failures of the first exchange, such as a transport error, an HTTP `5xx` or `429`, or another JSON-RPC error, are retried in the background. The server's webhook verification limit (`resourceExhausted` with `data.limit: 'verification'`) is one of those: the client subscribes again after `data.retryAfterMs` (or its usual backoff without one), before and after the first exchange. A push subscription that can fall back to poll, as above, does so instead on any of these failures but an `EventsError`, an auth failure, a `-32601` or a closed connection. Each retried failure, such as a transport error, an HTTP error status, another JSON-RPC error or the verification limit, before the first exchange succeeds or after, goes to the client's `onerror`: the first at once, then at most one report a minute with how many were retried since. A push stream that ends after its `active` or goes silent is reopened without a report, and so is a request retried after the event types are listed again. When the server refuses the delivery mode the client selected (`unsupported` for `deliveryMode`, say after a deploy that dropped it), the client lists the event types again once and subscribes in the mode that listing selects; a mode you force with `delivery` is not changed. Once subscribed, the loop ends with an `EventsError` when the server ends the subscription, such as `forbidden` when access is revoked, with a `-32601` (over Streamable HTTP, the `SdkHttpError` of a `404` whose body is that error), and with an auth failure only the user or the configuration can fix: `UnauthorizedError`, an `SdkError` such as a `401` after re-authentication, an `OAuthError` other than `server_error`, `temporarily_unavailable` and `too_many_requests`, or an OAuth flow error such as `InsecureTokenEndpointError`. Any other error the `authProvider` throws, such as a network error or one of those `OAuthError` codes while it fetches a token, is retried and reported like a transport error. A `notFound`, or an `unsupported` for a schema change, makes the client list the event types again and carry on while the type is still offered in that mode; a second `notFound` in a row, with no successful exchange between them, ends the loop even then. | ||
|
|
||
| `NoCompatibleDeliveryModeError` means no delivery mode the event type offers is usable here: webhook needs the `webhook` option, and `delivery` narrows the choice to one mode. Against a server without Events, or on a connection older than 2026-07-28, `events.supported` is `false`, and `list()` and `subscribe()` throw `SdkError` (`CapabilityNotSupported`). An error thrown from `onGap` goes to the client's `onerror`. | ||
|
|
||
| ## Recap | ||
|
|
||
| - `new EventsClientExtension()` in the client's `extensions`, then `connect()`, `subscribe({ name, arguments })` and `for await`. | ||
| - The loop is the same in every mode, and leaving it cancels the subscription. | ||
| - `subscription.cursor` is safe to save; pass it back as `cursor` to resume, and expect the last event again. | ||
| - `webhook: { url }`, with `createWebhookHandler()` served at that URL, turns on webhook delivery. | ||
| - `subscribe()` and the loop fail with an `EventsError` whose `kind` says why. | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 nit (optional): The client guide says a request retried after the event types are listed again goes unreported, but the first such
notFoundnow reachesonerror.#notFoundWhileOfferedcallsthis.#retrying(error)at packages/client/src/ext/events/recovery.ts:371, and packages/client/test/ext/events/poll.test.ts:382 pins that report. docs/clients/events.md:116 still says such a request is retried "without a report". Fix: reword that sentence so it excepts the firstnotFoundfor a type still listed, which is reported as a retried failure, and keeps the unreported case for a schema change. [also at: docs/clients/events.md:116 - nit: CLAUDE.md asks that docs say what the code does: docs/clients/events.md:116 says a request retried after the event types are listed again is retried "without a report".]Why this was flagged
Nothing fails at runtime; this is a check of the guide against the code. docs/clients/events.md:116 says "A push stream that ends after its
activeor goes silent is reopened without a report, and so is a request retried after the event types are listed again". Since the latest push,DriverLoop.recoversends anotFoundfor a type thatevents/liststill offers to#notFoundWhileOffered(packages/client/src/ext/events/recovery.ts:358). On the first one that method sets#notFoundand callsthis.#retrying(error)(recovery.ts:369-371), which callsconnection.report(new Error(... failed and is retried: ...))(recovery.ts:386). packages/client/test/ext/events/poll.test.ts:399-404 pins theonerrormessage "poll subscription to 'tick' failed and is retried: Not found". An app author who reads the guide does not expect anonerrorcall here. No safeguard applies: nothing compares guide prose with behaviour. The base branch has no Events guide.Verification: Triggered when a subscribed loop gets a
notFoundfor an event type that the re-list still offers in the same mode. Nothing fails at runtime; the guide misstates what reachesonerror. Inpackages/client/src/ext/events/recovery.ts,DriverLoop.recovercallsthis.#notFoundWhileOffered(error)(line 358), which callsthis.#retrying(error)(lines 368-372).Finding ID:
f-43db1001