iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

kernel / core / mind-worker / src / library / mcp-events.test.tsmain at 949894f

// The events of another MCP server, as the connection of `itx.connectToMcp` asks for them (./mcp.ts
// `listEvents`, `subscribe`, `unsubscribe`, `pollEvents`, and the script that renews a
// subscription), against a fake server of MCP Events (SEP-3415) and a context that records its
// schedules. That a schedule's script runs on a real context is ./mcp-in-workerd.test.ts; the
// receiving end of a webhook is ../integrations/mcp.ts.
import { runInThisContext } from "node:vm";
import { createMcpHandler, McpServer, ProtocolError } from "@modelcontextprotocol/server";
import { expect, onTestFinished, test, vi } from "vitest";
import { z } from "zod";
import type { LibraryItx } from "core-itx";
import { connectToMcp, followUpScript, whyNoFollowUp } from "./mcp.ts";

const SHOP = "https://petshop.test/mcp";
const WEBHOOK = "https://iterate.mind.test/api/mcp-webhook?path=%2Fagents%2Fmain";
const NOW = Date.parse("2026-11-26T12:00:00Z");
const HOUR_MS = 60 * 60_000;

test("the client declares MCP Events, and a request that names an event carries the name in Mcp-Name", async () => {
  const context = contextOfFake({});
  const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
  await mcp.listEvents();
  await mcp.subscribe("pet.adopted", { species: "beagle" });
  await mcp.pollEvents("über.event");
  expect(context.sent.at(-1)?.capabilities).toMatchObject({
    extensions: { "io.modelcontextprotocol/events": {} },
  });
  expect(context.sent.map(({ method, name }) => [method, name]).slice(-3)).toEqual([
    ["events/list", null],
    ["events/subscribe", "pet.adopted"],
    // a name that is not plain ASCII: UTF-8 in base64, as the transport encodes a header's value
    ["events/poll", "=?base64?w7xiZXIuZXZlbnQ=?="],
  ]);
  await mcp.close();
});

test.for([
  { name: "in extensions, where the extension puts it", declared: "extensions" as const },
  { name: "as the top-level events of the design sketch", declared: "sketch" as const },
])(
  "a server that declares MCP Events $name is asked for every page of its events",
  async ({ declared }) => {
    const context = contextOfFake({ declared });
    const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
    expect((await mcp.listEvents()).map((event) => event.name)).toEqual([
      "pet.created",
      "pet.adopted",
      "pet.returned",
    ]);
    await mcp.close();
  },
);

test("a server that declares no MCP Events is sent no events request", async () => {
  const context = contextOfFake({ declared: "none" });
  const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
  expect(await mcp.listEvents()).toEqual([]);
  const refused = `the MCP server ${SHOP} does not declare MCP Events`;
  await expect(mcp.subscribe("pet.adopted")).rejects.toThrow(refused);
  await expect(mcp.unsubscribe("pet.adopted")).rejects.toThrow(refused);
  await expect(mcp.pollEvents("pet.adopted")).rejects.toThrow(refused);
  expect(context.sent.filter(({ method }) => method.startsWith("events/"))).toEqual([]);
  expect(context).toMatchObject({ schedules: [] });
  await mcp.close();
});

