iterate.com / cloud

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

cloud / internal-packages / dummy-petshop / src / pet-events.test.tsmain at aacbc74

/**
 * What happens to an account's pets leaves the shop with nobody asking (pet-events.ts, mcp.ts): by
 * MCP Events' poll and push delivery, by a held `wait_for_pet_event` call, and by an MCP task of
 * that call. The walk-in visitor (walk-in.ts) is the shop acting by itself.
 */
import { Webhook } from "standardwebhooks";
import { expect, test, vi } from "vitest";
import { handleMcpRequest, type McpToolContext } from "./mcp.ts";
import { memoryPetshop } from "./memory-state.ts";
import { adoptPet } from "./pet-events.ts";
import { handlePetStream } from "./pet-stream.ts";
import { seedPets } from "./pets.ts";
import { handleWalkIn } from "./walk-in.ts";

const [biscuit, goldie] = seedPets() as [
  ReturnType<typeof seedPets>[0],
  ReturnType<typeof seedPets>[0],
];

test("the shop says that it has events, where SEP-3415 puts it and where ChatGPT reads it", async () => {
  const [{ result }] = await call(contextOf(), "server/discover");
  expect(result.capabilities).toMatchObject({
    events: {},
    extensions: { "io.modelcontextprotocol/events": {}, "io.modelcontextprotocol/tasks": {} },
  });
  const [listed] = await call(contextOf(), "events/list");
  expect(listed.result.events.map((event: { name: string }) => event.name)).toEqual([
    "pet.created",
    "pet.adopted",
    "pet.returned",
  ]);
  expect(listed.result.events[1]).toMatchObject({ delivery: ["webhook", "poll", "push"] });
});

test("events/poll answers the events after a cursor, of the event and species it names", async () => {
  const context = contextOf();
  const poll = async (params: Record<string, unknown>) =>
    (await call(context, "events/poll", params))[0].result;

  // no cursor: from now
  const start = await poll({ name: "pet.adopted", cursor: null });
  expect(start).toMatchObject({ events: [], cursor: "0", truncated: false, hasMore: false });

  await adoptPet(context.state, context.owner, goldie, "walk-in visitor");
  await adoptPet(context.state, context.owner, biscuit, "account");
  // adopting an adopted pet says nothing
  expect(await adoptPet(context.state, context.owner, biscuit, "account")).toBeNull();
  // another account's adoption is not this account's event
  await adoptPet(context.state, "bo@example.com", goldie, "account");

  const both = await poll({ name: "pet.adopted", cursor: start.cursor });
  expect(both).toMatchObject({
    events: [
      { name: "pet.adopted", data: { ...goldie, by: "walk-in visitor" } },
      { name: "pet.adopted", data: { ...biscuit, by: "account" } },
    ],
    cursor: "3",
    hasMore: false,
  });
  expect(both.events[0]).toMatchObject({ eventId: expect.stringMatching(/^evt_/) });
  // poll carries the cursor on the answer alone
  expect(both.events[0]).not.toHaveProperty("cursor");

  expect(
    await poll({ name: "pet.adopted", arguments: { species: "beagle" }, cursor: "0" }),
  ).toMatchObject({
    events: [{ data: biscuit }],
  });
  // one at a time: the cursor is the place of the last event answered
  expect(await poll({ name: "pet.adopted", cursor: "0", maxEvents: 1 })).toMatchObject({
    events: [{ data: goldie }],
    cursor: "1",
    hasMore: true,
  });
  expect(await poll({ name: "pet.adopted", cursor: both.cursor })).toMatchObject({ events: [] });
  expect(await poll({ name: "pet.returned", cursor: "0" })).toMatchObject({ events: [] });
});

test("a held wait_for_pet_event call answers at the moment a walk-in visitor adopts a pet", async () => {
  const context = contextOf();
  const waiting = call(context, "tools/call", {
    name: "wait_for_pet_event",
    arguments: { waitSeconds: 20 },
  });
  let answered = false;
  void waiting.then(() => (answered = true));
  await new Promise((resolve) => setTimeout(resolve, 50));
  expect(answered).toBe(false);

  const visit = await handleWalkIn(
    new Request("https://petshop.example/__test-controls/pets", {
      method: "POST",
      body: JSON.stringify({ account: context.owner, action: "adopt", name: "goldie" }),
    }),
    context,
  );
  expect(await visit!.json()).toMatchObject({
    events: [{ name: "pet.adopted", data: { ...goldie, by: "walk-in visitor" } }],
    pets: [biscuit, { ...goldie, adopted: true }],
  });

  const [{ result }] = await waiting;
  expect(result.structuredContent).toMatchObject({
    events: [{ name: "pet.adopted", data: { ...goldie, by: "walk-in visitor" }, cursor: "1" }],
    cursor: "1",
    pets: [biscuit, { ...goldie, adopted: true }],
  });

  // with nothing new the call answers when its wait ends, and the cursor goes on from there
  const [quiet] = await call(context, "tools/call", {
    name: "wait_for_pet_event",
    arguments: { cursor: "1", waitSeconds: 0.05 },
  });
  expect(quiet.result.structuredContent).toMatchObject({ events: [], cursor: "1" });

  // the pets come back, and the wait hears each
  await handleWalkIn(
    new Request("https://petshop.example/__test-controls/pets", {
      method: "POST",
      body: JSON.stringify({ account: context.owner, action: "return" }),
    }),
    context,
  );
  const [back] = await call(context, "tools/call", {
    name: "wait_for_pet_event",
    arguments: { cursor: "1" },
  });
  expect(back.result.structuredContent).toMatchObject({
    events: [{ name: "pet.returned", data: goldie }],
    pets: [biscuit, goldie],
  });
});

