Repository navigation
feat: Events extension (SEP-3415) - #3209
KKonstantinov wants to merge 52 commits into
Conversation
…JSON, Standard Webhooks, Mcp-Name rows
…onStore and fan-out
…Workers-unsafe state
…-specific entries
There was a problem hiding this comment.
Findings marked 🟡 are optional suggestions and need no follow-up push.
Still open from earlier reviews (10):
- 🔴
packages/server/src/ext/events/leases.ts:92—On Cloudflare Workers, poll leases never expire, so an isolate ends up refusing every new Events subscription with 'Sub… - 🔴
packages/server/src/ext/events/validation.ts:65—A caller can pin gigabytes of server memory by holding open events/stream requests padded to the 4 MiB body limit. The… - 🔴
packages/server/src/ext/events/webhookSubscriptions.ts:493—With replicas on a shared webhookStore, every replica can end up refusing all new poll, push and webhook subscriptions… - Also unresolved: 7 minor or pre-existing.
If you have decided not to act on one of these findings, you can resolve its thread (a reply alone leaves it open). The next review then stops counting it, unless this repository's Claude Approvals policy refuses the resolve. If the policy does not let you resolve it and the finding is fixed or wrong, leave the thread open, with a reply saying why if no code changed. A review is sure to check a finding again only while its thread is open. To review this commit again now, use Re-run on its "Claude Code Review" check.
…ounts, bounded params, stdio bursts, events before terminate Server: - Poll leases expire by their expiry time whenever the lease table is read or counted, and webhook subscription counts leave out a watch past its expiry and recheck it, so neither depends on a timer firing (Cloudflare Workers stop a request's timers when it ends). The guide says to use poll or push on Workers. - A webhook watch a process starts for a refresh of a subscription it did not create holds no maxSubscriptions slot or principal quota, so replicas no longer each count the whole fleet. - Request params are limited to 131 072 characters of canonical JSON in every mode, beside the 65 536-character arguments limit. - On a transport that cannot tell how far its client has read, such as stdio, an emit-only stream is abandoned only when emitBuffer.maxEvents live events wait and the transport has been writing its current message for longer than the heartbeat interval, so a burst no longer ends a stream that is being read. - Events queued before terminate(), remove() or a schema change are written ahead of terminated; only a client's cancellation or an abandon drops queued events. - A control body that cannot be serialised is reported and a terminated body goes out without data, instead of an unhandled rejection. - The heartbeat timer restarts only after a frame is written, and timer delays taken from heartbeatMs or checkIntervalMs are clamped to the largest timer delay. Client: - A terminated body that arrives while the client retries a failed events/subscribe ends the subscription with that error. - A webhook subscription to a type without replay reports onGap(null) whenever the server stopped holding it before the next successful subscribe, judged only against a grant still running when it arrived. - Comments no longer cite internal design-document ids, and the guide's push fallback sentence names its exceptions.
|
@claude review |
There was a problem hiding this comment.
Findings marked 🟡 are optional suggestions and need no follow-up push.
Still open from earlier reviews (6):
- 🔴
packages/server/src/ext/events/validation.ts:70—A caller can pin gigabytes of server memory by holding open events/stream requests padded to the 4 MiB body limit. The… - 🔴
packages/server/src/ext/events/webhookSubscriptions.ts:503—With replicas on a shared webhookStore, every replica can end up refusing all new poll, push and webhook subscriptions… - Also unresolved: 4 minor or pre-existing.
If you have decided not to act on one of these findings, you can resolve its thread (a reply alone leaves it open). The next review then stops counting it, unless this repository's Claude Approvals policy refuses the resolve. If the policy does not let you resolve it and the finding is fixed or wrong, leave the thread open, with a reply saying why if no code changed. A review is sure to check a finding again only while its thread is open. To review this commit again now, use Re-run on its "Claude Code Review" check.
…its request, a principal's webhook share across restarts Server: - Extension middleware on events/poll, events/stream, events/subscribe and events/unsubscribe refuses, with invalidParams, a request longer than 131 072 characters of canonical JSON as the protocol layer keeps it: its id, its params and _meta as received (keys the params parse would drop included), and the envelope and retry material lifted onto ctx.mcpReq. It replaces the params-only check, so a live push stream can no longer be padded to the body limit; an over-size request on a 2025-11-25 connection gets -32602. - A new webhook subscription counts toward its principal's share the webhook subscriptions this process serves for that principal, including those it took over on a refresh, so after a restart the share holds once the principal's subscriptions have been refreshed here. The process-wide maxSubscriptions still counts only what this process created. Core: - Protocol._startInbound hands the instrumentation scope a bound onerror instead of a closure, so a long-lived inbound request no longer keeps the raw message it arrived as while its handler runs.
|
@claude review |
There was a problem hiding this comment.
Findings marked 🟡 are optional suggestions and need no follow-up push.
Still open from earlier reviews (7):
- Unresolved: 6 minor or pre-existing, 1 blocking on lines changed since (possibly already fixed).
If you have decided not to act on one of these findings, you can resolve its thread (a reply alone leaves it open). The next review then stops counting it, unless this repository's Claude Approvals policy refuses the resolve. If the policy does not let you resolve it and the finding is fixed or wrong, leave the thread open, with a reply saying why if no code changed. A review is sure to check a finding again only while its thread is open. To review this commit again now, use Re-run on its "Claude Code Review" check.
…d, one recovery per server end, verification limits across hosts Node middleware: - toWebRequest, and so toNodeHandler, hands the request body to the forwarded Request as a one-chunk stream instead of a string, so a long-lived request such as an open events/stream no longer keeps its body once read. Such a Request can no longer replay its body on a 307 or 308 redirect, and one without a Content-Type no longer gets text/plain (own changeset). Server: - Per principal and across all hosts, at most 3 webhook endpoint verifications wait or run at once and at most 10 may fail in any 60 seconds, so different spellings of one host cannot multiply them; the per-host totals stay. Client: - A terminated body that repeats the error the webhook loop just recovered from (one server-side end answered on the refresh and POSTed) is not recovered from a second time, so a notFound for a type still offered no longer ends the subscription and a schema change keeps the cursor.
|
@claude review |
…r streaming methods, a rejecting webhook sender fails verification, webhook ends during a re-subscribe kept Server: - Before it serves a streaming method (events/stream), createMcpHandler cancels the request bodies nothing will read: the request's own when the host passed parsedBody (the Hono parser reads a clone, which leaves every byte queued on the original), and its own unread forward copy. An open stream whose body was padded with JSON whitespace no longer keeps that body. - A webhookSender that rejects during endpoint verification is reported to onerror and fails the verification as connection_refused, like any failed verification (failure memory, failure limits, callbackEndpointError), instead of reaching the client as an internal error it retries without end. Client: - The webhook loop forgets the end it recovered from once it sends the next events/subscribe, so a terminated body that ends the new subscription with the same error is no longer dropped as a copy of the old end; when that subscribe fails, a copy of the old end is still dropped. Node middleware: - The previous round's toWebRequest change (the body handed on as a stream) leaves this pull request for one of its own. Tests: - The cross-host verification limit test compares its three concurrent sends as a set, since their order depends on which signing finishes first.
|
@claude review |
There was a problem hiding this comment.
Beyond the inline finding, I also checked the switch of every per-request SSE response, not only events/stream, to a byte-length queue with a high-water mark of 0 (packages/server/src/server/perRequestTransport.ts:430). In the SDK, desiredSize is read only by the new backlog() (:468), which serves the Events backpressure path; frame writes are not gated on the stream's fill state, so other SSE responses enqueue as before. This is from reading the code; nothing was run.
Extended reasoning...
This run also examined the change of the per-request SSE stream's queuing strategy in perRequestTransport.ts, which applies to all streaming responses from createMcpHandler, and found no SDK write path that depends on the stream's fill state. The change as a whole adds the Events extension across core, server and client and touches security-sensitive surface: webhook signing, SSRF-hardened callback delivery, request-body retention and Mcp-Name / Mcp-Param header validation.
The latest push brings back an issue flagged in an earlier review; replied in that comment's thread.
Still open from earlier reviews (10):
- 🔴
packages/server/src/ext/events/validation.ts:36—On Hono, a caller can still pin about 4 MiB of server memory per open events/stream by padding the request body with JS… - Also unresolved: 9 minor or pre-existing.
If you have decided not to act on one of these findings, you can resolve its thread (a reply alone leaves it open). The next review then stops counting it, unless this repository's Claude Approvals policy refuses the resolve. If the policy does not let you resolve it and the finding is fixed or wrong, leave the thread open, with a reply saying why if no code changed. A review is sure to check a finding again only while its thread is open. To review this commit again now, use Re-run on its "Claude Code Review" check.
… open stream keeps none of it toWebRequest, and so toNodeHandler, built every converted Request from the body text, and a Request keeps a string body for its whole life. An open events/stream keeps its Request, so a body padded with JSON whitespace up to the request limit stayed in memory per stream. Only a request whose Mcp-Method header (as Headers reads it, the value createMcpHandler serves by) is events/stream now carries its body as a one-chunk stream, which keeps nothing once read; every other request is built as before. Such a Request cannot replay its body on a 307 or 308 redirect and, without a Content-Type header, gets no default text/plain (own changeset).
|
@claude review |
…close push streams without waiting, back off on short streams Server: - A stdio push stream of an emit-only type is also abandoned once emitBuffer.maxEvents live events have waited for a whole heartbeat interval, so a client that keeps reading, but more slowly than the emits, no longer grows server memory without bound. A burst that drains within the interval still goes through. - Webhook messages waiting between retries now count towards the 10 000 a subscription holds, with those waiting for a slot or parked. Past that the oldest is abandoned and the subscriber gets a gap, so a receiver that fails often, but under the suspension threshold, no longer makes the server hold every retry. - A process that takes over a webhook subscription refreshed without a cursor drops the events of its first check only for a type with replay (one whose check returns a cursor), so the subscriber no longer gets events from before it subscribed. A type without replay delivers as before. - A transform hook's result is typed as the payload schema's input, because the SDK parses it with payloadSchema, as it parses an emitted event's data. - The terminate() JSDoc says that a poll lease answers its next poll with the error, and that a later poll for the same principal, event name and arguments starts a new lease and runs onSubscribe again. Client: - Closing a push stream ends it at once. On the 2026-07-28 revision over a transport with per-request streams (Streamable HTTP), it sends no notifications/cancelled, because the abort is the cancellation, as it is for any other request. On other transports and revisions the cancellation is sent without being waited for. - The push reconnect backoff resets only after a stream has stayed open for its heartbeat interval, so streams that end right after they start no longer reopen about twice a second. - In a browser, which sends no Mcp-Param headers, a -32020 no longer triggers a second events/list and a retry that cannot succeed. - A notification whose stream: subscription id matches no live push stream (a frame still in flight after the stream ended) is dropped instead of reaching the global handlers and fallbackNotificationHandler. Docs: - Server guide: what terminate() does for poll clients that share a lease, the stdio abandon rule, and the held-message cap with retries included. - Client guide: browser clients and Mcp-Param headers, and that webhook mode needs a clock close to the server's.
|
@claude review |
…d open 5 s A push stream now resets the client's reconnect backoff once it has stayed open for 5 s after its `active`, or for its whole heartbeat grant if that is shorter. With the whole grant (30 s by default) as the threshold, a host or proxy that ends every response sooner, such as a 10 or 29 s request limit, never reset it, so after a few streams each reopen waited up to 30 s. Streams that end right after `active` still back off.
…e once the hook settles A termination (`handle.terminate()`, `remove()` or a re-registration) that reached a poll lease while its `onSubscribe` was still running ran `onUnsubscribe` at once. A hook that does not watch `ctx.signal` then finished its setup after it, the poll that started the lease and any poll waiting on that start were answered as if nothing had ended, and the setup was never torn down. The termination now only marks such a lease and aborts its `ctx.signal`; once the hook succeeds, `onUnsubscribe` runs and those polls answer with the termination's error. A hook that fails gets no `onUnsubscribe`, as push and webhook subscriptions already behave. The push tests also state the reconnect backoff rule as it now is: a stream resets it once it stayed open 5 s after its `active`, or its whole grant if shorter.
Adds the Events extension (SEP-3415) to the server, the client and the core wire schemas. A server declares event types and delivers their events by poll (
events/poll), push (events/stream) or webhook (events/subscribe); a client lists them and subscribes with one call, and the SDK picks the delivery mode. Everything is experimental and reachable only through newext/eventssubpaths; package root exports are unchanged. Events installs through the extensions option from #2820:new McpServer(info, { extensions: [events] })andnew Client(info, { extensions: [eventsClient] }).Motivation and Context
SEP-3415 was accepted on 2026-11-11 and still lists an official-SDK reference implementation as outstanding; this is the TypeScript one. modelcontextprotocol/python-sdk#3822 covers poll and webhook with in-memory state; this PR covers all three delivery modes, does the delivery work for the author as SEP Appendix A describes, and makes webhook state pluggable.
Built against:
60b15c16, which includes theheartbeatMsgrant, the server-generated per-messagewebhook-id, the advisorynextPollMsandMcp-Param-*headers onevents/*requests.76fef32dand feat(events): client conformance scenarios (#540) conformance#541 atc8625de3; their rows quote the older SEPb08e4f9d.How Has This Been Tested?
EventsError, canonical JSON and webhook signing, and core tests for the wire schemas.events/*exchange:Mcp-Name,Mcp-Paramand the400/-32020mismatch, the{}capability, and that the client never openssubscriptions/listen.test/e2e/requirements.ts, run on 2026-07-28. Ids shared with other SDKs use the SEP's wording; SDK-specific behaviour hastypescript:ids.examples/eventsis a self-verifying server and client pair with an emit-only and acheckevent type: poll and push on the stdio and HTTP legs, webhook on the HTTP leg.pnpm run:examplespasses every leg.EVENTS_CONFORMANCE_DIR; once the scenarios are released they move intoconformance.ymlwith a pin bump.events-discovery(14),events-poll(33),events-push(28),events-webhook(28) andevents-webhook-delivery(25), with 13 warnings, all "unverified, not violated". Baselined: the twoevents-webhook:sep-3415-ttl-no-expiry-*checks, because the server grants only finite TTLs (below);events-discovery:sep-3415-list-pagination, becauseevents/listis served as one page; and ten checks the suite reports as not testable for any server (it cannot mint a stale cursor, rotate a secret mid-delivery, or set up a second principal, a restart or a key-discovery origin).events-client-no-extensionpasses. The poll, push and webhook client scenarios cannot grade yet: the conformance#541 mock server omitspayloadSchemafrom its event descriptors (SEP l.15) andheartbeatMsfromactive(SEP l.382), so the client, which stays strict, refuses the listing and never polls, streams or subscribes. Those 14 checks are baselined with that reason until the mock sends both fields (I'll raise it on requireBearerAuth 403 breaks claude desktop #541); the e2e requirements and the integration suite cover the same behaviour. Two more are baselined forlist_changed(below).protocol:timeout:max-total [sse]timeout flake, which fails the same way onmainwithout this branch.Breaking Changes
None. The Events API is new, experimental, and reachable only through the new subpaths.
One edge worth knowing: on 2026-07-28,
createMcpHandlernow requiresMcp-Nameonevents/poll,events/stream,events/subscribeandevents/unsubscribe(400/-32020when it is missing or does not matchparams.name), whether or not the server serves Events. A server without Events answers those methods with method-not-found anyway, so only the error a header-less client sees changes.Types of changes
Checklist
Additional context
Protocol version. Events is served and used on 2026-07-28 sessions only. A server whose session negotiated an earlier revision leaves Events out of its
initializeresult and answersevents/*with-32601. The check reads the session's revision, so a single request cannot opt in by claiming 2026-07-28 in its own envelope.Installing. Both sides install through #2820's
setup(ctx); there is noattach. OneEventsExtensionserves every server constructed with it, which is whatcreateMcpHandler's per-request factory needs. Skills keeps itsattachbecause it was released before #2820.Two kinds of event type.
registerEventtakes either acheck(ctx, args, cursor)function, which the SDK calls to pull from upstream, oremitOnly: true, for types the author pushes withhandle.emit(). The definition is a discriminated union, after SEP Appendix A'semit_only=True; python-sdk#3822 infers the kind instead. Either kind is delivered by poll, push or webhook.Webhook delivery needs a principal. It turns on only when
webhookTtlMs,webhookSenderandgetPrincipalare all set.getPrincipalhas no default, unlike python-sdk#3822, whoseaccess_token_principalcombines client id, issuer and subject: the TypeScriptAuthInfohas no subject field, andclientIdnames the app, not the user. A default can be added later without breaking anyone, since configuration that throws today would then be accepted.Webhook storage.
WebhookSubscriptionStoreis public, withInMemoryWebhookSubscriptionStoreas the default (thewebhookStoreoption). SEP Appendix B says "A horizontally scaled server, with several replicas behind a load balancer, needs shared state", and Appendix A assumes SDK storage ("SDKs SHOULD refuse a no-expiry cap unless the author has wired up durable storage"); python-sdk#3822 keeps memory only. The store holds webhook secrets. The SDK deletes an expired record when it next reads it, so the docs tell shared-store users to expire records themselves (a Redis TTL, for example).Finite TTLs only. The server never grants
refreshBefore: null; every grant is capped bywebhookTtlMs. No-expiry also needs collection after sustained delivery failure and a store the author declares durable, so it is a follow-up on top of the store. That is why the twottl-no-expiryconformance checks are baselined.Callback URLs.
nodeWebhookSender()requireshttps, resolves the host at every send, refuses IANA special-purpose addresses, follows no redirects and gives up after 5 seconds.trustedOrigins(Python's name for the same option) exempts exact origins from thehttpsMUST and the private-address rule, for local development only.Endpoint verification is rate-limited (SEP l.632). A failed verification is remembered for 60 seconds per principal and URL, and each callback host gets at most one verification in flight and ten per minute. Past that,
events/subscribeanswersResourceExhaustedwith{ limit: 'verification', retryAfterMs }. The limits are internal constants, not options.Several replicas. With replicas sharing a
WebhookSubscriptionStore,emit()reaches push streams and the poll buffer only on the process that emits; a webhook subscription'scheckloop may run on more than one replica (the SDK prefers a duplicate delivery to a missed one, and receivers dedupe byeventId); andonUnsubscribefor a lapsed subscription may fire on more than one replica. The docs say so.Push under every response mode.
events/streamstreams even whencreateMcpHandlerusesresponseMode: 'json'. It sends no SSE comment keepalive: the Events heartbeat (heartbeatMs, 30 seconds by default) is the liveness signal (SEP l.381).Mcp-Paramonevents/*. Clients mirror annotated subscription arguments intoMcp-Param-*headers (SEPe1794032), and the server validates them with the same code that servestools/call.Not in this PR:
notifications/events/list_changed. The SEP makes it optional on both sides: the server'slistChangeddefaults tofalse, and a client receives the notification only if it opts in onsubscriptions/listen. The server advertises{}and the client never opts in. Supporting it would mean addingeventsListChangedto the coreSubscriptionFilterand a member to the publicServerEventunion. SEP-3371 rules out extensions adding filter fields to core streams, and the replacement shape is still open on #3415 (r4359154508). Conformance: the server suite passes. In the client suite,events-client-poll:sep-3415-client-listen-opt-inandevents-client-poll:sep-3415-client-relist-on-list-changedare listed as expected failures, pending conformance#541 grading them only for clients that opt in. It will follow in a separate PR once the SEPs settle how the notification is delivered.Known limits.
callTool, a browser client sends noMcp-Paramheaders, so a server that follows the spec rejects a subscription that sets anx-mcp-headerargument with-32020.subscribe()rejects without listing the event types again.refreshBefore, so webhook mode needs clocks close together: a client clock behind by more than a third of the grant refreshes too late. Signature timestamps already require clocks within 5 minutes.Open points.
checkreturnscursor: null, the SEP's "null means start from now", read literally, gives poll clients nothing. Here the firstcheckcall of a subscription only records where to start, and every latercheck(null)call delivers what happened since; push and webhook behave the same. In poll, that subscription is the poll lease, which the SEP keys on principal, event name and arguments. Clients sharing a lease (every caller on a server without authentication, or one user's two devices) split those events between them, and a lease that lapses between polls delivers nothing. Worth settling in the SEP.retryAfterMs.