test("subscribe asks for a day, hands the server's grant on, and sets the renewal on the context", async () => {
  vi.useFakeTimers({ toFake: ["Date"], now: NOW });
  onTestFinished(() => void vi.useRealTimers());
  const headers = { authorization: 'Bearer getSecret("/secrets/petshop")' };
  const context = contextOfFake({});
  const mcp = await connectToMcp(context.itx, SHOP, { headers }, webhook);
  // exact: the grant crosses as the server gave it
  expect(await mcp.subscribe("pet.adopted", { species: "beagle" })).toEqual({
    id: "sub_1",
    refreshBefore: new Date(NOW + HOUR_MS).toISOString(),
    cursor: "7",
    truncated: false,
    deliveryStatus: { active: true, lastError: null },
  });
  expect(context.sent.at(-1)?.params).toEqual({
    name: "pet.adopted",
    arguments: { species: "beagle" },
    delivery: { mode: "webhook", url: WEBHOOK, secret: "whsec_fake" },
    ttlMs: 24 * HOUR_MS,
  });
  // after two thirds of the hour, a script that subscribes again from the grant's cursor
  expect(context.schedules).toHaveLength(1);
  const key = z
    .tuple([z.literal("mcp-subscription"), z.string().regex(/^[0-9a-f]{32}$/)])
    .parse(context.schedules[0]?.set?.key);
  expect(context.schedules[0]?.set).toEqual({
    key,
    when: { afterMs: 40 * 60_000 },
    events: [
      {
        type: "events.iterate.com/itx/run-requested",
        payload: {
          code: followUpScript({
            server: SHOP,
            options: { headers },
            key,
            call: ["subscribe", "pet.adopted", { species: "beagle" }, { cursor: "7" }],
            failed: {
              type: "events.iterate.com/mcp/subscription-ended",
              // the subscription and the moment of this renewal's setting: one end for it
              idempotencyKey: `mcp/subscription-ended:${key[1]}:${String(NOW)}`,
              payload: { server: SHOP, name: "pet.adopted", arguments: { species: "beagle" } },
            },
            // the grant's own end: no try of the renewal subscribes after it
            lapsesAt: NOW + HOUR_MS,
          }),
        },
      },
    ],
  });
  await mcp.close();
});

test.for([
  // two thirds of four minutes
  { name: "a grant of four minutes", grantMs: 4 * 60_000, afterMs: 160_000 },
  // sooner than two minutes, and the kernel's loop guard would count the renewals as one fast chain
  { name: "a grant of two and a half minutes", grantMs: 150_000, afterMs: 2 * 60_000 },
  { name: "a grant of thirty days", grantMs: 30 * 24 * HOUR_MS, afterMs: 24 * HOUR_MS },
])("the renewal of $name is set within its bounds", async ({ grantMs, afterMs }) => {
  vi.useFakeTimers({ toFake: ["Date"], now: NOW });
  onTestFinished(() => void vi.useRealTimers());
  const context = contextOfFake({ grantMs });
  const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
  expect(await mcp.subscribe("pet.adopted")).not.toHaveProperty("notRenewed");
  expect(context.schedules).toMatchObject([{ set: { when: { afterMs } } }]);
  await mcp.close();
});

test("a grant that is over before a renewal may run is not renewed, and says so", async () => {
  vi.useFakeTimers({ toFake: ["Date"], now: NOW });
  onTestFinished(() => void vi.useRealTimers());
  const context = contextOfFake({});
  const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
  await mcp.subscribe("pet.adopted");
  // the server's next grant lasts a minute: a renewal after two minutes would come after the lapse
  context.grant(60_000);
  const lapse = new Date(NOW + 60_000).toISOString();
  expect(await mcp.subscribe("pet.adopted")).toMatchObject({
    refreshBefore: lapse,
    notRenewed: `the server's grant lasts 60 seconds, and a context renews no sooner than after 120. Nothing renews the subscription: it lapses at ${lapse}`,
  });
  // and the renewal that the hour's grant had set is the subscription's no more
  expect(context.schedules).toMatchObject([{ set: {} }, { cancel: context.schedules[0]?.set?.key }]);
  await mcp.close();
});

test.for<{ written: string; headers: Record<string, string> }>([
  { written: "the header authorization", headers: { authorization: "Bearer abc" } },
  { written: "the header X-Api-Key", headers: { "X-Api-Key": "abc" } },
])("a connection with $written written out is not renewed, and says so", async ({ headers }) => {
  const context = contextOfFake({});
  const mcp = await connectToMcp(context.itx, SHOP, { headers }, webhook);
  const [name = ""] = Object.keys(headers);
  expect(await mcp.subscribe("pet.adopted")).toMatchObject({
    id: "sub_1",
    notRenewed: expect.stringContaining(`the connection's header "${name}" is written out`),
  });
  // no script, so no copy of the credential in the context's log
  expect(context.schedules).toEqual([]);
  await mcp.close();
});