test("a client that follows MCP tasks gets a task, which is done once the shop has an event", async () => {
  const context = contextOf();
  const tasks = { extensions: { "io.modelcontextprotocol/tasks": {} } };
  const [{ result: task }] = await call(
    context,
    "tools/call",
    { name: "wait_for_pet_event", arguments: {} },
    tasks,
  );
  expect(task).toMatchObject({
    resultType: "task",
    taskId: expect.stringMatching(/^pet-watch-0-\d+$/),
    status: "working",
    ttlMs: null,
    pollIntervalMs: 2000,
    // the SDK adds the empty `content` of a tool's answer, which a task does not need
    content: [],
  });

  const get = async () =>
    (await call(context, "tasks/get", { taskId: task.taskId }, tasks))[0].result;
  expect(await get()).toMatchObject({ resultType: "complete", status: "working" });

  await adoptPet(context.state, context.owner, biscuit, "walk-in visitor");
  expect(await get()).toMatchObject({
    resultType: "complete",
    taskId: task.taskId,
    status: "completed",
    createdAt: task.createdAt,
    result: {
      structuredContent: {
        events: [{ name: "pet.adopted", data: { ...biscuit, by: "walk-in visitor" } }],
        pets: [{ ...biscuit, adopted: true }, goldie],
      },
    },
  });

  // the finished wait tells a model how to go on watching
  expect(await get()).toMatchObject({
    result: { structuredContent: { next: expect.stringContaining('cursor "1"') } },
  });
  // a cancel is acknowledged with nothing else
  expect(await call(context, "tasks/cancel", { taskId: task.taskId }, tasks)).toEqual([
    { jsonrpc: "2.0", id: 1, result: { resultType: "complete" } },
  ]);

  const [unknown] = await call(context, "tasks/get", { taskId: "build-7" }, tasks);
  expect(unknown.error).toMatchObject({ code: -32602 });
  // a client without the extension holds the call instead
  const [{ result: held }] = await call(context, "tools/call", {
    name: "wait_for_pet_event",
    arguments: { cursor: "0" },
  });
  expect(held).toMatchObject({ resultType: "complete", structuredContent: { cursor: "1" } });
});

test("a webhook subscription to pet.adopted gets the walk-in visitor's adoption, signed", async () => {
  const context = contextOf();
  const secret = `whsec_${btoa("0123456789abcdef0123456789abcdef")}`;
  // the subscriber's callback: it echoes the challenge, then takes each event
  const posted: { headers: Headers; body: string }[] = [];
  vi.stubGlobal("fetch", async (_url: string, init: { headers: HeadersInit; body: string }) => {
    posted.push({ headers: new Headers(init.headers), body: init.body });
    return Response.json({ challenge: JSON.parse(init.body).challenge });
  });
  const [{ result: subscription }] = await call(context, "events/subscribe", {
    name: "pet.adopted",
    arguments: { species: "goldfish" },
    delivery: { mode: "webhook", url: "https://subscriber.example/hook", secret },
  });
  expect(subscription).toMatchObject({ id: expect.stringMatching(/^sub_[0-9a-f]{16}$/) });

  // a beagle's adoption is not this subscription's event; a goldfish's is
  await adoptPet(context.state, context.owner, biscuit, "account");
  const visit = await adoptPet(context.state, context.owner, goldie, "walk-in visitor");
  expect(visit).toMatchObject({ deliveries: [{ id: subscription.id, status: 200 }] });
  vi.unstubAllGlobals();

  expect(posted).toHaveLength(2);
  const [, { headers, body }] = posted as [unknown, (typeof posted)[0]];
  expect(headers.get("x-mcp-subscription-id")).toBe(subscription.id);
  // Standard Webhooks: the subscriber's own check of the signature
  expect(new Webhook(secret).verify(body, Object.fromEntries(headers))).toMatchObject({
    eventId: headers.get("webhook-id"),
    name: "pet.adopted",
    data: { ...goldie, by: "walk-in visitor" },
    cursor: "2",
  });
});

