From 21f18cb4c695893f644d29ec512edf9e4d41c9df Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 23 Nov 2026 23:54:00 -0500 Subject: [PATCH 1/3] feat(everything): serve the Events extension on 2026-07-28 Serve io.modelcontextprotocol/events (SEP-3415) with poll and push delivery: events/list, events/poll and events/stream. A replayable clock-tick type (poll and push) is computed from the clock, and an emit-only custom-event (push) is raised by the new trigger-event tool through a process-wide bus. Webhook delivery is not offered: it needs an authenticated principal this server does not have. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .changeset/everything-events-extension.md | 5 + src/everything/README.md | 2 +- src/everything/__tests__/events.test.ts | 719 ++++++++++++++++++ src/everything/__tests__/harness.ts | 42 +- .../__tests__/registrations.test.ts | 1 + src/everything/__tests__/stdio.test.ts | 1 + src/everything/docs/features.md | 20 + src/everything/docs/how-it-works.md | 8 + src/everything/docs/instructions.md | 1 + src/everything/docs/startup.md | 4 +- src/everything/docs/structure.md | 6 + src/everything/server/events.ts | 670 ++++++++++++++++ src/everything/server/index.ts | 18 +- src/everything/tools/index.ts | 8 +- src/everything/tools/trigger-event.ts | 85 +++ 15 files changed, 1566 insertions(+), 24 deletions(-) create mode 100644 .changeset/everything-events-extension.md create mode 100644 src/everything/__tests__/events.test.ts create mode 100644 src/everything/server/events.ts create mode 100644 src/everything/tools/trigger-event.ts diff --git a/.changeset/everything-events-extension.md b/.changeset/everything-events-extension.md new file mode 100644 index 0000000000..facd3adb0d --- /dev/null +++ b/.changeset/everything-events-extension.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-everything": minor +--- + +Serve the Events extension (`io.modelcontextprotocol/events`, SEP-3415) on protocol version 2026-07-28: `events/list`, `events/poll` and `events/stream`, with a replayable `clock-tick` event type (poll and push) and an emit-only `custom-event` (push), raised by the new `trigger-event` tool. Webhook delivery is not offered. diff --git a/src/everything/README.md b/src/everything/README.md index 2258954702..1689bd8b74 100644 --- a/src/everything/README.md +++ b/src/everything/README.md @@ -23,7 +23,7 @@ The `get-env` tool returns the server's environment variables, but masks the val The server serves both protocol eras, over stdio and Streamable HTTP, from one process: -- **2026-07-28** clients connect with `server/discover`, send their protocol version, identity and capabilities with each request, and have no session. The server demonstrates the revision's new features for them: multi-round-trip requests (`input_required`) with `requestState`, `subscriptions/listen` change notifications, per-request log levels, cache hints (`ttlMs` / `cacheScope`), the tasks extension (`io.modelcontextprotocol/tasks`) under the `extensions` capability, and `x-mcp-header` with JSON Schema 2020-12 tool schemas. +- **2026-07-28** clients connect with `server/discover`, send their protocol version, identity and capabilities with each request, and have no session. The server demonstrates the revision's new features for them: multi-round-trip requests (`input_required`) with `requestState`, `subscriptions/listen` change notifications, per-request log levels, cache hints (`ttlMs` / `cacheScope`), the tasks (`io.modelcontextprotocol/tasks`) and events (`io.modelcontextprotocol/events`, poll and push delivery) extensions under the `extensions` capability, and `x-mcp-header` with JSON Schema 2020-12 tool schemas. - **2025-era** clients connect with the `initialize` handshake, as before. Elicitation, sampling and roots are served to them from the same multi-round-trip handlers through the SDK's legacy shim. Roots, sampling and logging are deprecated as of 2026-07-28 and stay available, labelled deprecated. [Server Features](docs/features.md) marks which era each feature belongs to. diff --git a/src/everything/__tests__/events.test.ts b/src/everything/__tests__/events.test.ts new file mode 100644 index 0000000000..7a43a2eb00 --- /dev/null +++ b/src/everything/__tests__/events.test.ts @@ -0,0 +1,719 @@ +/** + * Protocol-level tests for the Events extension (`io.modelcontextprotocol/events`, + * SEP-3415) on protocol version 2026-07-28 (#5651). + * + * The SDK client has no Events helpers, so every test drives the server with + * raw JSON-RPC through `connectRaw`, which records the notifications a push + * stream sends. The clock is faked: `clock-tick` occurrences are computed from + * it, and a push stream's heartbeat and tick timers run on it, so the tests + * step time instead of waiting for it and need no retries. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { z } from "zod"; +import { + connect, + connectRaw, + type RawSession, + type Session, +} from "./harness.js"; +import { + DEFAULT_HEARTBEAT_MS, + EVENTS_EXTENSION, + MAX_HEARTBEAT_MS, + MAX_STREAMS, + MIN_HEARTBEAT_MS, + PushStream, + RETAINED_TICKS, + SUBSCRIPTION_ID_META_KEY, + TICK_PERIOD_MS, + resetEvents, +} from "../server/events.js"; + +type Json = Record; + +/** The client declares the extension, as the spec says it MAY. */ +const CAPABILITIES = { extensions: { [EVENTS_EXTENSION]: {} } }; + +/** The tick that has just happened when each test starts. */ +const HEAD = 360_000_003; +/** Each test starts this far into the tick period after HEAD. */ +const OFFSET_MS = 2_000; + +const cursor = (tick: number) => `clock-tick:${tick}`; + +let open: Array<{ close: () => Promise }> = []; + +async function raw(): Promise { + const session = await connectRaw(CAPABILITIES); + open.push(session); + return session; +} + +async function legacy(): Promise { + const session = await connect(); + open.push(session); + return session; +} + +/** Let queued messages cross the in-memory transport. */ +const settle = () => vi.advanceTimersByTimeAsync(0); + +/** The notifications with this method, and their params. */ +function sent(session: RawSession, method: string): Json[] { + return session.notifications + .filter((n) => n.method === method) + .map((n) => n.params as Json); +} + +/** The `events/*` notifications, as `[method, params]` pairs. */ +function eventNotifications(session: RawSession): Array<[string, Json]> { + return session.notifications + .filter((n) => String(n.method).startsWith("notifications/events/")) + .map((n) => [String(n.method), n.params as Json]); +} + +/** The error of a response that must fail. */ +async function errorOf( + session: RawSession, + method: string, + params: Json = {}, +): Promise { + const response = await session.request(method, params); + expect(response.result).toBeUndefined(); + return response.error as Json; +} + +/** The text of a tools/call result. */ +function textOfCall(result: Json): string { + return (result.content as Array<{ text: string }>)[0].text; +} + +beforeEach(() => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] }); + vi.setSystemTime(HEAD * TICK_PERIOD_MS + OFFSET_MS); +}); + +afterEach(async () => { + for (const session of open.splice(0)) await session.close(); + resetEvents(); + vi.useRealTimers(); +}); + +describe("discovery", () => { + it("advertises the extension in server/discover", async () => { + const session = await raw(); + const discover = await session.result("server/discover"); + expect( + (discover.capabilities as { extensions: Json }).extensions, + ).toMatchObject({ [EVENTS_EXTENSION]: {} }); + }); + + it("lists both event types with their delivery modes and schemas", async () => { + const session = await raw(); + const list = await session.result("events/list"); + expect(list.resultType).toBe("complete"); + expect(list.nextCursor).toBeUndefined(); + const events = list.events as Json[]; + expect(events.map((e) => [e.name, e.delivery])).toEqual([ + ["clock-tick", ["poll", "push"]], + ["custom-event", ["push"]], + ]); + const [clockTick, customEvent] = events; + expect(clockTick.inputSchema).toMatchObject({ + type: "object", + properties: { + everyNth: { type: "integer", default: 1 }, + label: { type: "string" }, + }, + additionalProperties: false, + }); + expect(clockTick.payloadSchema).toMatchObject({ + type: "object", + properties: { tick: { type: "integer" }, label: { type: "string" } }, + required: ["tick"], + }); + expect(clockTick.inputSchema).not.toHaveProperty("$schema"); + expect(customEvent.inputSchema).toMatchObject({ + properties: { + minSeverity: { enum: ["info", "warning", "error"], default: "info" }, + }, + }); + expect(customEvent.payloadSchema).toMatchObject({ + required: ["message", "severity"], + }); + }); + + it("refuses an events/list cursor it never minted", async () => { + const session = await raw(); + expect( + await errorOf(session, "events/list", { cursor: "page-2" }), + ).toMatchObject({ code: -32602 }); + }); + + it("does not serve events/* to a 2025-era client (-32601)", async () => { + const session = await legacy(); + expect(session.client.getServerCapabilities()?.extensions).toBeUndefined(); + await expect( + session.client.request( + { method: "events/list", params: {} }, + z.looseObject({}), + ), + ).rejects.toMatchObject({ code: -32601 }); + }); + + it("offers no webhook delivery: events/subscribe and events/unsubscribe are not served", async () => { + const session = await raw(); + const params = { name: "clock-tick", arguments: {} }; + expect(await errorOf(session, "events/subscribe", params)).toMatchObject({ + code: -32601, + }); + expect(await errorOf(session, "events/unsubscribe", params)).toMatchObject({ + code: -32601, + }); + }); +}); + +describe("events/poll", () => { + it("bootstraps with a null cursor: no events and the current position", async () => { + const session = await raw(); + for (const params of [{ cursor: null }, {}]) { + const poll = await session.result("events/poll", { + name: "clock-tick", + ...params, + }); + expect(poll).toMatchObject({ + resultType: "complete", + events: [], + cursor: cursor(HEAD), + truncated: false, + hasMore: false, + nextPollMs: TICK_PERIOD_MS - OFFSET_MS, + }); + } + }); + + it("replays the ticks after the cursor, each with a stable eventId", async () => { + const session = await raw(); + const poll = await session.result("events/poll", { + name: "clock-tick", + cursor: cursor(HEAD - 2), + }); + expect(poll.events).toEqual([ + { + eventId: `tick-${HEAD - 1}`, + name: "clock-tick", + timestamp: new Date((HEAD - 1) * TICK_PERIOD_MS).toISOString(), + data: { tick: HEAD - 1 }, + }, + { + eventId: `tick-${HEAD}`, + name: "clock-tick", + timestamp: new Date(HEAD * TICK_PERIOD_MS).toISOString(), + data: { tick: HEAD }, + }, + ]); + expect(poll).toMatchObject({ + cursor: cursor(HEAD), + truncated: false, + hasMore: false, + }); + + // Polling again from the returned cursor finds nothing new until the + // next tick, and then exactly that tick. + const quiet = await session.result("events/poll", { + name: "clock-tick", + cursor: poll.cursor, + }); + expect(quiet.events).toEqual([]); + vi.advanceTimersByTime(TICK_PERIOD_MS); + const next = await session.result("events/poll", { + name: "clock-tick", + cursor: poll.cursor, + }); + expect((next.events as Json[]).map((e) => e.eventId)).toEqual([ + `tick-${HEAD + 1}`, + ]); + }); + + it("caps a batch at maxEvents and reports the backlog with hasMore", async () => { + const session = await raw(); + const first = await session.result("events/poll", { + name: "clock-tick", + cursor: cursor(HEAD - 5), + maxEvents: 2, + }); + expect((first.events as Json[]).map((e) => e.eventId)).toEqual([ + `tick-${HEAD - 4}`, + `tick-${HEAD - 3}`, + ]); + expect(first).toMatchObject({ + cursor: cursor(HEAD - 3), + hasMore: true, + nextPollMs: 0, + }); + + const rest = await session.result("events/poll", { + name: "clock-tick", + cursor: first.cursor, + maxEvents: 10, + }); + expect((rest.events as Json[]).map((e) => e.eventId)).toEqual([ + `tick-${HEAD - 2}`, + `tick-${HEAD - 1}`, + `tick-${HEAD}`, + ]); + expect(rest).toMatchObject({ cursor: cursor(HEAD), hasMore: false }); + }); + + it("filters with everyNth and transforms with label", async () => { + const session = await raw(); + // HEAD - 8 and HEAD - 3 are the multiples of 5 in the last ten ticks. + const poll = await session.result("events/poll", { + name: "clock-tick", + arguments: { everyNth: 5, label: "five" }, + cursor: cursor(HEAD - 10), + }); + expect(poll.events).toEqual([ + expect.objectContaining({ data: { tick: HEAD - 8, label: "five" } }), + expect.objectContaining({ data: { tick: HEAD - 3, label: "five" } }), + ]); + // The cursor advances past ticks the filter skipped. + expect(poll).toMatchObject({ cursor: cursor(HEAD), hasMore: false }); + + // hasMore counts only ticks that would be delivered. + const capped = await session.result("events/poll", { + name: "clock-tick", + arguments: { everyNth: 5 }, + cursor: cursor(HEAD - 10), + maxEvents: 1, + }); + expect(capped).toMatchObject({ cursor: cursor(HEAD - 8), hasMore: true }); + }); + + it("replays at most the retained ticks, and says it skipped some", async () => { + const session = await raw(); + const poll = await session.result("events/poll", { + name: "clock-tick", + cursor: cursor(HEAD - 500), + maxEvents: 200, + }); + const events = poll.events as Json[]; + expect(events).toHaveLength(RETAINED_TICKS); + expect(events[0].eventId).toBe(`tick-${HEAD - RETAINED_TICKS + 1}`); + expect(poll).toMatchObject({ truncated: true, hasMore: false }); + }); + + it("returns at most 100 events however large maxEvents is, and 50 by default", async () => { + const session = await raw(); + const large = await session.result("events/poll", { + name: "clock-tick", + cursor: cursor(HEAD - 150), + maxEvents: 1_000, + }); + expect(large.events as Json[]).toHaveLength(100); + const byDefault = await session.result("events/poll", { + name: "clock-tick", + cursor: cursor(HEAD - 90), + }); + expect(byDefault.events as Json[]).toHaveLength(50); + expect(byDefault.hasMore).toBe(true); + }); + + it("starts no earlier than maxAgeMs, and says so when that skips events", async () => { + const session = await raw(); + // now - 12 s falls 2 s after tick HEAD - 2's start, so replay starts there. + const poll = await session.result("events/poll", { + name: "clock-tick", + cursor: cursor(HEAD - 10), + maxAgeMs: 12_000, + }); + expect((poll.events as Json[]).map((e) => e.eventId)).toEqual([ + `tick-${HEAD - 2}`, + `tick-${HEAD - 1}`, + `tick-${HEAD}`, + ]); + expect(poll.truncated).toBe(true); + + // A floor older than the cursor skips nothing. + const wide = await session.result("events/poll", { + name: "clock-tick", + cursor: cursor(HEAD - 2), + maxAgeMs: 3_600_000, + }); + expect(wide).toMatchObject({ truncated: false }); + expect(wide.events as Json[]).toHaveLength(2); + + // maxAgeMs is ignored with a null cursor, which already means now. + const fresh = await session.result("events/poll", { + name: "clock-tick", + cursor: null, + maxAgeMs: 0, + }); + expect(fresh).toMatchObject({ events: [], truncated: false }); + }); + + it("refuses a cursor it never minted", async () => { + const session = await raw(); + for (const bad of ["garbage", cursor(HEAD + 1), "clock-tick:-1"]) { + expect( + await errorOf(session, "events/poll", { + name: "clock-tick", + cursor: bad, + }), + ).toMatchObject({ code: -32602, message: expect.stringContaining(bad) }); + } + }); + + it("answers an unknown event type with NotFound (-32023)", async () => { + const session = await raw(); + expect( + await errorOf(session, "events/poll", { name: "no-such-event" }), + ).toEqual({ + code: -32023, + message: "Unknown event type: no-such-event", + data: { kind: "event" }, + }); + }); + + it("answers a delivery mode the type does not offer with Unsupported (-32026)", async () => { + const session = await raw(); + expect( + await errorOf(session, "events/poll", { name: "custom-event" }), + ).toMatchObject({ + code: -32026, + data: { feature: "deliveryMode", value: "poll" }, + }); + }); + + it("answers arguments that do not match the inputSchema with InvalidParams", async () => { + const session = await raw(); + for (const args of [{ bogus: 1 }, { everyNth: 0 }, { label: 7 }]) { + expect( + await errorOf(session, "events/poll", { + name: "clock-tick", + arguments: args, + }), + ).toMatchObject({ code: -32602 }); + } + }); +}); + +describe("events/stream: clock-tick", () => { + it("confirms, replays, delivers each tick and heartbeats in between, all tagged with the request id", async () => { + const session = await raw(); + void session.request("events/stream", { + name: "clock-tick", + cursor: cursor(HEAD - 2), + heartbeatMs: 2_000, + arguments: { label: "push" }, + }); + const id = session.lastRequestId(); + await settle(); + + // active first, then the replayed backlog. + expect(eventNotifications(session)).toEqual([ + [ + "notifications/events/active", + { + cursor: cursor(HEAD - 2), + truncated: false, + heartbeatMs: 2_000, + _meta: { [SUBSCRIPTION_ID_META_KEY]: id }, + }, + ], + [ + "notifications/events/event", + expect.objectContaining({ + eventId: `tick-${HEAD - 1}`, + data: { tick: HEAD - 1, label: "push" }, + cursor: cursor(HEAD - 1), + _meta: { [SUBSCRIPTION_ID_META_KEY]: id }, + }), + ], + [ + "notifications/events/event", + expect.objectContaining({ + eventId: `tick-${HEAD}`, + cursor: cursor(HEAD), + }), + ], + ]); + + // 2 s of silence brings a heartbeat carrying the position checked up to. + await vi.advanceTimersByTimeAsync(2_000); + expect(sent(session, "notifications/events/heartbeat")).toEqual([ + { cursor: cursor(HEAD), _meta: { [SUBSCRIPTION_ID_META_KEY]: id } }, + ]); + + // The next tick arrives on time. + await vi.advanceTimersByTimeAsync(1_000); + expect(sent(session, "notifications/events/event").at(-1)).toMatchObject({ + eventId: `tick-${HEAD + 1}`, + cursor: cursor(HEAD + 1), + }); + }); + + it("starts from now with a null cursor, and advances the heartbeat cursor over filtered ticks", async () => { + const session = await raw(); + void session.request("events/stream", { + name: "clock-tick", + heartbeatMs: 1_000, + arguments: { everyNth: 1_000 }, + }); + await settle(); + expect(sent(session, "notifications/events/active")).toEqual([ + expect.objectContaining({ cursor: cursor(HEAD), truncated: false }), + ]); + await vi.advanceTimersByTimeAsync(TICK_PERIOD_MS * 2); + expect(sent(session, "notifications/events/event")).toEqual([]); + expect(sent(session, "notifications/events/heartbeat").at(-1)).toEqual( + expect.objectContaining({ cursor: cursor(HEAD + 2) }), + ); + }); + + it("reports a cursor outside the retained window as truncated on active", async () => { + const session = await raw(); + void session.request("events/stream", { + name: "clock-tick", + cursor: cursor(HEAD - 1_000), + }); + await settle(); + expect(sent(session, "notifications/events/active")).toEqual([ + expect.objectContaining({ + cursor: cursor(HEAD - RETAINED_TICKS), + truncated: true, + heartbeatMs: DEFAULT_HEARTBEAT_MS, + }), + ]); + expect(sent(session, "notifications/events/event")).toHaveLength( + RETAINED_TICKS, + ); + }); + + it("clamps the suggested heartbeat interval to the server's bounds", async () => { + const session = await raw(); + for (const heartbeatMs of [1, 10_000_000]) { + void session.request("events/stream", { + name: "clock-tick", + heartbeatMs, + }); + } + await settle(); + expect( + sent(session, "notifications/events/active").map((p) => p.heartbeatMs), + ).toEqual([MIN_HEARTBEAT_MS, MAX_HEARTBEAT_MS]); + }); + + it("stops delivering when the client cancels, and sends no response", async () => { + const session = await raw(); + const response = vi.fn(); + void session + .request("events/stream", { name: "clock-tick", heartbeatMs: 1_000 }) + .then(response); + const id = session.lastRequestId(); + await settle(); + await session.notify("notifications/cancelled", { requestId: id }); + await settle(); + const count = session.notifications.length; + await vi.advanceTimersByTimeAsync(TICK_PERIOD_MS * 3); + expect(session.notifications).toHaveLength(count); + expect(response).not.toHaveBeenCalled(); + }); + + it("refuses an invalid subscription with an error and opens no stream", async () => { + const session = await raw(); + expect( + await errorOf(session, "events/stream", { + name: "clock-tick", + arguments: { everyNth: "often" }, + }), + ).toMatchObject({ code: -32602 }); + expect( + await errorOf(session, "events/stream", { + name: "clock-tick", + cursor: "garbage", + }), + ).toMatchObject({ code: -32602 }); + expect( + await errorOf(session, "events/stream", { name: "nope" }), + ).toMatchObject({ code: -32023 }); + expect(eventNotifications(session)).toEqual([]); + }); +}); + +describe("events/stream: custom-event and trigger-event", () => { + it("delivers what trigger-event raises, filtered by minSeverity, with a null cursor", async () => { + const session = await raw(); + void session.request("events/stream", { + name: "custom-event", + arguments: { minSeverity: "warning" }, + heartbeatMs: 5_000, + }); + const id = session.lastRequestId(); + await settle(); + expect(sent(session, "notifications/events/active")).toEqual([ + { + cursor: null, + truncated: false, + heartbeatMs: 5_000, + _meta: { [SUBSCRIPTION_ID_META_KEY]: id }, + }, + ]); + + const info = await session.call("trigger-event", { message: "quiet" }); + expect(textOfCall(info)).toBe( + "Sent custom-event (info) to 1 open custom-event stream", + ); + await session.call("trigger-event", { + message: "loud", + severity: "warning", + }); + await settle(); + const events = sent(session, "notifications/events/event"); + expect(events).toEqual([ + { + eventId: expect.stringMatching(/^custom-[0-9a-f-]{36}$/), + name: "custom-event", + timestamp: new Date().toISOString(), + data: { message: "loud", severity: "warning" }, + cursor: null, + _meta: { [SUBSCRIPTION_ID_META_KEY]: id }, + }, + ]); + + await vi.advanceTimersByTimeAsync(5_000); + expect(sent(session, "notifications/events/heartbeat")).toEqual([ + { cursor: null, _meta: { [SUBSCRIPTION_ID_META_KEY]: id } }, + ]); + }); + + it("reaches streams opened through another connection", async () => { + const listener = await raw(); + const caller = await raw(); + void listener.request("events/stream", { name: "custom-event" }); + void listener.request("events/stream", { name: "custom-event" }); + await settle(); + const result = await caller.call("trigger-event", {}); + expect(textOfCall(result)).toBe( + "Sent custom-event (info) to 2 open custom-event streams", + ); + await settle(); + expect(sent(listener, "notifications/events/event")).toHaveLength(2); + }); + + it("sends a recoverable error and keeps the stream open", async () => { + const session = await raw(); + void session.request("events/stream", { name: "custom-event" }); + await settle(); + const result = await session.call("trigger-event", { + kind: "error", + message: "upstream 503", + }); + expect(textOfCall(result)).toBe( + "Sent notifications/events/error to 1 open custom-event stream", + ); + await settle(); + expect(sent(session, "notifications/events/error")).toEqual([ + expect.objectContaining({ + error: { + code: -32603, + message: "UpstreamError", + data: { reason: "upstream 503" }, + }, + }), + ]); + await session.call("trigger-event", {}); + await settle(); + expect(sent(session, "notifications/events/event")).toHaveLength(1); + }); + + it("terminates the subscription and ends the stream with an empty result", async () => { + const session = await raw(); + const stream = session.request("events/stream", { name: "custom-event" }); + const id = session.lastRequestId(); + await settle(); + const result = await session.call("trigger-event", { + kind: "terminate", + message: "access revoked", + }); + expect(textOfCall(result)).toBe( + "Sent notifications/events/terminated to 1 open custom-event stream", + ); + expect(sent(session, "notifications/events/terminated")).toEqual([ + { + error: { + code: -32024, + message: "Forbidden", + data: { reason: "access revoked" }, + }, + _meta: { [SUBSCRIPTION_ID_META_KEY]: id }, + }, + ]); + const response = await stream; + expect(response.result).toMatchObject({ + resultType: "complete", + _meta: { [SUBSCRIPTION_ID_META_KEY]: id }, + }); + + // The subscription is gone. + const after = await session.call("trigger-event", {}); + expect(textOfCall(after)).toBe( + "Sent custom-event (info) to 0 open custom-event streams", + ); + }); + + it("closes a connection's streams when the connection ends", async () => { + const listener = await raw(); + const caller = await raw(); + void listener.request("events/stream", { name: "custom-event" }); + await settle(); + await listener.close(); + expect(textOfCall(await caller.call("trigger-event", {}))).toBe( + "Sent custom-event (info) to 0 open custom-event streams", + ); + }); +}); + +describe("stream limit", () => { + it(`refuses stream ${MAX_STREAMS + 1} with ResourceExhausted (-32025), and frees a slot when one ends`, async () => { + const holder = await raw(); + for (let i = 0; i < MAX_STREAMS; i++) { + void holder.request("events/stream", { name: "custom-event" }); + } + await settle(); + const session = await raw(); + expect( + await errorOf(session, "events/stream", { name: "clock-tick" }), + ).toEqual({ + code: -32025, + message: `The server already has ${MAX_STREAMS} event streams open, its limit`, + data: { limit: "streams", max: MAX_STREAMS }, + }); + + await holder.close(); + void session.request("events/stream", { name: "clock-tick" }); + await settle(); + expect(sent(session, "notifications/events/active")).toHaveLength(1); + }); +}); + +describe("PushStream", () => { + it("ends when a send fails, and sends nothing after", async () => { + const notify = vi.fn().mockRejectedValue(new Error("connection gone")); + const stream = new PushStream({ id: 9, notify }, 1_000, () => null); + const released = vi.fn(); + stream.onClose(released); + stream.send("notifications/events/active", { cursor: null }); + await stream.ended(); + expect(stream.isClosed).toBe(true); + expect(released).toHaveBeenCalledOnce(); + expect(notify).toHaveBeenCalledOnce(); + + // Closed for good: no further sends, no heartbeat, no second release. + stream.send("notifications/events/event", {}); + stream.close(); + await vi.advanceTimersByTimeAsync(5_000); + expect(notify).toHaveBeenCalledOnce(); + expect(released).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/everything/__tests__/harness.ts b/src/everything/__tests__/harness.ts index baab1c4a38..461045dd05 100644 --- a/src/everything/__tests__/harness.ts +++ b/src/everything/__tests__/harness.ts @@ -19,7 +19,10 @@ * `connectRaw()` serves the same way to a raw JSON-RPC peer that puts the * 2026-07-28 envelope on each request, for what the SDK client hides or * refuses: the wire fields it consumes (`resultType`, the cache fields), a - * tampered `requestState`, and task handles. + * tampered `requestState`, task handles, and the Events extension's methods, + * which the SDK client has no helpers for. It records every notification the + * server sends and can send notifications of its own (`notifications/cancelled` + * ends an `events/stream`). * * `connectModern()` serves a 2026-07-28 client: it hands the factory to the * SDK's `serveStdio` entry over the in-memory pair, as the stdio transport @@ -207,6 +210,12 @@ export type RawSession = { call: (name: string, args?: Json) => Promise; /** The result of a `tasks/get`. */ get: (taskId: string) => Promise; + /** Send a notification, with the 2026-07-28 envelope. */ + notify: (method: string, params?: Json) => Promise; + /** Every notification the server has sent, in order. */ + notifications: Json[]; + /** The JSON-RPC id of the request sent last. */ + lastRequestId: () => number; close: () => Promise; }; @@ -226,31 +235,32 @@ export async function connectRaw(capabilities: Json): Promise { { transport: serverTransport }, ); const waiting = new Map void>(); + const notifications: Json[] = []; peer.onmessage = (message) => { if ("id" in message && typeof message.id === "number") { waiting.get(message.id)?.(message); + } else if ("method" in message) { + notifications.push({ ...message }); } }; await peer.start(); let nextId = 1; + const envelope = (params: Json): Json => ({ + ...params, + _meta: { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientCapabilities": capabilities, + ...(params._meta as Json | undefined), + }, + }); const request = (method: string, params: Json = {}) => { const id = nextId++; return new Promise((resolve) => { waiting.set(id, (m) => resolve({ ...m })); - void peer.send({ - jsonrpc: "2.0", - id, - method, - params: { - ...params, - _meta: { - "io.modelcontextprotocol/protocolVersion": "2026-07-28", - "io.modelcontextprotocol/clientCapabilities": capabilities, - ...(params._meta as Json | undefined), - }, - }, - }); + // The in-memory send settles at once; a failure surfaces as the + // response never arriving, which fails the awaiting test. + void peer.send({ jsonrpc: "2.0", id, method, params: envelope(params) }); }); }; const result = async (method: string, params: Json = {}) => { @@ -263,6 +273,10 @@ export async function connectRaw(capabilities: Json): Promise { result, call: (name, args = {}) => result("tools/call", { name, arguments: args }), get: (taskId) => result("tasks/get", { taskId }), + notify: (method, params = {}) => + peer.send({ jsonrpc: "2.0", method, params: envelope(params) }), + notifications, + lastRequestId: () => nextId - 1, close: async () => { await handle.close(); for (const cleanup of cleanups) cleanup(); diff --git a/src/everything/__tests__/registrations.test.ts b/src/everything/__tests__/registrations.test.ts index 463632df63..855eb7e704 100644 --- a/src/everything/__tests__/registrations.test.ts +++ b/src/everything/__tests__/registrations.test.ts @@ -105,6 +105,7 @@ describe("Registration Index Files", () => { "simulate-research-query", "trigger-sampling-request-async", "trigger-elicitation-request-async", + "trigger-event", ]); }); diff --git a/src/everything/__tests__/stdio.test.ts b/src/everything/__tests__/stdio.test.ts index d6889d9a34..c746100b93 100644 --- a/src/everything/__tests__/stdio.test.ts +++ b/src/everything/__tests__/stdio.test.ts @@ -66,6 +66,7 @@ describe("stdio transport", () => { expect(client.getProtocolEra()).toBe("modern"); expect(client.getServerCapabilities()?.extensions).toEqual({ "io.modelcontextprotocol/tasks": {}, + "io.modelcontextprotocol/events": {}, }); const result = await client.callTool({ name: "echo", diff --git a/src/everything/docs/features.md b/src/everything/docs/features.md index 9b0474b53c..35a1f65263 100644 --- a/src/everything/docs/features.md +++ b/src/everything/docs/features.md @@ -24,6 +24,7 @@ Each feature below is marked **both**, **2026-07-28** or **2025-era**. Roots, sa | Change notifications | on a `subscriptions/listen` stream the client opened | unsolicited, or after `resources/subscribe` | | Log level | per request, `_meta` `io.modelcontextprotocol/logLevel` (none named: no logs) | per session, `logging/setLevel` | | Tasks | the `io.modelcontextprotocol/tasks` extension | not served | +| Events | the `io.modelcontextprotocol/events` extension (poll and push) | not served (`-32601`) | | Cache hints | `ttlMs` / `cacheScope` on lists, reads and `server/discover` | not sent | | `x-mcp-header` | mirrored into `Mcp-Param-*` headers over Streamable HTTP | not mirrored | @@ -47,6 +48,7 @@ Each feature below is marked **both**, **2026-07-28** or **2025-era**. Roots, sa - `trigger-elicitation-request-async` (tools/trigger-elicitation-request-async.ts), **2026-07-28**: Runs as a task whose `input_required` status carries a form elicitation; the client answers with `tasks/update` and the task completes with a summary. Needs a client that declares the tasks extension and form-mode elicitation. - `trigger-list-changed` (tools/trigger-list-changed.ts), **both**: Sends `notifications//list_changed` for `tools`, `prompts` or `resources`: on 2026-07-28 to each `subscriptions/listen` stream that asked for that list, on a 2025-era connection unsolicited. - `trigger-log-messages` (tools/trigger-log-messages.ts), **both**, deprecated: Sends one log message at each level during the call. A 2026-07-28 request gets those at or above the level its `_meta` names (none if it names none); a 2025-era client those at or above its `logging/setLevel` level. +- `trigger-event` (tools/trigger-event.ts), **2026-07-28**: Raises the events extension's `custom-event` on every open `events/stream` subscribed to it, with a `message` and a `severity` (`info`, `warning` or `error`) each stream filters by its `minSeverity`. With `kind: "error"` it sends a recoverable `notifications/events/error` instead and the streams stay open; with `kind: "terminate"` it sends `notifications/events/terminated` (`-32024` Forbidden) and ends them. Reports how many streams it reached. - `trigger-long-running-operation` (tools/trigger-long-running-operation.ts), **both**: Simulates a multi-step operation over a given `duration` and number of `steps`; reports progress via `notifications/progress` when a `progressToken` is provided by the client. Honors cancellation: a cancelled call clears its timer and sends no further progress. - `trigger-multi-step-elicitation` (tools/trigger-multi-step-elicitation.ts), **both**: Asks for a name, then for a favorite color addressed by that name, carrying the first answer to the second round in `requestState`. The state is HMAC-signed and expires after ten minutes; a tampered or expired one is refused with `-32602`. A blank name or a color that is not a choice is asked again. Needs form-mode elicitation. - `trigger-resource-update` (tools/trigger-resource-update.ts), **both**: Sends `notifications/resources/updated` for a URI: on 2026-07-28 to each listen stream whose `resourceSubscriptions` name it, on a 2025-era connection once the client has subscribed to it. @@ -102,3 +104,21 @@ Logging is deprecated as of 2026-07-28 (SEP-2577) and remains available on both A task tool called by a client whose request does not declare the extension, or the capability its task asks for input with (`sampling` for `trigger-sampling-request-async`, form-mode `elicitation` for `trigger-elicitation-request-async`), is refused with `-32021` (missing required client capability), naming what is missing in `data.requiredCapabilities`; so is a `tasks/*` request from a client without the extension. An unknown or expired task, and a `tasks/update` whose answers exceed 64 KiB serialized (counted in UTF-8 bytes), are refused with `-32602`. A `tasks/cancel` is acknowledged whatever the task's status (cancellation is cooperative), and a finished task stays as it ended. An update's answers to requests that are not outstanding (never issued, already answered, or sent while the task is not waiting for input) are ignored, as the extension asks. Each input request a task makes has its own key, never reused once answered, so a request asked again after an answer that does not fit gets a new key (`form-2`, `sampling-2`). The process keeps at most 100 tasks, each until its TTL; at that limit a new task is refused with a tool error. The task id is a server-minted UUID, so a task lives across requests (each 2026-07-28 HTTP request is served by a fresh server instance) and is reached only through its handle. A task's progress is computed from the clock when it is read, so nothing runs in the background. The 2025-11-25 core task methods (`tasks/result`, `tasks/list`, task-augmented requests) are not served: SDK v2 removed the experimental layer they were built on. + +## Events + +**2026-07-28.** The server implements the server side of the [events extension](https://github.com/modelcontextprotocol/ext-events/blob/main/specification/beta/events/events.mdx) (`io.modelcontextprotocol/events`, SEP-3415, Beta), advertised under `capabilities.extensions` in `server/discover` with no `listChanged`, since its event types never change. A client lists the event types with `events/list` and receives their occurrences (`{eventId, name, timestamp, data, cursor}`) by poll or push. Two synthetic event types cover the extension's two cursor models: + +| Event type | Delivery | Cursor | Arguments | Payload | +| --- | --- | --- | --- | --- | +| `clock-tick` | `poll`, `push` | replayable: `clock-tick:`; the last 100 ticks can be replayed | `everyNth` (filter, default 1), `label` (copied into the payload) | `tick`, `label` | +| `custom-event` | `push` | always `null`: emit-only, no history | `minSeverity` (filter: `info`, `warning` or `error`) | `message`, `severity` | + +`clock-tick` fires every 5 seconds: tick *k* happens at *k* × 5 s since the Unix epoch, so every occurrence is computed from the clock and its `eventId` (`tick-`) is the same on every subscription and every replay. `custom-event` fires when the `trigger-event` tool is called, through a process-wide bus, so a stream opened through one connection (or one HTTP request) sees an event raised through another. + +- `events/poll` (`clock-tick` only): a `null` or absent cursor starts from now (no events, the current cursor). A cursor replays the ticks after it, at most `maxEvents` (default 50, at most 100) at a time, with `hasMore: true` and `nextPollMs: 0` while a backlog remains; otherwise `nextPollMs` is the time to the next tick (at least 1 s). Replay starts no earlier than `now - maxAgeMs` or the oldest retained tick, and `truncated: true` says when either skipped events. +- `events/stream`: one long-lived request per subscription. It sends `notifications/events/active` first (the starting cursor, `truncated`, and the granted `heartbeatMs`: the client's suggestion clamped to 1–60 s, 30 s by default), then the replayed backlog and each new occurrence as `notifications/events/event`, and `notifications/events/heartbeat` with the cursor checked up to whenever the granted interval passes without another message. Every notification carries the request's id in `_meta["io.modelcontextprotocol/subscriptionId"]`. Cancelling the request (`notifications/cancelled` on stdio, closing the HTTP response) ends the stream and releases its timers; when the server ends it (after `trigger-event` terminates it) the request answers with an empty result. The process holds at most 100 streams; past that a new one is refused with `-32025` (ResourceExhausted). +- Errors: an unknown event type is `-32023` (NotFound, `data.kind: "event"`); a delivery mode the type does not offer (polling `custom-event`) is `-32026` (Unsupported, `data: {feature: "deliveryMode", value}`); arguments that do not match the type's `inputSchema`, or a cursor the server never minted, are `-32602`. An invalid subscription gets its error before any stream opens. +- Webhook delivery is not offered: the extension requires an authenticated principal for `events/subscribe` and `events/unsubscribe`, and this server has none, so both answer `-32601`. + +Over Streamable HTTP the extension asks clients to send `Mcp-Name: ` on `events/poll` and `events/stream`. The SDK's server checks that header only for the core methods and `tasks/*` today, so a mismatched `Mcp-Name` on an `events/*` request is not refused yet. diff --git a/src/everything/docs/how-it-works.md b/src/everything/docs/how-it-works.md index 6059ac215d..542c843012 100644 --- a/src/everything/docs/how-it-works.md +++ b/src/everything/docs/how-it-works.md @@ -35,6 +35,14 @@ - Serves the tasks extension (`io.modelcontextprotocol/tasks`) on 2026-07-28: `tasks/get`, `tasks/update` and `tasks/cancel`, with explicit schemas. - `createTask(behavior, options)` stores a task under a minted UUID and returns the `tools/call` result that hands its handle to the client (`resultType: "task"`). A task's `behavior` works out its state from the clock (`stateAt`) and takes the client's answers (`receive`), so nothing runs in the background. Tasks past their TTL are dropped when the store is next touched. +# Events + +### Module: `server/events.ts` + +- Serves the events extension (`io.modelcontextprotocol/events`) on 2026-07-28: `events/list`, `events/poll` and `events/stream`, with explicit schemas. Webhook delivery is not offered. +- `clock-tick` is computed from the clock (tick *k* at *k* × 5 s), so a poll or a replaying stream needs no stored history. `custom-event` is raised by `trigger-event` through `emitCustomEvent`, a process-wide bus every open `custom-event` stream listens on. +- A `PushStream` sends one stream's notifications in order, tagged with the request id, re-arms the heartbeat after each, and ends on cancellation, on termination, on a failed send, or when its server instance is cleaned up. + ## Resource Subscriptions ### Module: `resources/subscriptions.ts` diff --git a/src/everything/docs/instructions.md b/src/everything/docs/instructions.md index 5c853824d7..ca5ca6bbba 100644 --- a/src/everything/docs/instructions.md +++ b/src/everything/docs/instructions.md @@ -8,6 +8,7 @@ Follow them to use, extend, and troubleshoot the server safely and effectively. The server serves two protocol eras. A client on protocol version 2026-07-28 connects with `server/discover` and sends its capabilities with each request; a 2025-era client connects with `initialize`. Some tools exist on one era only, so trust your `tools/list`: - 2026-07-28 only: `simulate-research-query`, `trigger-sampling-request-async` and `trigger-elicitation-request-async`, which run as tasks on the `io.modelcontextprotocol/tasks` extension and need a client that declares it; `trigger-sampling-request-async` also needs `sampling`, and `trigger-elicitation-request-async` form-mode `elicitation`. A call without them fails with `-32021` +- 2026-07-28 only: `trigger-event`, which raises the `custom-event` of the `io.modelcontextprotocol/events` extension on open `events/stream` subscriptions - 2025-era only (deprecated): `toggle-simulated-logging` and `toggle-subscriber-updates` ## Cross-Feature Relationships diff --git a/src/everything/docs/startup.md b/src/everything/docs/startup.md index bc0f6ba40a..f35f348b84 100644 --- a/src/everything/docs/startup.md +++ b/src/everything/docs/startup.md @@ -49,7 +49,7 @@ - `logging: {}` - `prompts: { listChanged: true }` - `resources: { subscribe: true, listChanged: true }` - - `extensions: { "io.modelcontextprotocol/tasks": {} }` (2026-07-28 only) + - `extensions: { "io.modelcontextprotocol/tasks": {}, "io.modelcontextprotocol/events": {} }` (2026-07-28 only) - **Server Instructions** - Loaded from the docs folder (`instructions.md`). - **Options** @@ -57,7 +57,7 @@ - The `requestState` verifier for multi-round tools (`roundStateCodec`). - **Registrations** - Builds a per-instance **context** (`server/context.ts`): the era, where change notifications go, the 2025-era resource subscriptions, and a cleanup registry. - - Registers **tools** via `registerTools(server, context)`, and then by era: `registerModernTools` and the tasks extension (`server/tasks.ts`) for 2026-07-28; `registerLegacyTools` now and `registerConditionalTools` once the client has initialized, for the 2025 era. + - Registers **tools** via `registerTools(server, context)`, and then by era: `registerModernTools` and the tasks and events extensions (`server/tasks.ts`, `server/events.ts`) for 2026-07-28; `registerLegacyTools` now and `registerConditionalTools` once the client has initialized, for the 2025 era. - Registers **resources** via `registerResources(server, context)`. - Registers **prompts** via `registerPrompts(server)`. - **Other Request Handlers** (2025 era) diff --git a/src/everything/docs/structure.md b/src/everything/docs/structure.md index a8a3601f4e..20f2317522 100644 --- a/src/everything/docs/structure.md +++ b/src/everything/docs/structure.md @@ -37,6 +37,7 @@ src/everything ├── server │ ├── index.ts │ ├── context.ts + │ ├── events.ts │ ├── icons.ts │ ├── logging.ts │ ├── roots.ts @@ -59,6 +60,7 @@ src/everything │ ├── toggle-subscriber-updates.ts │ ├── trigger-elicitation-request-async.ts │ ├── trigger-elicitation-request.ts + │ ├── trigger-event.ts │ ├── trigger-list-changed.ts │ ├── trigger-log-messages.ts │ ├── trigger-long-running-operation.ts @@ -157,6 +159,8 @@ src/everything - Exposes `{ server, cleanup }` to the chosen transport. Cleanup stops any running intervals in the server when the connection ends. - `context.ts` - The per-instance context features receive: the era, the change publisher, the 2025-era subscriptions and a cleanup registry. +- `events.ts` + - 2026-07-28: the server side of the events extension (`events/list`, `events/poll`, `events/stream`), its two event types (`clock-tick`, `custom-event`) and the process-wide bus `trigger-event` raises `custom-event` on. - `icons.ts` - The light- and dark-themed icon pairs (SEP-973) attached to the server info and to every tool, prompt, resource and resource template, one pair per kind, as inline SVG `data:` URIs. - `logging.ts` @@ -202,6 +206,8 @@ src/everything - 2026-07-28: registers a `trigger-elicitation-request-async` tool that runs as a task waiting in `input_required` for a form elicitation. - `trigger-list-changed.ts` - Registers a `trigger-list-changed` tool that publishes a tools, prompts or resources list change. +- `trigger-event.ts` + - 2026-07-28: registers a `trigger-event` tool that raises `custom-event` on the open `events/stream` subscriptions, or sends them a recoverable error or a termination. - `trigger-log-messages.ts` - Registers a `trigger-log-messages` tool that sends one log message per level, filtered by the request's or session's log level. - `trigger-multi-step-elicitation.ts` diff --git a/src/everything/server/events.ts b/src/everything/server/events.ts new file mode 100644 index 0000000000..384377cbfe --- /dev/null +++ b/src/everything/server/events.ts @@ -0,0 +1,670 @@ +// The server side of the Events extension (`io.modelcontextprotocol/events`, +// SEP-3415) on the 2026-07-28 revision (#5651). +// +// A client lists the server's event types with `events/list`, then receives +// their occurrences by polling (`events/poll`) or over a long-lived push +// stream (`events/stream`). The SDK has no server implementation of the +// extension yet (modelcontextprotocol/typescript-sdk#3209), so this module is +// one, built on the SDK's custom request handlers, as `tasks.ts` is for Tasks. +// +// Two synthetic event types cover the extension's two cursor models without +// an upstream service: +// - `clock-tick` (poll and push) is replayable. Tick k happens at k × the +// tick period since the Unix epoch, so every occurrence can be computed +// from the clock and its cursor is just the tick index. Nothing is stored, +// which matters because on the 2026-07-28 HTTP path every request gets a +// fresh server instance. Only the last RETAINED_TICKS ticks can be +// replayed, which gives `truncated: true` a real trigger. +// - `custom-event` (push only) is emit-only. The `trigger-event` tool raises +// it on a process-wide bus, so a stream served by one instance sees an event +// raised through another. It has no history, so its cursor is always null. +// +// Webhook delivery (`events/subscribe`, `events/unsubscribe`) is not offered: +// the extension requires an authenticated principal for it, and this server +// has none, so those methods are left unregistered and answer -32601. The +// extension is served on 2026-07-28 only; a 2025-era client gets -32601 for +// every `events/*` method. + +import { randomUUID } from "node:crypto"; +import { + McpServer, + ProtocolError, + ProtocolErrorCode, + type ServerContext as RequestContext, +} from "@modelcontextprotocol/server"; +import { z } from "zod"; +import type { ServerContext } from "./context.js"; + +/** The extension's identifier, as declared in `capabilities.extensions`. */ +export const EVENTS_EXTENSION = "io.modelcontextprotocol/events"; + +/** The `_meta` key that ties a push notification to its `events/stream`. */ +export const SUBSCRIPTION_ID_META_KEY = + "io.modelcontextprotocol/subscriptionId"; + +/** The extension's error codes (its Error Handling table). */ +export const EventsErrorCode = { + NotFound: -32023, + Forbidden: -32024, + ResourceExhausted: -32025, + Unsupported: -32026, +} as const; + +/** How often `clock-tick` fires. */ +export const TICK_PERIOD_MS = 5_000; + +/** How many past ticks a `clock-tick` cursor can replay. */ +export const RETAINED_TICKS = 100; + +/** The most events one `events/poll` returns, and its default. */ +export const MAX_POLL_EVENTS = 100; +const DEFAULT_POLL_EVENTS = 50; + +/** The bounds and default of a push stream's heartbeat interval. */ +export const MIN_HEARTBEAT_MS = 1_000; +export const MAX_HEARTBEAT_MS = 60_000; +export const DEFAULT_HEARTBEAT_MS = 30_000; + +/** The shortest `nextPollMs` the server suggests when it has no backlog. */ +const MIN_POLL_INTERVAL_MS = 1_000; + +/** + * The most push streams the process holds open at once. Each is a long-lived + * request with a timer, so without a cap a client could open them until the + * process runs out of memory; past it, a new stream is refused with + * ResourceExhausted. + */ +export const MAX_STREAMS = 100; + +const Severity = z.enum(["info", "warning", "error"]); +type Severity = z.infer; +const SEVERITY_RANK: Record = { + info: 0, + warning: 1, + error: 2, +}; + +const ClockTickArguments = z.strictObject({ + everyNth: z + .number() + .int() + .min(1) + .max(1000) + .default(1) + .describe("A filter: deliver only ticks whose index is a multiple of this"), + label: z + .string() + .max(100) + .optional() + .describe("A transform: copied into each delivered payload as `label`"), +}); + +const ClockTickPayload = z.object({ + tick: z.number().int().describe("The tick's index since the Unix epoch"), + label: z.string().optional().describe("The subscription's `label` argument"), +}); + +const CustomEventArguments = z.strictObject({ + minSeverity: Severity.default("info").describe( + "A filter: deliver only events at this severity or above", + ), +}); + +const CustomEventPayload = z.object({ + message: z.string().describe("The message passed to trigger-event"), + severity: Severity.describe("The severity passed to trigger-event"), +}); + +type Delivery = "poll" | "push"; + +/** One event type this server offers. */ +type EventType = { + name: string; + description: string; + delivery: Delivery[]; + arguments: z.ZodType; + payload: z.ZodType; +}; + +const EVENT_TYPES: EventType[] = [ + { + name: "clock-tick", + description: `Fires every ${TICK_PERIOD_MS / 1000} seconds. Replayable: a cursor can resume up to ${RETAINED_TICKS} ticks back.`, + delivery: ["poll", "push"], + arguments: ClockTickArguments, + payload: ClockTickPayload, + }, + { + name: "custom-event", + description: + "Fires when the trigger-event tool is called. Emit-only: it has no history, so its cursor is always null.", + delivery: ["push"], + arguments: CustomEventArguments, + payload: CustomEventPayload, + }, +]; + +/** A JSON Schema for `schema`, without the `$schema` dialect marker. */ +function jsonSchema( + schema: z.ZodType, + io: "input" | "output", +): Record { + const { $schema: _dialect, ...rest } = z.toJSONSchema(schema, { io }); + return rest; +} + +/** The descriptors `events/list` returns. */ +function descriptors(): Record[] { + return EVENT_TYPES.map((type) => ({ + name: type.name, + description: type.description, + delivery: type.delivery, + inputSchema: jsonSchema(type.arguments, "input"), + payloadSchema: jsonSchema(type.payload, "output"), + })); +} + +/** The event type named `name`, or NotFound. */ +function findType(name: string): EventType { + const type = EVENT_TYPES.find((t) => t.name === name); + if (!type) { + throw new ProtocolError( + EventsErrorCode.NotFound, + `Unknown event type: ${name}`, + { kind: "event" }, + ); + } + return type; +} + +/** Refuse a delivery mode the event type does not offer. */ +function requireDelivery(type: EventType, mode: Delivery): void { + if (!type.delivery.includes(mode)) { + throw new ProtocolError( + EventsErrorCode.Unsupported, + `Event type ${type.name} does not support ${mode} delivery`, + { feature: "deliveryMode", value: mode }, + ); + } +} + +/** Parse a subscription's arguments against the type's schema. */ +function parseArguments( + schema: T, + name: string, + args: unknown, +): z.infer { + const parsed = schema.safeParse(args ?? {}); + if (!parsed.success) { + throw new ProtocolError( + ProtocolErrorCode.InvalidParams, + `Invalid arguments for event type ${name}: ${z.prettifyError(parsed.error)}`, + ); + } + return parsed.data; +} + +// --------------------------------------------------------------------------- +// clock-tick: positions, cursors and replay +// --------------------------------------------------------------------------- + +const CURSOR_PREFIX = "clock-tick:"; + +/** The index of the latest tick that has happened at `now`. */ +function headAt(now: number): number { + return Math.floor(now / TICK_PERIOD_MS); +} + +function formatCursor(tick: number): string { + return `${CURSOR_PREFIX}${tick}`; +} + +/** The tick a cursor names, or InvalidParams for one this server never minted. */ +function parseCursor(cursor: string, head: number): number { + const match = /^clock-tick:(\d{1,15})$/.exec(cursor); + const tick = match ? Number(match[1]) : NaN; + if (!Number.isSafeInteger(tick) || tick > head) { + throw new ProtocolError( + ProtocolErrorCode.InvalidParams, + `Invalid cursor for clock-tick: ${cursor}`, + ); + } + return tick; +} + +/** + * Where delivery starts for a subscription: the first tick to check, and + * whether ticks after the client's cursor were skipped to get there. + * + * A null (or absent) cursor means "start from now": nothing is replayed and + * `maxAgeMs` is ignored. Otherwise replay starts after the cursor, but no + * earlier than `now - maxAgeMs` or the oldest retained tick, and moving past + * the cursor for either reason is reported as `truncated`. + */ +function startFor( + cursor: string | null | undefined, + maxAgeMs: number | undefined, + now: number, +): { from: number; truncated: boolean } { + const head = headAt(now); + if (cursor === null || cursor === undefined) { + return { from: head + 1, truncated: false }; + } + const after = parseCursor(cursor, head) + 1; + let from = Math.max(after, head - RETAINED_TICKS + 1); + if (maxAgeMs !== undefined) { + from = Math.max(from, Math.ceil((now - maxAgeMs) / TICK_PERIOD_MS)); + } + return { from, truncated: from > after }; +} + +type ClockTickArgs = z.infer; + +function tickMatches(tick: number, args: ClockTickArgs): boolean { + return tick % args.everyNth === 0; +} + +/** One `clock-tick` occurrence, without its cursor. */ +function tickOccurrence( + tick: number, + args: ClockTickArgs, +): Record { + return { + eventId: `tick-${tick}`, + name: "clock-tick", + timestamp: new Date(tick * TICK_PERIOD_MS).toISOString(), + data: { tick, ...(args.label !== undefined && { label: args.label }) }, + }; +} + +// --------------------------------------------------------------------------- +// custom-event: the process-wide bus +// --------------------------------------------------------------------------- + +/** What `trigger-event` asks the open `custom-event` streams to do. */ +export type CustomEventSignal = + | { kind: "event"; message: string; severity: Severity } + | { kind: "error"; message: string } + | { kind: "terminate"; message: string }; + +/** Every open `custom-event` stream, across every server instance. */ +const customListeners = new Set<(signal: CustomEventSignal) => void>(); + +/** + * Hand a signal to every open `custom-event` stream, and return how many there + * were. Each stream applies its own `minSeverity` filter to an event. + */ +export function emitCustomEvent(signal: CustomEventSignal): number { + // Copied first: a terminate closes each stream, which removes its listener. + const listeners = [...customListeners]; + for (const listener of listeners) listener(signal); + return listeners.length; +} + +/** How many push streams are open in the process. */ +let openStreams = 0; + +/** Forget every open stream. For tests. */ +export function resetEvents(): void { + customListeners.clear(); + openStreams = 0; +} + +// --------------------------------------------------------------------------- +// Push streams +// --------------------------------------------------------------------------- + +type Json = Record; + +/** What a push stream needs of the `events/stream` request it serves. */ +type StreamRequest = Pick; + +/** + * One open `events/stream`: sends its notifications in order, keeps the + * heartbeat going whenever nothing else has been sent for the granted + * interval, and resolves `done` when it ends. Exported for its unit tests, + * which cover the failed send no in-process transport can produce. + */ +export class PushStream { + readonly done: Promise; + private finish!: () => void; + private chain: Promise = Promise.resolve(); + private heartbeat?: NodeJS.Timeout; + private readonly cleanups: Array<() => void> = []; + private closed = false; + + /** Whether the stream has ended. */ + get isClosed(): boolean { + return this.closed; + } + + constructor( + private readonly request: StreamRequest, + private readonly heartbeatMs: number, + private readonly cursor: () => string | null, + ) { + this.done = new Promise((resolve) => (this.finish = resolve)); + } + + /** The `_meta` every notification on this stream carries. */ + get meta(): Json { + return { [SUBSCRIPTION_ID_META_KEY]: this.request.id }; + } + + /** Queue a notification, and restart the heartbeat interval. */ + send(method: string, params: Json): void { + if (this.closed) return; + this.armHeartbeat(); + const notification = { method, params: { ...params, _meta: this.meta } }; + this.chain = this.chain + .then(() => this.request.notify(notification)) + // A send fails only when the connection is gone, so the stream is too. + .catch(() => this.close()); + } + + /** Run `fn` when the stream ends. */ + onClose(fn: () => void): void { + this.cleanups.push(fn); + } + + /** End the stream and release what it holds. Safe to call more than once. */ + close(): void { + if (this.closed) return; + this.closed = true; + clearTimeout(this.heartbeat); + for (const fn of this.cleanups.splice(0)) fn(); + this.finish(); + } + + /** Wait for the stream to end and for its last notification to be sent. */ + async ended(): Promise { + await this.done; + await this.chain; + } + + private armHeartbeat(): void { + clearTimeout(this.heartbeat); + this.heartbeat = setTimeout( + () => + this.send("notifications/events/heartbeat", { cursor: this.cursor() }), + this.heartbeatMs, + ); + } +} + +/** Run a `clock-tick` subscription on `stream` until it closes. */ +function runClockTick( + stream: PushStream, + args: ClockTickArgs, + start: { from: number; truncated: boolean }, + heartbeatMs: number, + position: { checked: number }, +): void { + stream.send("notifications/events/active", { + cursor: formatCursor(position.checked), + truncated: start.truncated, + heartbeatMs, + }); + + let timer: NodeJS.Timeout | undefined; + // Deliver every tick up to now that has not been checked yet (the replayed + // backlog, on the first call), then wait for the next one. + const catchUp = () => { + const head = headAt(Date.now()); + for (let tick = position.checked + 1; tick <= head; tick++) { + position.checked = tick; + if (tickMatches(tick, args)) { + stream.send("notifications/events/event", { + ...tickOccurrence(tick, args), + cursor: formatCursor(tick), + }); + } + } + timer = setTimeout( + catchUp, + (position.checked + 1) * TICK_PERIOD_MS - Date.now(), + ); + }; + stream.onClose(() => clearTimeout(timer)); + catchUp(); +} + +/** Run a `custom-event` subscription on `stream` until it closes. */ +function runCustomEvent( + stream: PushStream, + args: z.infer, + heartbeatMs: number, +): void { + stream.send("notifications/events/active", { + cursor: null, + truncated: false, + heartbeatMs, + }); + const listener = (signal: CustomEventSignal) => { + switch (signal.kind) { + case "event": + if (SEVERITY_RANK[signal.severity] >= SEVERITY_RANK[args.minSeverity]) { + stream.send("notifications/events/event", { + eventId: `custom-${randomUUID()}`, + name: "custom-event", + timestamp: new Date().toISOString(), + data: { message: signal.message, severity: signal.severity }, + cursor: null, + }); + } + break; + case "error": + stream.send("notifications/events/error", { + error: { + code: ProtocolErrorCode.InternalError, + message: "UpstreamError", + data: { reason: signal.message }, + }, + }); + break; + case "terminate": + stream.send("notifications/events/terminated", { + error: { + code: EventsErrorCode.Forbidden, + message: "Forbidden", + data: { reason: signal.message }, + }, + }); + stream.close(); + break; + } + }; + customListeners.add(listener); + stream.onClose(() => customListeners.delete(listener)); +} + +// --------------------------------------------------------------------------- +// The methods +// --------------------------------------------------------------------------- + +const Cursor = z.string().nullable().optional(); + +const ListParams = z.object({ + cursor: z.string().optional().describe("A pagination cursor"), +}); + +const SubscriptionParams = { + name: z.string().describe("The event type to subscribe to"), + arguments: z + .record(z.string(), z.unknown()) + .optional() + .describe("The subscription's arguments, per the type's inputSchema"), + cursor: Cursor.describe("Where to resume; null means start from now"), + maxAgeMs: z + .number() + .int() + .nonnegative() + .optional() + .describe("Do not replay events older than this many milliseconds"), +}; + +const PollParams = z.object({ + ...SubscriptionParams, + maxEvents: z + .number() + .int() + .min(1) + .optional() + .describe("The most events to return"), +}); + +const StreamParams = z.object({ + ...SubscriptionParams, + heartbeatMs: z + .number() + .int() + .positive() + .optional() + .describe("The suggested heartbeat interval"), +}); + +const LooseResult = z.looseObject({}); + +/** + * Serve the extension's methods on a 2026-07-28 server: `events/list`, + * `events/poll` and `events/stream`. + * + * @param {McpServer} server - The 2026-07-28 server to serve them on. + * @param {ServerContext} context - The instance's context, whose cleanup + * closes the streams it still has open. + */ +export function registerEventsExtension( + server: McpServer, + context: ServerContext, +): void { + const streams = new Set(); + context.onCleanup(() => { + for (const stream of streams) stream.close(); + }); + + server.server.setRequestHandler( + "events/list", + { params: ListParams, result: LooseResult }, + async ({ cursor }) => { + // Every type fits on one page, so no cursor was ever minted. + if (cursor !== undefined) { + throw new ProtocolError( + ProtocolErrorCode.InvalidParams, + `Invalid cursor for events/list: ${cursor}`, + ); + } + return { events: descriptors() }; + }, + ); + + server.server.setRequestHandler( + "events/poll", + { params: PollParams, result: LooseResult }, + async (params) => { + const type = findType(params.name); + requireDelivery(type, "poll"); + // Only clock-tick offers poll. + const args = parseArguments( + ClockTickArguments, + type.name, + params.arguments, + ); + const now = Date.now(); + const head = headAt(now); + const start = startFor(params.cursor, params.maxAgeMs, now); + const maxEvents = Math.min( + params.maxEvents ?? DEFAULT_POLL_EVENTS, + MAX_POLL_EVENTS, + ); + + const events: Json[] = []; + let checked = start.from - 1; + while (checked < head && events.length < maxEvents) { + checked++; + if (tickMatches(checked, args)) { + events.push(tickOccurrence(checked, args)); + } + } + let hasMore = false; + for (let tick = checked + 1; tick <= head && !hasMore; tick++) { + hasMore = tickMatches(tick, args); + } + return { + events, + cursor: formatCursor(checked), + truncated: start.truncated, + hasMore, + nextPollMs: hasMore + ? 0 + : Math.max(MIN_POLL_INTERVAL_MS, (head + 1) * TICK_PERIOD_MS - now), + }; + }, + ); + + server.server.setRequestHandler( + "events/stream", + { params: StreamParams, result: LooseResult }, + async (params, ctx) => { + const type = findType(params.name); + requireDelivery(type, "push"); + const heartbeatMs = Math.min( + MAX_HEARTBEAT_MS, + Math.max(MIN_HEARTBEAT_MS, params.heartbeatMs ?? DEFAULT_HEARTBEAT_MS), + ); + + // Validate everything before the stream opens: an invalid subscription + // is answered with an error and no stream. + let run: (stream: PushStream) => void; + let cursor: () => string | null; + if (type.name === "clock-tick") { + const args = parseArguments( + ClockTickArguments, + type.name, + params.arguments, + ); + const start = startFor(params.cursor, params.maxAgeMs, Date.now()); + const position = { checked: start.from - 1 }; + cursor = () => formatCursor(position.checked); + run = (stream) => + runClockTick(stream, args, start, heartbeatMs, position); + } else { + const args = parseArguments( + CustomEventArguments, + type.name, + params.arguments, + ); + cursor = () => null; + run = (stream) => runCustomEvent(stream, args, heartbeatMs); + } + if (openStreams >= MAX_STREAMS) { + throw new ProtocolError( + EventsErrorCode.ResourceExhausted, + `The server already has ${MAX_STREAMS} event streams open, its limit`, + { limit: "streams", max: MAX_STREAMS }, + ); + } + + const stream = new PushStream(ctx.mcpReq, heartbeatMs, cursor); + openStreams++; + streams.add(stream); + stream.onClose(() => { + openStreams--; + streams.delete(stream); + }); + // Cancellation (notifications/cancelled on stdio, an abort on HTTP) + // ends the stream and releases its timers and listener. + const signal = ctx.mcpReq.signal; + const abort = () => stream.close(); + signal.addEventListener("abort", abort, { once: true }); + stream.onClose(() => signal.removeEventListener("abort", abort)); + // An already-aborted signal never fires its abort event, so check it. + /* v8 ignore next -- the SDK dispatches no request it has already seen cancelled */ + if (signal.aborted) stream.close(); + else run(stream); + await stream.ended(); + // The final frame, when the server ends the stream; the SDK sends no + // response to a request the client cancelled. + return { _meta: stream.meta }; + }, + ); +} diff --git a/src/everything/server/index.ts b/src/everything/server/index.ts index fb8a531423..cfa3c157b4 100644 --- a/src/everything/server/index.ts +++ b/src/everything/server/index.ts @@ -17,7 +17,8 @@ // - 2026-07-28: there is no `initialize`, and each request carries the // client's capabilities in its `_meta`, so the capability-gated tools are // registered up front and the SDK refuses an embedded request the client -// did not declare (-32021). The tasks extension is served here only. +// did not declare (-32021). The tasks and events extensions are served here +// only. import { createRequestStateCodec, @@ -33,6 +34,7 @@ import { } from "../tools/index.js"; import { registerResources, readInstructions } from "../resources/index.js"; import { registerPrompts } from "../prompts/index.js"; +import { EVENTS_EXTENSION, registerEventsExtension } from "./events.js"; import { guardTaskTools, registerTasksExtension, @@ -148,9 +150,13 @@ export const createServer = ( // eras: 2025-era clients set the level with `logging/setLevel`, // 2026-07-28 clients per request in `_meta`. logging: {}, - // The tasks extension (`io.modelcontextprotocol/tasks`) is - // advertised on 2026-07-28 only, where it is served. - ...(era === "modern" && { extensions: { [TASKS_EXTENSION]: {} } }), + // The tasks (`io.modelcontextprotocol/tasks`) and events + // (`io.modelcontextprotocol/events`) extensions are advertised on + // 2026-07-28 only, where they are served. Events sends no + // list_changed notifications: its event types never change. + ...(era === "modern" && { + extensions: { [TASKS_EXTENSION]: {}, [EVENTS_EXTENSION]: {} }, + }), }, instructions, cacheHints: CACHE_HINTS, @@ -185,9 +191,11 @@ export const createServer = ( if (era === "modern") { // Each request carries the client's capabilities, so the tools that need - // one are registered up front, along with the tasks extension. + // one are registered up front, along with the tasks and events + // extensions. registerModernTools(server, context); registerTasksExtension(server); + registerEventsExtension(server, context); } else { registerLegacyTools(server, context); setSubscriptionHandlers(server, context.subscribed); diff --git a/src/everything/tools/index.ts b/src/everything/tools/index.ts index 361cd67bcb..55b8d4c361 100644 --- a/src/everything/tools/index.ts +++ b/src/everything/tools/index.ts @@ -9,7 +9,8 @@ // - `registerModernTools`: 2026-07-28 clients. Their capabilities arrive with // each request, so the capability-gated tools are registered up front and the // SDK refuses an embedded request the client did not declare (-32021); the -// task tools are served only here, on the tasks extension. +// task tools are served only here, on the tasks extension, and so is +// `trigger-event`, which drives the events extension. import { McpServer } from "@modelcontextprotocol/server"; import type { ServerContext } from "../server/context.js"; @@ -29,6 +30,7 @@ import { registerToggleSimulatedLoggingTool } from "./toggle-simulated-logging.j import { registerToggleSubscriberUpdatesTool } from "./toggle-subscriber-updates.js"; import { registerTriggerElicitationRequestAsyncTool } from "./trigger-elicitation-request-async.js"; import { registerTriggerElicitationRequestTool } from "./trigger-elicitation-request.js"; +import { registerTriggerEventTool } from "./trigger-event.js"; import { registerTriggerListChangedTool } from "./trigger-list-changed.js"; import { registerTriggerLogMessagesTool } from "./trigger-log-messages.js"; import { registerTriggerLongRunningOperationTool } from "./trigger-long-running-operation.js"; @@ -108,7 +110,8 @@ export const registerConditionalTools = ( /** * Register the tools a 2026-07-28 client gets beyond the common ones: the - * capability-gated tools, registered up front, and the task tools. + * capability-gated tools, registered up front, the task tools, and the + * events extension's trigger-event. * @param server * @param context */ @@ -124,4 +127,5 @@ export const registerModernTools = ( registerSimulateResearchQueryTool(server); registerTriggerSamplingRequestAsyncTool(server); registerTriggerElicitationRequestAsyncTool(server); + registerTriggerEventTool(server); }; diff --git a/src/everything/tools/trigger-event.ts b/src/everything/tools/trigger-event.ts new file mode 100644 index 0000000000..b3777b74c3 --- /dev/null +++ b/src/everything/tools/trigger-event.ts @@ -0,0 +1,85 @@ +// The `trigger-event` tool: raises the Events extension's `custom-event` on +// every open push stream subscribed to it (#5651), so a client can watch an +// event arrive on `events/stream` when it asks for one. +// +// Besides an ordinary event, it can make the streams report a recoverable +// upstream failure (`notifications/events/error`, the stream stays open) or +// end their subscriptions (`notifications/events/terminated`), the two +// non-event outcomes a push subscriber has to handle. The extension is served +// on 2026-07-28 only, so the tool is too. + +import { McpServer, CallToolResult } from "@modelcontextprotocol/server"; +import { z } from "zod"; +import { emitCustomEvent } from "../server/events.js"; +import { TOOL_ICONS } from "../server/icons.js"; + +// Tool input schema +const TriggerEventSchema = z.object({ + kind: z + .enum(["event", "error", "terminate"]) + .default("event") + .describe( + "event: deliver a custom-event occurrence; error: send notifications/events/error and keep the " + + "streams open; terminate: send notifications/events/terminated and close the streams", + ), + message: z + .string() + .min(1) + .max(500) + .default("Hello from trigger-event") + .describe( + "The event's message, or the reason given for an error or termination", + ), + severity: z + .enum(["info", "warning", "error"]) + .default("info") + .describe( + "The event's severity, matched against each stream's minSeverity (kind event only)", + ), +}); + +// Tool configuration +const name = "trigger-event"; +const config = { + title: "Trigger Event Tool", + description: + "Raises the Events extension's custom-event on every open events/stream subscribed to it. " + + "With kind error it sends a recoverable notifications/events/error instead, and with kind " + + "terminate it ends those subscriptions with notifications/events/terminated.", + inputSchema: TriggerEventSchema, + icons: TOOL_ICONS, + annotations: { + readOnlyHint: false, + destructiveHint: false, + idempotentHint: false, + openWorldHint: false, + }, +}; + +/** + * Registers the 'trigger-event' tool. + * + * @param {McpServer} server - The McpServer instance where the tool will be registered. + */ +export const registerTriggerEventTool = (server: McpServer) => { + server.registerTool(name, config, async (args): Promise => { + const { kind, message, severity } = TriggerEventSchema.parse(args); + const streams = emitCustomEvent( + kind === "event" ? { kind, message, severity } : { kind, message }, + ); + const what = + kind === "event" + ? `custom-event (${severity})` + : kind === "error" + ? "notifications/events/error" + : "notifications/events/terminated"; + return { + content: [ + { + type: "text", + text: `Sent ${what} to ${streams} open custom-event stream${streams === 1 ? "" : "s"}`, + }, + ], + }; + }); +}; From 55eef5f063e5ff5c3168c1fe4ee8ee076831ac8e Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 23 Nov 2026 23:56:31 -0500 Subject: [PATCH 2/3] test(everything): declare the open-session list const Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/everything/__tests__/events.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/everything/__tests__/events.test.ts b/src/everything/__tests__/events.test.ts index 7a43a2eb00..cbca374e55 100644 --- a/src/everything/__tests__/events.test.ts +++ b/src/everything/__tests__/events.test.ts @@ -41,7 +41,7 @@ const OFFSET_MS = 2_000; const cursor = (tick: number) => `clock-tick:${tick}`; -let open: Array<{ close: () => Promise }> = []; +const open: Array<{ close: () => Promise }> = []; async function raw(): Promise { const session = await connectRaw(CAPABILITIES); From d2772632794324761df27a7583e937ae6d77263e Mon Sep 17 00:00:00 2001 From: cliffhall Date: Tue, 24 Nov 2026 00:51:08 -0500 Subject: [PATCH 3/3] fix(everything): share custom-event identity, stop queued sends on cancel, bound catch-up replay Copilot round 1 on #5652: - Mint a custom-event's eventId and timestamp once on the bus, so every matching subscription receives the same occurrence identity. - Drop notifications still queued when a stream ends abruptly (cancellation, a failed send, cleanup); a termination still drains. - Re-apply the retention window when a late tick timer catches up, and report the gap with a fresh active carrying truncated: true. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/everything/__tests__/events.test.ts | 91 ++++++++++++++++++++++++- src/everything/docs/features.md | 2 +- src/everything/docs/how-it-works.md | 2 +- src/everything/server/events.ts | 72 ++++++++++++++++--- 4 files changed, 153 insertions(+), 14 deletions(-) diff --git a/src/everything/__tests__/events.test.ts b/src/everything/__tests__/events.test.ts index cbca374e55..f2d3d3d129 100644 --- a/src/everything/__tests__/events.test.ts +++ b/src/everything/__tests__/events.test.ts @@ -471,6 +471,33 @@ describe("events/stream: clock-tick", () => { ); }); + it("replays no more than the retained ticks when its timer fires late, and reports the gap", async () => { + const session = await raw(); + void session.request("events/stream", { + name: "clock-tick", + heartbeatMs: MAX_HEARTBEAT_MS, + }); + await settle(); + // The process sleeps through 1000 ticks: the clock jumps, and the tick + // timer fires once, late. + // (Faking the clock moves Date but not the timer queue, so the jump is + // set short by the time left until the timer is due.) + const untilDue = TICK_PERIOD_MS - OFFSET_MS; + vi.setSystemTime((HEAD + 1_000) * TICK_PERIOD_MS + OFFSET_MS - untilDue); + await vi.advanceTimersByTimeAsync(untilDue); + expect(sent(session, "notifications/events/active")).toEqual([ + expect.objectContaining({ cursor: cursor(HEAD), truncated: false }), + expect.objectContaining({ + cursor: cursor(HEAD + 1_000 - RETAINED_TICKS), + truncated: true, + heartbeatMs: MAX_HEARTBEAT_MS, + }), + ]); + const events = sent(session, "notifications/events/event"); + expect(events).toHaveLength(RETAINED_TICKS); + expect(events[0].eventId).toBe(`tick-${HEAD + 1_000 - RETAINED_TICKS + 1}`); + }); + it("reports a cursor outside the retained window as truncated on active", async () => { const session = await raw(); void session.request("events/stream", { @@ -598,7 +625,18 @@ describe("events/stream: custom-event and trigger-event", () => { "Sent custom-event (info) to 2 open custom-event streams", ); await settle(); - expect(sent(listener, "notifications/events/event")).toHaveLength(2); + // One occurrence: the same eventId and timestamp on every subscription. + const [first, second] = sent(listener, "notifications/events/event"); + expect(second.eventId).toBe(first.eventId); + expect(second.timestamp).toBe(first.timestamp); + expect(second._meta).not.toEqual(first._meta); + + // A second call is a new occurrence. + await caller.call("trigger-event", {}); + await settle(); + expect(sent(listener, "notifications/events/event")[2].eventId).not.toBe( + first.eventId, + ); }); it("sends a recoverable error and keeps the stream open", async () => { @@ -716,4 +754,55 @@ describe("PushStream", () => { expect(notify).toHaveBeenCalledOnce(); expect(released).toHaveBeenCalledOnce(); }); + + /** A notify whose sends stay pending until released, one at a time. */ + function slowNotify() { + const pending: Array<() => void> = []; + const notify = vi.fn( + () => new Promise((resolve) => pending.push(resolve)), + ); + const release = async () => { + pending.shift()?.(); + await settle(); + }; + return { notify, release }; + } + + it("drops what is still queued when it ends abruptly", async () => { + const { notify, release } = slowNotify(); + const stream = new PushStream({ id: 1, notify }, 1_000, () => null); + stream.send("notifications/events/event", { n: 1 }); + stream.send("notifications/events/event", { n: 2 }); + stream.send("notifications/events/event", { n: 3 }); + await settle(); + stream.abort(); + await release(); + await stream.ended(); + expect(notify).toHaveBeenCalledOnce(); + }); + + it("drops what is still queued after a failed send", async () => { + const notify = vi + .fn() + .mockRejectedValueOnce(new Error("connection gone")) + .mockResolvedValue(undefined); + const stream = new PushStream({ id: 1, notify }, 1_000, () => null); + stream.send("notifications/events/event", { n: 1 }); + stream.send("notifications/events/event", { n: 2 }); + await stream.ended(); + expect(notify).toHaveBeenCalledOnce(); + }); + + it("sends what is already queued when it ends gracefully", async () => { + const { notify, release } = slowNotify(); + const stream = new PushStream({ id: 1, notify }, 1_000, () => null); + stream.send("notifications/events/terminated", { n: 1 }); + stream.send("notifications/events/terminated", { n: 2 }); + await settle(); + stream.close(); + await release(); + await release(); + await stream.ended(); + expect(notify).toHaveBeenCalledTimes(2); + }); }); diff --git a/src/everything/docs/features.md b/src/everything/docs/features.md index 35a1f65263..78047a5e92 100644 --- a/src/everything/docs/features.md +++ b/src/everything/docs/features.md @@ -117,7 +117,7 @@ The 2025-11-25 core task methods (`tasks/result`, `tasks/list`, task-augmented r `clock-tick` fires every 5 seconds: tick *k* happens at *k* × 5 s since the Unix epoch, so every occurrence is computed from the clock and its `eventId` (`tick-`) is the same on every subscription and every replay. `custom-event` fires when the `trigger-event` tool is called, through a process-wide bus, so a stream opened through one connection (or one HTTP request) sees an event raised through another. - `events/poll` (`clock-tick` only): a `null` or absent cursor starts from now (no events, the current cursor). A cursor replays the ticks after it, at most `maxEvents` (default 50, at most 100) at a time, with `hasMore: true` and `nextPollMs: 0` while a backlog remains; otherwise `nextPollMs` is the time to the next tick (at least 1 s). Replay starts no earlier than `now - maxAgeMs` or the oldest retained tick, and `truncated: true` says when either skipped events. -- `events/stream`: one long-lived request per subscription. It sends `notifications/events/active` first (the starting cursor, `truncated`, and the granted `heartbeatMs`: the client's suggestion clamped to 1–60 s, 30 s by default), then the replayed backlog and each new occurrence as `notifications/events/event`, and `notifications/events/heartbeat` with the cursor checked up to whenever the granted interval passes without another message. Every notification carries the request's id in `_meta["io.modelcontextprotocol/subscriptionId"]`. Cancelling the request (`notifications/cancelled` on stdio, closing the HTTP response) ends the stream and releases its timers; when the server ends it (after `trigger-event` terminates it) the request answers with an empty result. The process holds at most 100 streams; past that a new one is refused with `-32025` (ResourceExhausted). +- `events/stream`: one long-lived request per subscription. It sends `notifications/events/active` first (the starting cursor, `truncated`, and the granted `heartbeatMs`: the client's suggestion clamped to 1–60 s, 30 s by default), then the replayed backlog and each new occurrence as `notifications/events/event`, and `notifications/events/heartbeat` with the cursor checked up to whenever the granted interval passes without another message. Every notification carries the request's id in `_meta["io.modelcontextprotocol/subscriptionId"]`. If the stream's tick timer fires late (the process was suspended, or the clock jumped), it replays no more than the 100 retained ticks and first sends a fresh `active` with `truncated: true`. A `custom-event` raised once arrives with the same `eventId` and `timestamp` on every stream it matches. Cancelling the request (`notifications/cancelled` on stdio, closing the HTTP response) ends the stream, drops any notifications still queued and releases its timers; when the server ends it (after `trigger-event` terminates it) the request answers with an empty result. The process holds at most 100 streams; past that a new one is refused with `-32025` (ResourceExhausted). - Errors: an unknown event type is `-32023` (NotFound, `data.kind: "event"`); a delivery mode the type does not offer (polling `custom-event`) is `-32026` (Unsupported, `data: {feature: "deliveryMode", value}`); arguments that do not match the type's `inputSchema`, or a cursor the server never minted, are `-32602`. An invalid subscription gets its error before any stream opens. - Webhook delivery is not offered: the extension requires an authenticated principal for `events/subscribe` and `events/unsubscribe`, and this server has none, so both answer `-32601`. diff --git a/src/everything/docs/how-it-works.md b/src/everything/docs/how-it-works.md index 542c843012..fa4aafd46e 100644 --- a/src/everything/docs/how-it-works.md +++ b/src/everything/docs/how-it-works.md @@ -41,7 +41,7 @@ - Serves the events extension (`io.modelcontextprotocol/events`) on 2026-07-28: `events/list`, `events/poll` and `events/stream`, with explicit schemas. Webhook delivery is not offered. - `clock-tick` is computed from the clock (tick *k* at *k* × 5 s), so a poll or a replaying stream needs no stored history. `custom-event` is raised by `trigger-event` through `emitCustomEvent`, a process-wide bus every open `custom-event` stream listens on. -- A `PushStream` sends one stream's notifications in order, tagged with the request id, re-arms the heartbeat after each, and ends on cancellation, on termination, on a failed send, or when its server instance is cleaned up. +- A `PushStream` sends one stream's notifications in order, tagged with the request id, re-arms the heartbeat after each, and ends on cancellation, on termination, on a failed send, or when its server instance is cleaned up. An abrupt end (cancellation, a failed send, cleanup) drops what is still queued; a termination sends it first. ## Resource Subscriptions diff --git a/src/everything/server/events.ts b/src/everything/server/events.ts index 384377cbfe..a94c91f6bd 100644 --- a/src/everything/server/events.ts +++ b/src/everything/server/events.ts @@ -287,17 +287,37 @@ export type CustomEventSignal = | { kind: "error"; message: string } | { kind: "terminate"; message: string }; +/** + * A signal as the bus hands it to each stream: an event carries the identity + * and time minted once for it, so every subscription it matches receives the + * same `eventId` and `timestamp`, as the extension requires of one occurrence. + */ +type BusMessage = + | (Extract & { + eventId: string; + timestamp: string; + }) + | Exclude; + /** Every open `custom-event` stream, across every server instance. */ -const customListeners = new Set<(signal: CustomEventSignal) => void>(); +const customListeners = new Set<(message: BusMessage) => void>(); /** * Hand a signal to every open `custom-event` stream, and return how many there * were. Each stream applies its own `minSeverity` filter to an event. */ export function emitCustomEvent(signal: CustomEventSignal): number { + const message: BusMessage = + signal.kind === "event" + ? { + ...signal, + eventId: `custom-${randomUUID()}`, + timestamp: new Date().toISOString(), + } + : signal; // Copied first: a terminate closes each stream, which removes its listener. const listeners = [...customListeners]; - for (const listener of listeners) listener(signal); + for (const listener of listeners) listener(message); return listeners.length; } @@ -332,6 +352,8 @@ export class PushStream { private heartbeat?: NodeJS.Timeout; private readonly cleanups: Array<() => void> = []; private closed = false; + /** Set by an abrupt end: notifications still queued are dropped. */ + private discarding = false; /** Whether the stream has ended. */ get isClosed(): boolean { @@ -357,9 +379,11 @@ export class PushStream { this.armHeartbeat(); const notification = { method, params: { ...params, _meta: this.meta } }; this.chain = this.chain - .then(() => this.request.notify(notification)) + .then(() => + this.discarding ? undefined : this.request.notify(notification), + ) // A send fails only when the connection is gone, so the stream is too. - .catch(() => this.close()); + .catch(() => this.abort()); } /** Run `fn` when the stream ends. */ @@ -367,7 +391,21 @@ export class PushStream { this.cleanups.push(fn); } - /** End the stream and release what it holds. Safe to call more than once. */ + /** + * End the stream abruptly (the client cancelled, a send failed, or the + * connection ended): release it, and send nothing still queued, since the + * extension says delivery stops at cancellation. + */ + abort(): void { + this.discarding = true; + this.close(); + } + + /** + * End the stream gracefully: release it, but send what is already queued + * (a `terminated` goes out before the final result). Safe to call more than + * once. + */ close(): void { if (this.closed) return; this.closed = true; @@ -411,6 +449,18 @@ function runClockTick( // backlog, on the first call), then wait for the next one. const catchUp = () => { const head = headAt(Date.now()); + // A timer that fires late (the process was suspended, or the clock jumped + // forward) replays no more than a new stream would, and reports the gap + // as the extension asks: a fresh `active` with `truncated: true`. + const oldest = head - RETAINED_TICKS + 1; + if (position.checked + 1 < oldest) { + position.checked = oldest - 1; + stream.send("notifications/events/active", { + cursor: formatCursor(position.checked), + truncated: true, + heartbeatMs, + }); + } for (let tick = position.checked + 1; tick <= head; tick++) { position.checked = tick; if (tickMatches(tick, args)) { @@ -440,14 +490,14 @@ function runCustomEvent( truncated: false, heartbeatMs, }); - const listener = (signal: CustomEventSignal) => { + const listener = (signal: BusMessage) => { switch (signal.kind) { case "event": if (SEVERITY_RANK[signal.severity] >= SEVERITY_RANK[args.minSeverity]) { stream.send("notifications/events/event", { - eventId: `custom-${randomUUID()}`, + eventId: signal.eventId, name: "custom-event", - timestamp: new Date().toISOString(), + timestamp: signal.timestamp, data: { message: signal.message, severity: signal.severity }, cursor: null, }); @@ -539,7 +589,7 @@ export function registerEventsExtension( ): void { const streams = new Set(); context.onCleanup(() => { - for (const stream of streams) stream.close(); + for (const stream of streams) stream.abort(); }); server.server.setRequestHandler( @@ -654,12 +704,12 @@ export function registerEventsExtension( // Cancellation (notifications/cancelled on stdio, an abort on HTTP) // ends the stream and releases its timers and listener. const signal = ctx.mcpReq.signal; - const abort = () => stream.close(); + const abort = () => stream.abort(); signal.addEventListener("abort", abort, { once: true }); stream.onClose(() => signal.removeEventListener("abort", abort)); // An already-aborted signal never fires its abort event, so check it. /* v8 ignore next -- the SDK dispatches no request it has already seen cancelled */ - if (signal.aborted) stream.close(); + if (signal.aborted) stream.abort(); else run(stream); await stream.ended(); // The final frame, when the server ends the stream; the SDK sends no