test.for<{ url: string; headers: Record<string, string>; why: string | null }>([
  { url: SHOP, headers: {}, why: null },
  { url: SHOP, headers: { authorization: 'Bearer getSecret("/secrets/shop")' }, why: null },
  { url: SHOP, headers: { "accept-language": "en", "x-tenant": "acme" }, why: null },
  { url: `${SHOP}?api_key=getSecret("/secrets/shop")`, headers: {}, why: null },
  { url: `${SHOP}?page=2`, headers: {}, why: null },
  {
    url: SHOP,
    headers: { cookie: 'a=getSecret("/secrets/a"); b=getSecret("/secrets/b", { field: "sid" })' },
    why: null,
  },
  {
    url: SHOP,
    headers: { authorization: `Basic ${btoa('shop:getSecret("/secrets/shop")')}` },
    why: null,
  },
  { url: SHOP, headers: { Cookie: "sid=abc" }, why: 'header "Cookie"' },
  // one secret by name beside one that is written out: the header as a whole is not a reference
  {
    url: SHOP,
    headers: { Cookie: 'a=getSecret("/secrets/a"); sid=abc' },
    why: 'header "Cookie"',
  },
  {
    url: SHOP,
    headers: { authorization: 'Bearer abc getSecret("/secrets/shop")' },
    why: 'header "authorization"',
  },
  { url: SHOP, headers: { authorization: `Basic ${btoa("shop:hunter2")}` }, why: 'header "authorization"' },
  { url: SHOP, headers: { "x-api-key": 'k-getSecret("/secrets/shop")' }, why: 'header "x-api-key"' },
  { url: `${SHOP}?token=abcgetSecret("/secrets/shop")`, headers: {}, why: 'address\'s parameter "token"' },
  { url: `${SHOP}?api_key=abc`, headers: {}, why: 'address\'s parameter "api_key"' },
  { url: "https://shop:hunter2@petshop.test/mcp", headers: {}, why: "address's password" },
])("whyNoFollowUp of $url with $headers names $why", ({ url, headers, why }) => {
  const reason = whyNoFollowUp(url, { headers });
  if (why === null) expect(reason).toBeNull();
  else expect(reason).toContain(`the connection's ${why} is written out`);
});

test("a grant that never lapses sets no renewal", async () => {
  const context = contextOfFake({ grantMs: null });
  const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
  expect(await mcp.subscribe("pet.adopted")).toMatchObject({ refreshBefore: null });
  expect(context).toMatchObject({ schedules: [] });
  await mcp.close();
});

test("the renewal's script subscribes again from the cursor, which sets the next renewal", async () => {
  vi.useFakeTimers({ toFake: ["Date"], now: NOW });
  onTestFinished(() => void vi.useRealTimers());
  const context = contextOfFake({});
  const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
  await mcp.subscribe("pet.adopted", { species: "beagle" });
  const [first] = context.schedules;
  const key = first?.set?.key;
  expect(await context.runScheduled(first)).toMatchObject({ id: "sub_1" });
  expect(context.sent.at(-1)).toMatchObject({
    method: "events/subscribe",
    params: { name: "pet.adopted", arguments: { species: "beagle" }, cursor: "7" },
  });
  // The script's first act is its claim: the same key, set to the second try, two minutes on.
  // The next renewal takes the claim's place, so the context holds one schedule for one
  // subscription at every moment.
  expect(context.schedules).toMatchObject([
    first,
    { set: { key, when: { afterMs: 2 * 60_000 } } },
    { set: { key, when: { afterMs: 40 * 60_000 } } },
  ]);
  expect(context).toMatchObject({ appended: [] });
  await mcp.close();
});