test("the gallery's watch_pets answers the address of its own stream, on which the shop pushes", async () => {
  const context = contextOf();
  // never a task, whatever the host's client follows: the gallery reads the answer itself
  const [{ result }] = await call(
    context,
    "tools/call",
    { name: "watch_pets", arguments: { waitSeconds: 0 } },
    { extensions: { "io.modelcontextprotocol/tasks": {} } },
  );
  const { stream, cursor } = result.structuredContent;
  expect(result).toMatchObject({ resultType: "complete", structuredContent: { events: [] } });
  expect(stream).toMatch(/^https:\/\/petshop\.example\/pets\/stream\?ticket=/);

  // the frame holds no token: the ticket in the address is all it has, and any origin may ask
  const response = (await handlePetStream(new Request(`${stream}&cursor=${cursor}`), context))!;
  expect(response.headers.get("content-type")).toBe("text/event-stream");
  expect(response.headers.get("access-control-allow-origin")).toBe("*");
  const messages = sseMessages(response);
  await adoptPet(context.state, context.owner, goldie, "walk-in visitor");
  expect((await messages.next()).value).toMatchObject({
    events: [{ name: "pet.adopted", data: { ...goldie, by: "walk-in visitor" } }],
    cursor: "1",
    pets: [biscuit, { ...goldie, adopted: true }],
  });
  await messages.return(undefined);

  const forged = await handlePetStream(
    new Request("https://petshop.example/pets/stream?ticket=abc"),
    context,
  );
  expect(forged).toMatchObject({ status: 401 });
  expect(await handlePetStream(new Request("https://petshop.example/pets"), context)).toBeNull();
});

test("events/stream says it is active, then sends each event on the open request", async () => {
  const context = contextOf();
  const response = await post(context, "events/stream", { name: "pet.adopted", cursor: null });
  expect(response.headers.get("content-type")).toContain("text/event-stream");
  const messages = sseMessages(response);
  expect((await messages.next()).value).toMatchObject({
    method: "notifications/events/active",
    params: {
      cursor: "0",
      truncated: false,
      heartbeatMs: 15000,
      _meta: { "io.modelcontextprotocol/subscriptionId": 1 },
    },
  });
  await adoptPet(context.state, context.owner, goldie, "walk-in visitor");
  expect((await messages.next()).value).toMatchObject({
    method: "notifications/events/event",
    params: {
      name: "pet.adopted",
      data: { ...goldie, by: "walk-in visitor" },
      cursor: "1",
      _meta: { "io.modelcontextprotocol/subscriptionId": 1 },
    },
  });
  await messages.return(undefined);
});

/** One request of protocol revision 2026-07-28, with the capabilities the client sends in it. */
function post(
  context: McpToolContext,
  method: string,
  params: Record<string, unknown> = {},
  clientCapabilities: Record<string, unknown> = {},
) {
  const headers = new Headers({
    "content-type": "application/json",
    accept: "application/json, text/event-stream",
    "mcp-protocol-version": "2026-07-28",
    "mcp-method": method,
  });
  // the transport's routing header: the tool, the event or the task that the request names
  const named = params.name ?? params.taskId;
  if (typeof named === "string") headers.set("mcp-name", named);
  return handleMcpRequest(
    new Request("https://petshop.example/mcp", {
      method: "POST",
      headers,
      body: JSON.stringify({
        jsonrpc: "2.0",
        id: 1,
        method,
        params: {
          ...params,
          _meta: {
            "io.modelcontextprotocol/protocolVersion": "2026-07-28",
            "io.modelcontextprotocol/clientCapabilities": clientCapabilities,
          },
        },
      }),
    }),
    context,
  );
}

/** The messages of an answer: the one of a JSON body, or each of a stream that ended. */
async function call(...args: Parameters<typeof post>) {
  const response = await post(...args);
  if (response.headers.get("content-type")?.includes("application/json"))
    return [(await response.json()) as { result?: any; error?: any }];
  const messages = [];
  for await (const message of sseMessages(response)) messages.push(message);
  return messages as { result?: any; error?: any }[];
}

/** The JSON-RPC messages of a server-sent event stream, as they arrive. */
async function* sseMessages(response: Response) {
  const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader();
  try {
    for (let text = ""; ;) {
      const { done, value } = await reader.read();
      if (done) return;
      text += value;
      for (let end = text.indexOf("\n\n"); end >= 0; end = text.indexOf("\n\n")) {
        const data = text
          .slice(0, end)
          .split("\n")
          .find((line) => line.startsWith("data: "));
        text = text.slice(end + 2);
        if (data) yield JSON.parse(data.slice(6));
      }
    }
  } finally {
    await reader.cancel();
  }
}

function contextOf(): McpToolContext {
  return {
    ...memoryPetshop(),
    owner: "ada@example.com",
    pets: seedPets(),
    origin: "https://petshop.example",
  };
}