Repository navigation
feat: Events extension (SEP-3415) - #3209
KKonstantinov wants to merge 42 commits into
Conversation
…JSON, Standard Webhooks, Mcp-Name rows
…onStore and fan-out
…Workers-unsafe state
…-specific entries
- Push merges the event's _meta with the stream's subscription id instead of replacing it. - Every interval the server sends is a wire-valid integer: nextPollMs from check is rounded up, clamped at 0 and capped at half of pollSubscriptionTtlMs; heartbeatMs, defaultNextPollMs and webhookTtlMs must be positive integers, and an explicit defaultNextPollMs above half the lease TTL throws. - The client ends a push stream whose active fails its schema, and bounds the wait for the first active by the request timeout. - A verification for a host with one in flight waits its turn (at most 10 waiting; a cancelled waiter leaves at once); the client retries resourceExhausted with limit 'verification' after retryAfterMs. - With getPrincipal set, each principal (and the callers without one, together) holds at most a quarter of maxSubscriptions, refused as limit 'principalSubscriptions'. - nodeWebhookSender resolves through a c-ares Resolver, cancelled at the deadline, instead of dns.lookup on the libuv thread pool. - A new webhook subscription to an emit-only type replays the buffer from its cursor, and each body carries the event's own cursor once nothing before it is unsettled. - Docs: poll limits for types without replay, the store keeps records a minute past expiresAt so onUnsubscribe runs, DNS resolution.
|
@claude review |
… limits, stable eventId - nodeWebhookSender fails a send whose deadline or cancel fires while one DNS family is still pending, and pins the connection to every checked address (by family when asked) instead of the first, so IPv6-only servers reach dual-stack receivers. - The webhook engine runs at most 10 event POSTs per subscription at a time, for replay, resume and live bursts. - check results must give every event an eventId; one without is dropped and reported. emit() still generates ids. - The client falls back from push to poll when the first push exchange fails for a reason other than an EventsError and the app did not choose a mode. - A refresh on any replica ends a suspension: the engine reactivates when the stored record's expiresAt moves past the one it saw at suspension. - A failing store listing during an emit's fan-out is retried up to 3 times without delivering twice. - Docs and the typescript:events:store:restart requirement describe restart behaviour as it is (check types resume at the next refresh, from the client's cursor), and the client docs say the receiver acknowledges once an event is queued.
- A message holds one of a subscription's ten slots only while a POST attempt is in flight; a retry queues for a slot when it is due, so a failing receiver suspends within about 100 attempts again. - Messages waiting for a slot and parked messages share one cap of 10 000 per subscription; past it the oldest is abandoned. - Events abandoned past the cap or after their fifth failed attempt are reported to onerror at once for the first, then at most once a minute per subscription with how many. - Tests: the IPv6 fall-through resolves A to an unanswered TEST-NET address, the restart e2e runs on fake time with a bounded wait, and an invalid first active falls back to poll.
|
@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 (4):
- 🔴
packages/server/src/ext/events/webhookSubscriptions.ts:222—With a shared webhookStore, one failed store read during emit() silently drops that event for webhook subscribers, with… - 🔴
packages/server/src/ext/events/webhookSubscriptions.ts:395—An app that restarts and resumes a webhook subscription from its saved cursor silently loses the events its old process… - 🔴
packages/server/src/server/createMcpHandler.ts:915—On hosts that buffer responses, where operators set responseMode: 'json', SDK clients cannot subscribe to any event typ… - Also unresolved: 1 blocking on lines changed since (possibly already fixed).
If you have decided not to act on one of these findings, resolve its thread (a reply alone leaves it open) and the next review stops counting it. To review this commit again now, use Re-run on its "Claude Code Review" check.
| installTestHook(this, { | ||
| generation: () => this.#generation, | ||
| restart: () => { | ||
| this.#generation += 1; | ||
| for (const clear of this.#restarts) clear(); | ||
| }, | ||
| state: () => ({ | ||
| trustedOrigins: [...this.#trustedOrigins], | ||
| emitBuffer: this.#buffer.sizes(), | ||
| pollLeases: this.#poll.size, | ||
| pushStreams: this.#push.size, | ||
| webhookSubscriptions: this.#webhooks?.delivering ?? 0, | ||
| webhookExpiryTimers: this.#webhooks?.watching ?? 0 | ||
| }), | ||
| addTrustedOrigin: origin => { | ||
| assertOrigin(origin); | ||
| this.#trustedOrigins.add(origin); | ||
| }, | ||
| addSource: source => { | ||
| this.#sources.push(source); | ||
| }, | ||
| addFanOut: fanOut => { | ||
| this.#fanOuts.push(fanOut); | ||
| } | ||
| }); |
There was a problem hiding this comment.
🟡 nit (optional): CLAUDE.md's Minimalism principle prefers changes that add no API unless justified: the EventsExtension constructor installs a test hook on every shipped instance under Symbol.for('mcp.events.testHook') (restart, state, addTrustedOrigin, addSource, addFanOut), used only by unit tests and the conformance fixture. Fix: keep test-only controls out of shipped code: give tests what they need through constructor injection or a test-only build, and have the conformance fixture set trusted origins and restarts through public options.
Why this was flagged
Nothing fails at runtime. The principle guards the SDK's surface. Here packages/server/src/ext/events/extension.ts:220-244 gives every shipped EventsExtension a non-enumerable property, reachable through the global symbol registry by any code that holds the instance. Through it a caller can add a trustedOrigins entry after construction (which exempts that origin from the https and private-address rules), register extra fan-outs and sources, and drop all in-memory state. Code that exists only to serve it: #restarts and #generation in extension.ts, clear() on PollSource, EmitBuffer, LeaseTable, WebhookSubscriptions and WebhookEngine, StreamSet.closeAll() ('for a simulated restart'), and the 'Read at every send, so origins added later count' contract at webhookEngine.ts:43. It is deliberate: testHook.ts:20 calls it 'never part of the public API or its declarations' and registration.test.ts:320 pins it as non-enumerable. Its only users are test/conformance/src/events.ts:66 and four unit-test files.
Verification: Instruction: root CLAUDE.md at base 5ee54ee, principle 1, verbatim: "Minimalism — The SDK should do less, not more: prefer changes that add no API or option unless justified." REVIEW.md says to review by these principles, so it binds packages/server/src/ext/events/extension.ts.
Code: packages/server/src/ext/events/extension.ts:220-244, in a file this diff adds. The EventsExtension constructor calls installTestHook(this, {...}) unconditionally.
Finding ID: f-a1b4cbc2
There was a problem hiding this comment.
Leaving this as it is. The hook is a non-enumerable property under Symbol.for('mcp.events.testHook'), absent from the type declarations and the docs (testHook.ts:20). It exists so the unit tests and the conformance fixture can simulate a restart and add a trusted origin after construction. Moving those controls into constructor options or a separate build would add public surface, which is what principle 1 asks us to avoid. Code that can reach the instance already runs in the server's process with its privileges, so the symbol gives it nothing it did not have.
…og and replica state Client: - An auth-seam error (UnauthorizedError from an authProvider, or a throwing token()) refuses the first exchange and ends a live subscription, instead of being retried with a fresh authorization redirect each time. - Retried failures are reported to onerror, the first at once and then at most once a minute with how many; -32601 and -32602 end the subscription. - A first exchange refused with unsupported deliveryMode re-lists once and selects again; an HTTP 5xx or 429 on the first exchange is retried like any transient failure. Server: - In every check batch, truncated or not, events before the last carry the cursor the batch was read from, and so does a truncated batch's own cursor, so no saved cursor passes an unsent event. - The pinned lookup honours ADDRCONFIG: only families the host has a non-loopback, non-link-local interface address of, unless that leaves none. - Events abandoned past the held cap, after the last retry, over the body size or answered 413 are signalled to the subscriber as a gap: a gap envelope at the watermark after the next acknowledged delivery, or truncated: true on the next refresh. - A replica that only delivers for a subscription re-reads its record at expiresAt and drops the state once the record is gone, expired or re-created; a re-created record restarts the state instead. - A push stream whose unread backlog passes 1 MiB is ended; the per-request transport exposes its queued byte count internally. The restart e2e block uses fake setTimeout with a real clock so the client's refresh lands at three quarters of the 60 s grant before the grant can lapse, and a slow run cannot turn the refresh into a create.
|
@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 (3):
- Unresolved: 1 minor or pre-existing, 2 blocking on lines changed since (possibly already fixed).
If you have decided not to act on one of these findings, resolve its thread (a reply alone leaves it open) and the next review stops counting it. To review this commit again now, use Re-run on its "Claude Code Review" check.
## Motivation Nessa's existing MCP session path does not offer an Events beta polling client. An SDK caller should be able to opt into one configured server and event type without moving existing tool sessions to MCP 2026-07-28. Closes #1428 (the poll-only SDK slice). Contract: [MCP Events beta](https://github.com/modelcontextprotocol/ext-events/blob/main/specification/beta/events/events.mdx). ## Solution 1. `468ebe6b`: Add a caller-driven Events poll handle. Reuse the configured remote, grant, authorization owner, clock and HTTP port. Discover capability, list a selected poll-capable event, then return one bounded batch per caller request. 2. In the same commit, test wire and ownership behavior with injected peers and exercise the existing Reqwest adapter over real loopback HTTP against a separately written, reusable Python fixture. Keep the legacy session and application paths unchanged. ### Before The caller could use the existing tool client, but the SDK had no path to read an Events feed. ```mermaid sequenceDiagram participant Caller as SDK caller participant SDK as Nessa SDK participant Peer as Configured MCP server Caller->>SDK: Use configured server for tools SDK->>Peer: Open existing tool session Note over Caller,SDK: No Events poll handle is available ``` ### After The caller can explicitly open one event. The existing tool session still follows its original path. ```mermaid sequenceDiagram participant Caller as SDK caller participant SDK as Nessa SDK participant Peer as Configured MCP server Caller->>SDK: Choose configured server and event SDK->>Peer: Discover support and list event types Peer-->>SDK: Advertise a poll-capable descriptor SDK-->>Caller: Return caller-owned poll handle Caller->>SDK: Poll once SDK->>Peer: Poll with the current cursor Peer-->>SDK: Return a complete batch or refusal SDK-->>Caller: Return accepted batch or typed refusal ``` The handle accepts matching complete JSON/SSE replies, keeps only an in-memory checkpoint, and reports a retention gap rather than automatically recovering it. The handle classifies the first response as replay or non-replay. A later mode change returns `ReplayModeChanged` without discarding a known cursor; callers can explicitly reopen if they want to accept the new mode. A config/grant/bearer change fences acceptance, not delivery of a request already in flight. HTTP 403 is reported to the existing authorization owner; 401 does not auto-retry. Open reserves enough request budget for the widest request ID and a maximally escaped allowed cursor. **Not included:** host subscriptions, a poll scheduler, durable replay, agent/workflow activation, push, webhooks, argument schema routing annotations, migration of MCP tools, UI, or a compatibility fallback. Event payloads do not authorize action. No user flow changed, so desktop/state charts were not re-stamped; the SDK contract and ordering table are in `docs/design/mcp-connections.md`. ### Reproduce ```sh cargo test --offline --locked -p nessa-sdk --lib position_tests cargo test --offline --locked -p nessa-sdk --test infrastructure mcp_events cargo test --offline --locked -p nessa-sdk --lib infrastructure::mcp::tests::http cargo test --offline --locked -p nessa-conversation --lib events_beta_tests RUSTDOCFLAGS="-D warnings" cargo doc --offline --locked -p nessa-sdk --no-deps ``` Start either peer profile manually if needed: [fixture README](https://github.com/nessalabs/nessa-agent/blob/codex/1428-mcp-events-beta-poll/crates/nessa-sdk/tests/infrastructure/mcp/fixtures/events_beta/README.md). It is loopback-only, with synthetic CI data. Replay runs JSON and SSE; the alternate descriptor advertises push-only, which is refused. The separate official-reference smoke used unmodified [typescript-sdk#3209](modelcontextprotocol/typescript-sdk#3209) at `5ebb589b970bfc8f98e344e13299f8eb76ff8cd1` on loopback, with its synthetic counter example and its documented demo token. Nessa discovered and listed the event, bootstrapped an empty batch, observed exactly `value-1` after the example's increment, then read an empty follow-up. All six responses from that server were JSON; SSE is covered by the independent fixture. This does not claim official conformance or OAuth acquisition. The reference's pinned pnpm 10.26.1 workspace was installed with a frozen lock and scripts disabled; its filtered examples packages were built locally. ### Gates Exact Mac candidate `468ebe6b`: replay state table 1/1, Events SDK 11/11, legacy MCP HTTP 101/101, real Reqwest JSON/SSE and push-only loopback 2/2, strict Rustdoc and the public doctest 1/1, plus the official JSON smoke. Both affected crates passed format checks. Hosted gates are separate. The ordinary pre-push hook passed in full: selected server format, strict Clippy and tests, and SDK format, strict Clippy, all tests and strict docs. ### Signed-out desktop regression This is a regression of the existing gateway and desktop behavior, not an Events test. The signed-out harness uses a scripted agent and does not contact live providers. Reproduce with `pnpm run test:e2e:scripted -- --channel bundled --evidence target/mcp-events-1428-scripted`. The evidence directory is produced locally; no screenshots or raw logs were uploaded. Verdict: pass | Check | Chromium | WebKit | | --- | --- | --- | | resize-observers | pass | pass | | mcp-apps-gateway | pass | pass | | gateway-window | pass | pass | | scripted-scenarios | pass | pass | | parent-stop | pass | pass | Relevant log lines: - console chromium: requestfailed: http://127.0.0.1:59125/browser/check net::ERR_ABORTED (aborted after a 204 response, #485) (harmless) --------- Co-authored-by: Codex <codex@openai.com>
…ges, bounded fan-out, gap signalling Client: - A first exchange still refuses any auth-seam error; once subscribed, only a final auth failure (UnauthorizedError, SdkError, an OAuthError other than server_error, temporarily_unavailable or too_many_requests, or an OAuth client-flow error) ends a subscription, and any other is retried and reported like a transport failure. - An events/stream that ends without an error before its first valid active is a failure, as the no-active timeout is: the first stream falls back to poll where allowed, a reopen is retried and reported. - maxAgeMs is sent until the first replay is known complete: the cursor moves off the subscribed one, a push heartbeat or a poll result arrives, or the first webhook refresh succeeds. - A poll answered hasMore with no events waits the floor instead of polling again at once. - onGap is described as receiving the cursor delivery continues from. Server: - A push stream ends when its unread backlog has stayed above 1 MiB for a heartbeat interval, or at once above 8 MiB. - Webhook records store the arguments as the client sent them; check, match and onUnsubscribe get the inputSchema output, parsed on read, and a parse failure is reported and skipped. - Emits of a type that queue behind a webhook listing share one pass, capped at 10 000 events: past it the oldest are dropped, reported at most once a minute per type, and every subscription that pass lists gets a gap. A type without webhook delivery lists nothing, and a subscribe closes the pending pass. - A gap mark clears only when the gap envelope gets a 2xx, or a refresh carries the watermark the last truncated answer gave; until then every refresh answers truncated: true and the envelope goes after the next acknowledged delivery. - Targeted events are documented as reaching only a live subscription; a push reconnect or a lapsed poll lease starts a new one. - SEP-3415 is Final and the Events spec is at Beta: the error codes are no longer called provisional, and the guides link the ext-events spec.
|
@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 (4):
- 🔴
packages/server/src/ext/events/push.ts:109—Apps that subscribe with maxAgeMs to a check event type can now receive events older than that limit after a push strea… - 🔴
packages/server/src/ext/events/push.ts:273—Push subscribers silently lose targeted events across a stream reconnect, while poll and webhook subscribers keep them.… - Also unresolved: 1 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.
…ure, maxAgeMs floor, gap and watermark edges
Server:
- emit() broadcasts only: targeted emit (`emit(event, { subscriptionId })`) is removed, so no targeted event can be lost across a push reconnect or a lapsed poll lease; an event meant for one subscriber is routed with `match` on the subscription's arguments or `ctx.principal`. `ctx.subscriptionId` stays for the hooks and `terminate`.
- A push stream hands its next message to the response only while its client has at most 1 MiB unread. A stream whose client stays over that for a heartbeat interval, an emit-only stream with more live events waiting than `emitBuffer.maxEvents`, or a stream that ends while its client is more than 1 MiB behind, is abandoned: the response body is errored so the unread bytes are dropped, and the subscription ends. A check stream runs its next check only once its last batch has been written to the transport.
- A push stream or webhook check loop started from a cursor with `maxAgeMs` applies that floor to every later check run.
- `registerEvent` and `update()` reject a `payloadSchema` whose JSON Schema root is not an object.
- An event that cannot be serialised is dropped and reported to onerror in every mode.
- Webhook gaps: marks are a running total, an acknowledged gap envelope clears only the marks its body covered, a refresh clears only with an unambiguous proof, and a gap envelope is built from the current watermark at each attempt and starts only when no event POST is in flight.
- The webhook watermark follows emits a subscription did not select, after fan-out and after a create's replay, once nothing is pending.
Client:
- `maxAgeMs` is a fixed floor taken when subscribe() is called with a cursor: every request of the subscription sends the time since that floor, across a push-to-poll fallback.
- A poll answered `hasMore` re-polls at once when the page carried events or moved the cursor without `truncated`, and waits the floor otherwise.
Node:
- toNodeHandler destroys the response and its socket when the response body errors, and cancels the body when a write throws.
Docs and comments: the header-validation JSDoc names the events/* methods and extension-registered lookups, and the replica gap bullet states the clearing rule.
|
@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 (2):
- Unresolved: 1 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.
…bounded verification state, per-caller webhook listing Client: - A subscription holds at most 1 000 events its loop has not taken. Poll waits for room before the next request; push closes its stream at a cursor change and reopens from the last cursor once the loop has drained to half; the webhook receiver answers 503 to a delivery for a full subscription so the server retries it. A type without replay drops its oldest queued event on push and reports it once per episode through onGap(null). - notifications/events/error frames on a push stream are reported through the subscription's throttled retry report, as poll reports the same failure. - Poll calls onGap once per run of consecutive truncated results. Server: - Push and webhook check runs pass ctx.maxEvents 100 and run the next page at once after a page with more waiting that moved on (push once the batch reached the transport, webhook once the engine has settled the subscription's messages), and report truncation once per run of truncated pages. - The emit-only waiting-frame cap applies only while a push stream's client is blocked, so a burst of concurrent emits reaches a reading client in full. - delivery.url is limited to 2 048 characters, and remembered verification state drops expired entries on every insert. - events/list leaves webhook out for a caller without a principal, and omits a type that would then offer no mode. - When a maxAgeMs floor applies and a check event has no timestamp, it is delivered and reported to onerror at most once a minute per type; the guide's check sets timestamp and pages by ctx.maxEvents. - Internal symbols use one-line comments instead of JSDoc. Node: - toNodeHandler is unchanged from before the fifth round; its changeset entry is removed.
|
@claude review |
…ion limits, restart gaps, poll and webhook edges Server: - Subscription arguments are limited to 65 536 characters of canonical JSON in every mode, refused with invalidParams before any state is made, and poll leases are keyed by a digest of principal, name and arguments. - A host's verification window (10 per minute) gets per-principal limits: at most 3 failed verifications per principal per window, and at most 3 of a principal's verifications waiting or in flight at once. - A poll from an evicted cursor of this emit buffer gets the events from the oldest retained position with truncated: true in one exchange; a cursor of another buffer still gets the empty answer. - A process reports a gap for an emit-only webhook subscription created before it started: truncated: true on the first refresh it answers when its buffer cannot serve the client's cursor (and on a retry with that cursor), or a gap envelope after its first acknowledged delivery, whichever comes first. Client: - A poll truncation run continues only through truncated pages with hasMore, so separate losses each call onGap. - A notFound while the type is still listed is reported, and a second one in a row ends the subscription. - A shared webhook subscription answers 503 only when every member is full; a full member drops its oldest event and reports onGap once per episode. - A type without replay reports onGap(null) once per episode when a full queue stops taking events, in poll and webhook as in push. - A method-not-found sent as HTTP 404 with a -32601 body ends a subscription. - The poll interval JSDoc names the hasMore exception.
|
@claude review |
| if (watched === undefined) { | ||
| watched = this.#watch(record.id, entry, record.principal, args); | ||
| watched.position = from; | ||
| watched.floor = floor; | ||
| this.#watched.set(record.id, watched); | ||
| if (entry.kind === 'check') this.#schedule(watched); |
There was a problem hiding this comment.
🔴 After a restart over a durable webhookStore, webhook subscriptions whose onSubscribe set up in-process state keep running without it, and can deliver nothing. #keep (webhookSubscriptions.ts:488-493) starts a watch and the check loop on a refresh without calling onSubscribe; only #create calls it (:344). Client refreshes keep the record alive, so no create follows. Fix: what onSubscribe sets up must exist wherever the subscription is served: run the hooks in a process that takes one over, or say in types.ts:99 and docs/servers/events.md:186 that they run only where it was created.
Why this was flagged
Condition: a webhookStore that outlives the process or is shared by replicas (docs/servers/events.md:186, :192), and an event type whose onSubscribe builds in-process state that its emit() source, match or check needs, such as an upstream watcher per subscription. After a restart the SDK client's next refresh finds the stored record (webhookSubscriptions.ts:229-232) and runs #refresh. #keep makes a new watch and schedules check (:488-493), and #deliverTo runs match for unwatched records (:657-662), but onSubscribe is called only in #create (:344). The client refreshes at ¾ of every grant (packages/client/src/ext/events/webhook.ts:18, :286), so the record never lapses and #create never runs again. The watcher is never rebuilt: the subscriber gets no events and no error. The base branch has no Events. The earlier restart fix restarted the check loop on refresh and did not add the hook. No test covers a hook after a restart. Nothing was run.
Verification: Triggers when a webhookStore outlives the process (or is shared by replicas) and the event type's onSubscribe builds in-process state that delivery depends on; the new process serves the stored subscription without ever running the hook. Nothing was run; this is from reading the code. Events is new in this PR, so the base has no such path.
Finding ID: f-bd8e5203
| const record = await this.#deps.store.get(id); | ||
| if (this.#watched.get(id) !== watched) return; | ||
| if (record === undefined || isExpired(record)) { | ||
| // The expiry path decides; it stops this loop unless the record was refreshed meanwhile. | ||
| this.#later(id, () => this.#recheck(id)); | ||
| } else { | ||
| const maxAgeMs = maxAgeSince(watched.floor); | ||
| const ctx = makeContext({ ...watched.ctx, maxEvents: DEFAULT_MAX_EVENTS, maxAgeMs }); | ||
| const result = await entry.definition.check!(ctx, watched.args, from); | ||
| const batch = await checkedBatch(entry, from, result, maxAgeMs, this.#deps.report); | ||
| if (this.#watched.get(id) !== watched) return; | ||
| this.#send(record, batch, from); |
There was a problem hiding this comment.
🔴 Webhook subscribers of a check type can silently lose a whole batch of events when one check() call outlasts the rest of the grant. #check reads the record before check() and hands that copy to the engine afterwards (webhookSubscriptions.ts:736). Once its expiresAt has passed, #try calls forget, although a refresh already extended the stored record (webhookEngine.ts:761). Fix: judge expiry on the store's current record, for example read it again after check() returns. The SDK client refreshes at ¾ of the grant, so a check() over a quarter of webhookTtlMs triggers it.
Why this was flagged
Condition: webhookTtlMs is short (60_000, the floor at webhookSubscriptions.ts:22) and one check call of a webhook subscription takes over 15 s, for example on a slow upstream. #check reads record at webhookSubscriptions.ts:725, awaits check at :733 and calls this.#send(record, batch, from) at :736. The SDK client refreshes at ¾ of the grant, and #refresh stores a new object (webhookSubscriptions.ts:451-453), so the copy #check holds keeps the old expiresAt. record.expiresAt <= this.#now() is true at webhookEngine.ts:761, so :762 runs this.forget(tracked.id) and returns without a POST, once per event of the batch. watched.position = batch.position (webhookSubscriptions.ts:741) then moves past those events. The dropped state held the watermark and any gap mark, so the next refresh answers truncated: false, and onGap never runs. Events is new, so the base has no such path. The guard at webhookSubscriptions.ts:735 only checks that the watch is unchanged, which a refresh keeps.
Verification: Triggers when one check() call of a webhook subscription is still running while the client refreshes and returns after the pre-refresh expiresAt. In #try, webhookEngine.ts:758 uses the supplied stale copy, so there is no store read, and :761-763 runs forget. No guard found on this path. Events is new in this PR, so the base has no such path.
Finding ID: f-9d908460
| this.#onerror = options.onerror; | ||
| this.#watches = options.watches ?? (() => false); | ||
| this.#now = options.now ?? (() => Date.now()); | ||
| this.#startedAt = this.#now(); |
There was a problem hiding this comment.
🔴 On Cloudflare Workers, webhook subscribers get no gap report for events lost in a restart when the new isolate delivers before the next refresh. The engine reads its start time in the constructor (webhookEngine.ts:278). Workers return 0 from Date.now() at module scope, where the extension is built. record.createdAt < this.#startedAt (webhookEngine.ts:612) is then never true. Fix: take the start time at the engine's first use inside a request, as #lifetime is, so records created before this process first ran compare as older. Not run; the Workers clock is not in this checkout.
Why this was flagged
Condition: an EventsExtension with webhook delivery built at module scope on Cloudflare Workers, with a webhookStore that outlives the isolate, and an emit() on a new isolate before the subscription's next refresh. Nothing was run, and that Workers return 0 from Date.now() outside a request is a platform fact this checkout does not hold. The WebhookSubscriptions constructor builds the engine, which runs this.#startedAt = this.#now() (webhookEngine.ts:278), so #startedAt is 0. #trackedFor makes the restart mark only when record.createdAt < this.#startedAt (webhookEngine.ts:612), which is then never true, so no gap POST follows the first delivery. That delivery moves the client's cursor to the new buffer epoch, so at the next refresh buffer.serves is true and first is false (webhookSubscriptions.ts:462-466), and the answer is truncated: false. onGap never runs for what the old isolate had not delivered; on Node the mark is made. The base has no Events.
Verification: The start time is taken in the constructor (packages/server/src/ext/events/webhookEngine.ts:277-278). The restart mark is gated on if (record.createdAt < this.#startedAt) (webhookEngine.ts:612). With #startedAt === 0 this is never true. The refresh answers truncated: false, and the loss is never reported. The whole file is new in this diff, so the base has no such path.
Finding ID: f-410873ae
|
|
||
| // Reads the record again: gone ends what this process runs for it, a later expiry re-arms the timer, a passed one expires it. | ||
| async #recheck(id: string): Promise<void> { | ||
| const record = await this.#deps.store.get(id); |
There was a problem hiding this comment.
🔴 With a remote webhookStore, one failed store call when a webhook subscription expires leaves its watch in memory for good. It keeps a maxSubscriptions slot and onUnsubscribe never runs. The expiry timer runs #recheck once (webhookSubscriptions.ts:508). When store.get (:526) or store.delete (:541) rejects, #later only reports it and nothing arms the timer again. Fix: after a failed recheck or expire, arm the expiry timer again, as the engine's #sweep does with SWEEP_RETRY_MS, so every watch ends. An emit-only type has no check loop to retry for it.
Why this was flagged
Condition: webhookStore is a remote store whose calls can reject, the event type is emit-only, and a subscription lapses (its client stopped refreshing) while the store is unreachable. #arm sets one timer that queues #recheck (webhookSubscriptions.ts:505-509). #recheck awaits this.#deps.store.get(id) (:526) and #expire awaits store.delete (:541) before #release. A rejection goes to .catch(report) in #later (:513) and the timer is not set again. The entry stays in #watched, which size and countOf count (:191-201), so assertCapacity (validation.ts:77-90) charges it to the process and to the principal's quarter until restart. #unsubscribed never runs for it. Only a later subscribe for the same id, or a fan-out pass that still lists the expired record (:638-640), clears it. A check type recovers through its loop (:727-729). The default in-memory store never rejects. Events is new, so the base has no such path. Nothing was run.
Verification: Nothing was run; this is from reading the code. #recheck awaits this.#deps.store.get(id) (:526) with no try/catch. #later (:512-514) is enqueue(...).catch(error => this.#deps.report(error)). A rejection is only reported; #arm is not called again and watched.expiry has already fired. The entry therefore stays in #watched.
Finding ID: f-6e454ebc
| mode: 'poll' as const, | ||
| signal: ctx.mcpReq.signal | ||
| }; | ||
| const maxEvents = params.maxEvents ?? DEFAULT_MAX_EVENTS; |
There was a problem hiding this comment.
🔴 Any poll caller can make the server build one response holding a whole event backlog, where push and webhook get 100 events at a time. handlePoll takes the caller's maxEvents as the page size with no server limit (poll.ts:187). The wire schema only requires an integer of at least 1. Fix: clamp the requested maxEvents to a server-side page limit (the default 100 or a new option) before the buffer read and before check, and report the rest through hasMore.
Why this was flagged
A caller sends one small events/poll with an old or zero-position cursor and maxEvents: 9007199254740991; nothing was run. PollEventsRequestParams accepts it: packages/core/src/ext/events/schemas.ts:126 is z.number().int().min(1).optional(). poll.ts:187 uses the value unchanged. For an emit-only type EmitBuffer.read loops until events.length < options.maxEvents fails (emitBuffer.ts:97), so the page is the whole ring, 10 000 events by default and more when emitBuffer.maxEvents is raised; poll.ts:197 then runs checkedSelection for all of them at once. For a check type the value becomes ctx.maxEvents (poll.ts:202), and the guide's own check slices from + (ctx.maxEvents ?? changes.length) (docs/servers/events.md:29), so the whole upstream is validated one by one (poll.ts:86-100) and serialised into one result. Push and webhook pin 100 (push.ts:380, webhookSubscriptions.ts:732). assertCapacity counts leases, not requests, so repeats on one lease are free. The base has no Events. Remedy: cap the page server-side.
Verification: When any caller sends events/poll with a very large maxEvents and a cursor at or before the oldest retained position. packages/server/src/ext/events/poll.ts:187 is const maxEvents = params.maxEvents ?? DEFAULT_MAX_EVENTS;, with no clamp. So one request returns the whole ring. No guard exists on any path. Events is new in this diff, so the base has no such path.
Finding ID: f-6a97dc16
| ): Promise<EventOccurrence | undefined> { | ||
| if (entry.definition.transform === undefined) return occurrence; | ||
| try { | ||
| const parsed = await entry.parsePayload(occurrence.data); |
There was a problem hiding this comment.
🟡 (optional) Subscribers of an emit-only type with a transform hook get no events, or silently altered data, when its payloadSchema output differs from its input. checkedSelection runs entry.parsePayload on the hook's result (poll.ts:139), but that data is already the schema's output: the emit was parsed once in toOccurrence. Fix: do not run the schema's own transforms a second time on already-parsed data; check a hook's result against the output JSON Schema only, or skip the re-parse and keep the serialisation check.
Why this was flagged
An author registers emitOnly: true with payloadSchema: z.object({ amount: z.string().transform(Number) }) (or z.number().transform(d => d * 100)) and a per-subscription transform hook; nothing was run. emit() parses the input once in toOccurrence and stores the output (poll.ts:52, :61). checkedSelection then calls entry.parsePayload(occurrence.data) (poll.ts:139), which is validateStandardSchema(payloadSchema, data), an input parse (registry.ts:79-82). With a type-changing schema the parse fails and every selected event is dropped for poll, push and webhook (poll.ts:141, :145); the only trace is one onerror line per event. With a non-idempotent schema the parse succeeds and the transform is applied twice (cents become cents x 100), with no report. A type without the hook is parsed once (poll.ts:137), so adding the hook changes the data. The base has no Events. No test uses a payload schema whose output differs from its input together with transform.
Verification: emit() calls toOccurrence, which runs entry.parsePayload(input.data) and stores the schema OUTPUT (packages/server/src/ext/events/poll.ts:52, :61). checkedSelection then validates the hook's result a second time whenever a hook exists (poll.ts:137-140). A failure drops the event (poll.ts:141). No guard or test covers it. Events is new in this diff, so the base has no such path.
Finding ID: f-677a7508
| let watched = this.#watched.get(record.id); | ||
| if (watched === undefined) { | ||
| watched = this.#watch(record.id, entry, record.principal, args); | ||
| watched.position = from; |
There was a problem hiding this comment.
🟡 nit (optional): Webhook subscribers can receive events from before they subscribed when check returns events for cursor: null. On a refresh with cursor: null that reaches a process not yet watching the subscription, #keep sets watched.position = from (webhookSubscriptions.ts:490) and the loop delivers what check returns for null. types.ts:120-122 says the SDK drops those events and takes only the cursor. Fix: start that loop through startCheck, as every other start does, so a null position takes only the returned cursor, while a type without replay still gets its later calls delivered.
Why this was flagged
Condition: a shared or durable webhookStore, a check type with replay whose check returns events when called with cursor: null (packages/server/src/ext/events/types.ts:120-122 allows it, saying the SDK drops them), and an events/subscribe without a cursor for a subscription that already has a stored record, handled by a process that does not watch it. subscribe finds the record and runs #refresh (webhookSubscriptions.ts:229-232). #keep creates the watch with position = from, here null, and schedules the loop (:488-493). #check calls check(ctx, args, null) and #send delivers every event of the result (:733-736). startCheck (push.ts:171-174), which #create and push use, and poll (poll.ts:205-207) discard those events. The receiver gets up to 100 old events once. The base branch has no Events. No test covers a null-cursor refresh on a process that does not watch. Nothing was run.
Verification: Nothing was run; this is from reading the code. #keep on an unwatched id sets watched.position = from and calls this.#schedule(watched) (webhookSubscriptions.ts:488-493). It never calls startCheck. No branch drops the events of a null start. Events is new in this PR, so the base has no such path.
Finding ID: f-a9785b3b
| 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. |
There was a problem hiding this comment.
🟡 nit (optional): The client guide says a request retried after the event types are listed again goes unreported, but the first such notFound now reaches onerror. #notFoundWhileOffered calls this.#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 first notFound for 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 active or 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.recover sends a notFound for a type that events/list still offers to #notFoundWhileOffered (packages/client/src/ext/events/recovery.ts:358). On the first one that method sets #notFound and calls this.#retrying(error) (recovery.ts:369-371), which calls connection.report(new Error(... failed and is retried: ...)) (recovery.ts:386). packages/client/test/ext/events/poll.test.ts:399-404 pins the onerror message "poll subscription to 'tick' failed and is retried: Not found". An app author who reads the guide does not expect an onerror call 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 notFound for an event type that the re-list still offers in the same mode. Nothing fails at runtime; the guide misstates what reaches onerror. In packages/client/src/ext/events/recovery.ts, DriverLoop.recover calls this.#notFoundWhileOffered(error) (line 358), which calls this.#retrying(error) (lines 368-372).
Finding ID: f-43db1001
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.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.