test("a renewal that fails twice, two minutes apart, tells the context that the subscription ended", async () => {
  const context = contextOfFake({});
  const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
  await mcp.subscribe("pet.adopted", { species: "beagle" });
  const [first] = context.schedules;
  const key = first?.set?.key;
  context.refuse("Forbidden: access was revoked");
  // the first try: its claim is the second try, and that stands when the try fails
  await expect(context.runScheduled(first)).rejects.toThrow("Forbidden: access was revoked");
  expect(context.schedules).toMatchObject([first, { set: { key, when: { afterMs: 120_000 } } }]);
  expect(context).toMatchObject({ appended: [] });
  // the second try, as the schedule fires it: its claim is the fact that it did not end
  await expect(context.runScheduled(context.schedules[1])).rejects.toThrow(
    "Forbidden: access was revoked",
  );
  expect(context.sent.filter(({ method }) => method === "events/subscribe")).toHaveLength(3);
  // the fact names the subscription and the server's own reason, once
  const ended = [
    {
      type: "events.iterate.com/mcp/subscription-ended",
      idempotencyKey: expect.stringMatching(/^mcp\/subscription-ended:[0-9a-f]{32}:\d+$/),
      payload: {
        server: SHOP,
        name: "pet.adopted",
        arguments: { species: "beagle" },
        error: expect.stringContaining("Forbidden: access was revoked"),
      },
    },
  ];
  expect(context.appended).toEqual(ended);
  // the last claim is a script that would have said so by itself after eleven minutes; the try
  // took it away, and nothing subscribes again
  expect(context.schedules.slice(2)).toMatchObject([
    {
      set: {
        key,
        when: { afterMs: 11 * 60_000 },
        events: [{ type: "events.iterate.com/itx/run-requested" }],
      },
    },
    { cancel: key },
  ]);
  // ONE END FOR ONE FOLLOW-UP: had the claim stayed and fired, its script writes under the same
  // key, and the log keeps the end that the try wrote
  await context.runScheduled(context.schedules[2]);
  expect(context.appended).toEqual(ended);
  await mcp.close();
});

test("a renewal with no time for a second try before the grant lapses tries once", async () => {
  vi.useFakeTimers({ toFake: ["Date"], now: NOW });
  onTestFinished(() => void vi.useRealTimers());
  const context = contextOfFake({ grantMs: 3 * 60_000 });
  const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
  await mcp.subscribe("pet.adopted");
  const [first] = context.schedules;
  expect(first).toMatchObject({ set: { when: { afterMs: 2 * 60_000 } } });
  // two minutes on, with one minute of the grant left: a second try would come after the lapse
  vi.setSystemTime(NOW + 2 * 60_000);
  context.refuse("the shop is closed");
  await expect(context.runScheduled(first)).rejects.toThrow("the shop is closed");
  expect(context.appended).toMatchObject([
    {
      type: "events.iterate.com/mcp/subscription-ended",
      payload: { name: "pet.adopted", error: expect.stringContaining("the shop is closed") },
    },
  ]);
  // its claim was the end and not a second try, and the try took it away
  expect(context.schedules.slice(1)).toMatchObject([
    { set: { when: { afterMs: 11 * 60_000 } } },
    { cancel: first?.set?.key },
  ]);
  await mcp.close();
});

test("a renewal that begins after the grant lapsed asks the server nothing, and tells the context", async () => {
  vi.useFakeTimers({ toFake: ["Date"], now: NOW });
  onTestFinished(() => void vi.useRealTimers());
  const context = contextOfFake({});
  const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
  await mcp.subscribe("pet.adopted");
  // the context was away: its schedule fires a minute after the hour's grant ended
  vi.setSystemTime(NOW + HOUR_MS + 60_000);
  expect(await context.runScheduled(context.schedules[0])).toBeNull();
  expect(context.sent.filter(({ method }) => method === "events/subscribe")).toHaveLength(1);
  expect(context.appended).toMatchObject([
    {
      type: "events.iterate.com/mcp/subscription-ended",
      payload: {
        name: "pet.adopted",
        error: `the grant lapsed at ${new Date(NOW + HOUR_MS).toISOString()}, before a renewal ran`,
      },
    },
  ]);
  expect(context.schedules.at(-1)).toEqual({ cancel: context.schedules[0]?.set?.key });
  await mcp.close();
});

test("a renewal on a context whose rules give its code no schedules tells the context at once", async () => {
  const context = contextOfFake({});
  const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
  await mcp.subscribe("pet.adopted");
  const refused = 'no rewrite rule matches "itx.schedules.set(...)"';
  const schedules = { set: async () => Promise.reject(new Error(refused)) };
  await expect(context.runScheduled(context.schedules[0], { schedules })).rejects.toThrow(refused);
  // nothing was asked of the server, and the end is no silence
  expect(context.sent.filter(({ method }) => method === "events/subscribe")).toHaveLength(1);
  expect(context.appended).toEqual([
    {
      type: "events.iterate.com/mcp/subscription-ended",
      idempotencyKey: expect.stringMatching(/^mcp\/subscription-ended:[0-9a-f]{32}:\d+$/),
      payload: {
        server: SHOP,
        name: "pet.adopted",
        arguments: {},
        error: `the follow-up could not hold its schedule: ${refused}`,
      },
    },
  ]);
  await mcp.close();
});

test("a renewal that gets a grant which the context does not renew tells the context", async () => {
  const context = contextOfFake({});
  const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
  await mcp.subscribe("pet.adopted");
  const [first] = context.schedules;
  context.grant(60_000);
  expect(await context.runScheduled(first)).toMatchObject({
    notRenewed: expect.stringContaining("the server's grant lasts 60 seconds"),
  });
  expect(context.appended).toMatchObject([
    {
      type: "events.iterate.com/mcp/subscription-ended",
      payload: { name: "pet.adopted", error: expect.stringContaining("lasts 60 seconds") },
    },
  ]);
  // the claim went with the fact: no schedule stands
  expect(context.schedules.at(-1)).toEqual({ cancel: first?.set?.key });
  await mcp.close();
});

test("a renewal that unsubscribe overtakes sets no renewal, ends what it subscribed, and writes no end", async () => {
  const context = contextOfFake({});
  const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
  await mcp.subscribe("pet.adopted");
  const [first] = context.schedules;
  // `unsubscribe` runs while the server answers the renewal: it finds the renewal's claim
  context.whileSubscribing(async () => {
    context.whileSubscribing(async () => undefined);
    await mcp.unsubscribe("pet.adopted");
  });
  expect(await context.runScheduled(first)).toMatchObject({
    notRenewed: "the subscription was ended, or subscribed again, while this renewal ran",
  });
  expect(context.schedules.map((row) => (row.set ? "set" : "cancel"))).toEqual([
    "set",
    "set",
    "cancel",
  ]);
  // the server was asked to end it twice: by `unsubscribe`, and by the renewal for what it made
  expect(context.sent.map(({ method }) => method).filter((m) => m.startsWith("events/"))).toEqual([
    "events/subscribe",
    "events/subscribe",
    "events/unsubscribe",
    "events/unsubscribe",
  ]);
  expect(context.appended).toEqual([]);

  // a renewal whose claim is gone before it asks the server asks nothing
  await mcp.subscribe("pet.created");
  const sent = context.sent.length;
  await expect(mcp.subscribe("pet.created", {}, { claim: 0 })).rejects.toThrow(
    "the subscription was ended, or subscribed again, while this renewal ran",
  );
  expect(context.sent).toHaveLength(sent);
  await mcp.close();
});

test("unsubscribe ends the renewal first, and then asks the server", async () => {
  const context = contextOfFake({});
  const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
  await mcp.subscribe("pet.adopted", { species: "beagle" });
  const key = context.schedules[0]?.set?.key;
  await mcp.unsubscribe("pet.adopted", { species: "beagle" });
  expect(context.schedules.at(-1)).toEqual({ cancel: key });
  expect(context.sent.at(-1)).toMatchObject({
    method: "events/unsubscribe",
    params: {
      name: "pet.adopted",
      arguments: { species: "beagle" },
      delivery: { url: WEBHOOK },
    },
  });
  // a subscription that this context does not renew: the server is asked, and no schedule is touched
  await mcp.unsubscribe("pet.returned");
  expect(context.schedules).toHaveLength(2);
  // when the server refuses, the renewal has ended all the same
  await mcp.subscribe("pet.created");
  context.refuse("the shop is closed");
  await expect(mcp.unsubscribe("pet.created")).rejects.toThrow("the shop is closed");
  expect(context.schedules.at(-1)).toEqual({ cancel: context.schedules.at(-2)?.set?.key });
  await mcp.close();
});

test("unsubscribe ends the renewal also when the server declares MCP Events no more", async () => {
  const context = contextOfFake({});
  const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
  await mcp.subscribe("pet.adopted");
  context.declare("none");
  // a later connection of the same context: the server's handshake names no events now
  const later = await connectToMcp(context.itx, SHOP, {}, webhook);
  await expect(later.unsubscribe("pet.adopted")).rejects.toThrow("does not declare MCP Events");
  expect(context.schedules.at(-1)).toEqual({ cancel: context.schedules[0]?.set?.key });
  expect(context.sent.filter(({ method }) => method === "events/unsubscribe")).toEqual([]);
  await mcp.close();
  await later.close();
});

test("pollEvents asks once, from the cursor it is given", async () => {
  const context = contextOfFake({});
  const mcp = await connectToMcp(context.itx, SHOP, {}, webhook);
  // exact: one poll's answer crosses as the server gave it
  expect(await mcp.pollEvents("pet.adopted", { species: "beagle" }, { cursor: "7" })).toEqual({
    events: [
      {
        eventId: "evt_8",
        name: "pet.adopted",
        timestamp: "2026-11-26T12:00:00Z",
        data: { id: "pet-1", name: "Goldie", species: "beagle" },
      },
    ],
    cursor: "8",
    truncated: false,
    hasMore: false,
    nextPollMs: 30_000,
  });
  expect(context.sent.at(-1)?.params).toEqual({
    name: "pet.adopted",
    arguments: { species: "beagle" },
    cursor: "7",
  });
  await mcp.close();
});

const webhook = () => Promise.resolve({ url: WEBHOOK, secret: "whsec_fake" });

type Scheduled = { set?: { key: unknown; when: unknown; events: unknown[] }; cancel?: unknown };

/** A context whose `fetch` reaches a fake server of MCP Events, and what it recorded: each request
 *  the server got (its method, its `Mcp-Name` header, its params, the capabilities it declared),
 *  each schedule set or cancelled, and each event appended. `runScheduled` runs the script of a
 *  schedule as the context would: with an `itx` whose `connectToMcp` is this connection's.
 *  `grantMs`: how long the server's grant lasts, or null for one that never lapses; `grant`
 *  changes it for later grants. `declared`: where the server declares MCP Events, which `declare`
 *  changes for every later connection. `whileSubscribing`: what happens on the context while the
 *  server answers `events/subscribe`. */
function contextOfFake({
  declared = "extensions",
  grantMs: firstGrantMs = HOUR_MS,
}: {
  declared?: "extensions" | "sketch" | "none";
  grantMs?: number | null;
}) {
  let grantMs = firstGrantMs;
  let declares = declared;
  let refusal: string | undefined;
  const refuseIfAsked = () => {
    if (refusal) throw new ProtocolError(-32024, refusal);
  };
  const handler = createMcpHandler(() => {
    const server = new McpServer(
      { name: "fake-petshop", version: "1" },
      {
        capabilities: {
          ...(declares === "extensions" && {
            extensions: { "io.modelcontextprotocol/events": {} },
          }),
          // the design sketch's place for it, which the SDK's type does not name
          ...(declares === "sketch" && { ...{ events: {} } }),
        },
      },
    );
    server.registerTool("unused", {}, () => ({ content: [] }));
    const AnyResult = z.looseObject({});
    const Named = z.looseObject({ name: z.string() });
    server.server.setRequestHandler(
      "events/list",
      { params: z.looseObject({ cursor: z.string().optional() }), result: AnyResult },
      ({ cursor }) => {
        const page = Number(cursor || 0);
        const name = ["pet.created", "pet.adopted", "pet.returned"][page];
        return {
          events: [{ name, delivery: ["webhook", "poll"] }],
          ...(page < 2 && { nextCursor: String(page + 1) }),
        };
      },
    );
    server.server.setRequestHandler(
      "events/subscribe",
      { params: Named, result: AnyResult },
      async () => {
        refuseIfAsked();
        await subscribing?.();
        return {
          id: "sub_1",
          refreshBefore: grantMs === null ? null : new Date(Date.now() + grantMs).toISOString(),
          cursor: "7",
          truncated: false,
          deliveryStatus: { active: true, lastError: null },
        };
      },
    );
    server.server.setRequestHandler(
      "events/unsubscribe",
      { params: Named, result: AnyResult },
      () => {
        refuseIfAsked();
        return {};
      },
    );
    server.server.setRequestHandler("events/poll", { params: Named, result: AnyResult }, () => ({
      events: [
        {
          eventId: "evt_8",
          name: "pet.adopted",
          timestamp: "2026-11-26T12:00:00Z",
          data: { id: "pet-1", name: "Goldie", species: "beagle" },
        },
      ],
      cursor: "8",
      truncated: false,
      hasMore: false,
      nextPollMs: 30_000,
    }));
    return server;
  });
  const sent: { method: string; name: string | null; params: unknown; capabilities: unknown }[] =
    [];
  const schedules: Scheduled[] = [];
  const appended: { idempotencyKey?: string }[] = [];
  // as the log: a key that comes back with the same body writes nothing, and with another body
  // it is refused
  const append = async (event: { idempotencyKey?: string }) => {
    const kept = appended.find(
      (row) => event.idempotencyKey && row.idempotencyKey === event.idempotencyKey,
    );
    if (!kept) return void appended.push(event);
    if (JSON.stringify(kept) !== JSON.stringify(event))
      throw Object.assign(new Error(`${String(event.idempotencyKey)}: another body`), {
        code: "IDEMPOTENCY_CONFLICT",
      });
  };
  // THE CONTEXT'S SCHEDULES, as the kernel keeps them: `schedules` is every `set` and `cancel` in
  // order, and a row's place is its offset. The schedule of a key stands while its newest row is
  // a `set` that has not fired. A receipt cancels the one definition that it names.
  const fired = new Set<Scheduled>();
  const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
  const standing = (key: unknown) => {
    const at = schedules.findLastIndex((row) => same(row.set?.key, key) || same(row.cancel, key));
    const row = schedules[at];
    return row?.set && !fired.has(row) ? { ...row.set, scheduledAtOffset: at } : null;
  };
  const Receipt = z.object({ key: z.string(), scheduledAtOffset: z.number() });
  const scheduleTable = {
    set: async (set: NonNullable<Scheduled["set"]>) => ({
      key: JSON.stringify(set.key),
      scheduledAtOffset: schedules.push({ set }) - 1,
    }),
    get: async (key: unknown) => standing(key),
    cancel: async (named: unknown) => {
      const receipt = Receipt.safeParse(named);
      if (!receipt.success) return void schedules.push({ cancel: named });
      const key: unknown = JSON.parse(receipt.data.key);
      if (standing(key)?.scheduledAtOffset === receipt.data.scheduledAtOffset)
        schedules.push({ cancel: key });
    },
  };
  let subscribing: (() => Promise<void>) | undefined;
  const Sent = z.object({
    method: z.string(),
    params: z
      .looseObject({
        _meta: z
          .looseObject({ "io.modelcontextprotocol/clientCapabilities": z.unknown() })
          .optional(),
      })
      .optional(),
  });
  const itx = {
    fetch: async (request: Request) => {
      if (request.method === "POST") {
        const { method, params: { _meta, ...params } = {} } = Sent.parse(
          await request.clone().json(),
        );
        sent.push({
          method,
          name: request.headers.get("mcp-name"),
          params,
          capabilities: _meta?.["io.modelcontextprotocol/clientCapabilities"],
        });
      }
      return await handler.fetch(request);
    },
    builtins: { schedules: scheduleTable },
    // the cast: the connection uses `fetch` and its schedules alone of a context's itx
  } as unknown as LibraryItx;
  return {
    itx,
    sent,
    schedules,
    appended,
    refuse: (message: string) => void (refusal = message),
    declare: (next: typeof declares) => void (declares = next),
    grant: (ms: number) => void (grantMs = ms),
    whileSubscribing: (hook: () => Promise<void>) => void (subscribing = hook),
    runScheduled: async (scheduled: Scheduled | undefined, masked?: { schedules: unknown }) => {
      const { code } = z
        .object({ payload: z.object({ code: z.string() }) })
        .parse(scheduled?.set?.events[0]).payload;
      // a schedule that fires is the context's no more
      if (scheduled) fired.add(scheduled);
      // the script is the text of a function of the context's itx, as the kernel runs it
      const script: (itx: unknown) => Promise<unknown> = runInThisContext(`(${code})`);
      return await script({
        connectToMcp: (server: string, options: { headers?: Record<string, string> }) =>
          connectToMcp(itx, server, options, webhook),
        append,
        schedules: scheduleTable,
        // what the context's rules take from its own code, for a context that is held
        ...masked,
      });
    },
  };
}