iterate.com / cloud

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

cloud / internal-packages / dummy-petshop / src / mcp.tsmain at aacbc74

/**
 * The pet shop as an MCP server, served at `GET|POST /mcp` over the modern
 * streamable-HTTP transport (the shape createMcpHandler produces). It exposes
 * the shop's pets as MCP tools:
 *
 *   - `list_pets`      — the account's pets.
 *   - `get_pet(id)`    — one pet by id.
 *   - `create_pet(...)`— add a pet to the account.
 *
 * one MCP App (the extension io.modelcontextprotocol/ui; mcp-app.ts is its page):
 *
 *   - `show_pets`      — the pets as a gallery: a host that supports MCP Apps draws the UI
 *                        resource `ui://petshop/pets.html` in a sandboxed frame, and any other
 *                        client reads the same pets as text.
 *   - `open_pet_shop`  — the same gallery, opened large: its resource says
 *                        `preferredDisplayMode: "fullscreen"`, on which Claude opens a view in its
 *                        side panel with no click. A host that does not read it shows it inline.
 *   - `adopt_pet`      — mark a pet adopted, by its id or its name. A person presses Adopt in
 *                        the gallery, or tells the model "adopt Goldie": both call it.
 *   - `watch_pets`     — the gallery's own call (`visibility: ["app"]`), which the shop holds
 *                        open until something happens to the pets. MCP Apps has no way to push
 *                        to a frame that is open, so the gallery keeps one such call open, or
 *                        opens the stream whose address the call answers (pet-stream.ts).
 *
 * one tool by which a model waits for the shop:
 *
 *   - `wait_for_pet_event` — answers once something happens to the pets. To a client that
 *                        follows MCP tasks (`io.modelcontextprotocol/tasks`) the answer is a
 *                        task, which that client asks about until it is done: in Claude a
 *                        finished task starts a turn with nobody typing. Any other client's
 *                        call is held open.
 *
 * one tool that makes the shop act by itself, behind the scenes (shop-day.ts):
 *
 *   - `simulate_shop_activity` — a few things happen to the account's pets on a clock, with no
 *                        further call: a pet comes in, a visitor adopts one, it comes back. The
 *                        same begins by itself, once an hour, when a client starts to watch a
 *                        shop: a new webhook subscription, a stream, a `wait_for_pet_event` call.
 *
 * and three events of the MCP Events extension (`io.modelcontextprotocol/events`, SEP-3415,
 * github.com/modelcontextprotocol/ext-events; pet-events.ts lists them), in its three delivery
 * modes:
 *
 *   - `pet.created`    — `create_pet` added a pet, or one came into the shop by itself.
 *   - `pet.adopted`    — the account's client adopted a pet, or a walk-in visitor did (walk-in.ts).
 *   - `pet.returned`   — an adopted pet is up for adoption again.
 *
 * `{ species }` filters each. Poll (`events/poll`) reads the shop's list of events after a
 * cursor. Push (`events/stream`) holds the request open and sends each event on it. Webhook
 * (`events/subscribe`) verifies the callback with a signed challenge, then keeps the
 * subscription for an hour, and each matching event is POSTed to it.
 *
 * Auth is the same OAuth bearer token as the rest of the shop: the worker
 * resolves it with `accessGrant` (worker.ts) before ever calling this handler,
 * then passes the authenticated owner + request-scoped pet catalogue through
 * as the MCP `authInfo.extra`, so tool bodies never see the raw token.
 *
 * This makes the pet shop a real remote MCP server for the OS outbound-MCP
 * integration work.
 */
import { McpServer, ProtocolError, createMcpHandler } from "@modelcontextprotocol/server";
import { z } from "zod";
import { MCP_APP_MIME_TYPE, PETS_APP_HTML, PETS_APP_URI, PETS_PANEL_URI } from "./mcp-app.ts";
import {
  PET_EVENT_NAMES,
  PET_EVENTS,
  adoptPet,
  emitPetEvent,
  occurrenceOf,
  petsOf,
  postSigned,
} from "./pet-events.ts";
import { petStreamUrl } from "./pet-stream.ts";
import { ASKED_DAY, AUTO_DAY, dayOf } from "./shop-day.ts";
import type { Pet } from "./pets.ts";
import {
  PET_EVENTS_LONGEST_WAIT_MS,
  SHOP_DAY_LEAST_EVERY_MS,
  SHOP_DAY_MOST_EVERY_MS,
  SHOP_DAY_MOST_HAPPENINGS,
  type PetEvent,
  type PetEventsRead,
  type ShopDeps,
} from "./state.ts";

/**
 * The authenticated principal + request-scoped catalogue threaded to the MCP
 * tools, and the state its event subscriptions live in. Carried on
 * `authInfo.extra` because createMcpHandler builds a fresh McpServer per
 * request and hands the factory the request's `authInfo`.
 */
export interface McpToolContext extends ShopDeps {
  owner: string;
  pets: Pet[];
  /** The origin the request came to: where the gallery's own stream is (pet-stream.ts). */
  origin: string;
}

const asText = (value: unknown) => ({
  content: [{ type: "text" as const, text: JSON.stringify(value, null, 2) }],
});

/** A result that a model reads as text and an MCP App reads as data: the same JSON, both ways. */
const asData = (value: Record<string, unknown>) => ({ ...asText(value), structuredContent: value });

/** What a subscription listens for, in every delivery mode: the event and its arguments. */
const Listened = z.object({
  name: z.enum(PET_EVENT_NAMES),
  arguments: z.strictObject({ species: z.string().optional() }).default({}),
});

/** A cursor is the place of an event in the shop's list (state.ts `PetEvent.seq`), as a string;
 *  none, or `null`, means from now. */
const Cursor = z.string().regex(/^\d+$/).nullish();

/** `events/poll`, and `events/stream` with the same fields. */
const PollParams = Listened.extend({
  cursor: Cursor,
  maxAgeMs: z.number().nonnegative().optional(),
  maxEvents: z.int().positive().optional(),
});

/** How long one `events/stream` request lasts before the shop ends it and the client opens the
 *  next with its cursor, and how often a quiet stream says that it is alive. */
const STREAM_LASTS_MS = 4 * 60 * 1000;
const STREAM_HEARTBEAT_MS = 15_000;

const cursorOf = (cursor: string | null | undefined) => (cursor ? Number(cursor) : null);

/** The events not older than `maxAgeMs`, and whether that skipped any. */
const notOlderThan = (events: PetEvent[], maxAgeMs?: number) => {
  if (maxAgeMs === undefined) return { events, skipped: false };
  const kept = events.filter((event) => Date.parse(event.timestamp) >= Date.now() - maxAgeMs);
  return { events: kept, skipped: kept.length < events.length };
};

/** What a wait answers: the account's events after a cursor, the cursor to go on from, and the
 *  pets as they are now. */
const eventsAndPets = async ({ owner, pets, state }: McpToolContext, read: PetEventsRead) => ({
  owner,
  events: read.events.map(occurrenceOf),
  cursor: String(read.cursor),
  truncated: read.truncated,
  pets: await petsOf(state, owner, pets),
  // one wait hears one change: a model that was asked to watch must wait again
  next: `Tell the person what happened. To go on watching, call wait_for_pet_event again with cursor "${read.cursor}".`,
});

/** The arguments of a wait: where it goes on from, and how long the call is held open. */
const waitInput = {
  cursor: z
    .string()
    .regex(/^\d+$/)
    .optional()
    .describe("The `cursor` of the last answer. Without it the wait starts now."),
  waitSeconds: z
    .number()
    .min(0)
    .max(PET_EVENTS_LONGEST_WAIT_MS / 1000)
    .optional()
    .describe("How long the call is held open. 25 without it."),
};

/** A `tasks/get` or `tasks/cancel` request of the tasks extension. */
const TaskRequest = z.object({
  id: z.union([z.string(), z.number()]),
  method: z.enum(["tasks/get", "tasks/cancel"]),
  params: z.object({ taskId: z.string() }),
});

/** A request's envelope (`ctx.mcpReq.envelope`, which the SDK types as empty) of a client that
 *  follows MCP tasks: it names the tasks extension in the capabilities it sends with the request. */
const FollowsTasks = z.looseObject({
  "io.modelcontextprotocol/clientCapabilities": z.looseObject({
    extensions: z.looseObject({ "io.modelcontextprotocol/tasks": z.looseObject({}) }),
  }),
});

/** The task of one `wait_for_pet_event` call while nothing happened yet, as the tasks extension
 *  describes a task. Its id is the cursor it waits after and when it began (epoch ms). */
const petWatchTask = (after: number, createdAt: number) => ({
  taskId: `pet-watch-${after}-${createdAt}`,
  status: "working",
  statusMessage: "Waiting for something to happen to the pets",
  createdAt: new Date(createdAt).toISOString(),
  lastUpdatedAt: new Date().toISOString(),
  ttlMs: null,
  pollIntervalMs: 2000,
});

/**
 * MCP tasks (`io.modelcontextprotocol/tasks`), for `wait_for_pet_event` alone: the answer to a
 * `tasks/get` or `tasks/cancel` request, or null for any other. A task's id holds all there is to
 * know of it, so the shop keeps nothing: the task is done once the account has an event after the
 * id's cursor. These two are answered here because SDK 2.1.0 answers "Method not found" to the
 * extension's methods; it does pass a tool's task answer through.
 */
async function petWatchTaskResponse(
  request: Request,
  context: McpToolContext,
): Promise<Response | null> {
  // a client of revision 2026-07-28 names the method in this header, so no other body is read
  if (!request.headers.get("mcp-method")?.startsWith("tasks/")) return null;
  const message = TaskRequest.safeParse(
    await request
      .clone()
      .json()
      .catch(() => null),
  );
  if (!message.success) return null;
  const { id, method, params } = message.data;
  const [, cursor, began] = /^pet-watch-(\d+)-(\d+)$/.exec(params.taskId) || [];
  // the tasks extension's answer to an id that the server does not know
  if (!cursor || !began)
    return Response.json({
      jsonrpc: "2.0",
      id,
      error: { code: -32602, message: `Unknown task ${params.taskId}` },
    });
  const task = petWatchTask(Number(cursor), Number(began));
  const read = await context.state.petEventsAfter(context.owner, Number(cursor));
  const happened = read.events.length > 0 || read.truncated;
  // the extension's answer to a cancel is an empty acknowledgement
  if (method === "tasks/cancel")
    return Response.json({ jsonrpc: "2.0", id, result: { resultType: "complete" } });
  return Response.json({
    jsonrpc: "2.0",
    id,
    result: {
      resultType: "complete",
      ...task,
      ...(happened && {
        status: "completed",
        statusMessage: read.events.map(({ name, data }) => `${name}: ${data.name}`).join(", "),
        result: asData(await eventsAndPets(context, read)),
      }),
    },
  });
}

/** What names a webhook subscription besides its owner: the event, its arguments and the
 *  callback URL. */
const SubscriptionKey = Listened.extend({
  delivery: z.object({ url: z.url({ protocol: /^https$/ }) }),
});
const SubscribeParams = SubscriptionKey.extend({
  delivery: SubscriptionKey.shape.delivery.extend({
    mode: z.literal("webhook"),
    // Standard Webhooks: base64 of 24 to 64 bytes
    secret: z.string().regex(/^whsec_[A-Za-z0-9+/]{32,86}={0,2}$/),
  }),
});

// One handler at module scope; the factory runs per request and reads the
// authenticated context off the authInfo the worker passed in.
const mcpHandler = createMcpHandler(({ authInfo }) => {
  // handleMcpRequest (below), this handler's only caller, always passes an McpToolContext as the
  // authInfo's `extra`, which the SDK types as a plain record
  const context = authInfo!.extra as unknown as McpToolContext;
  const { owner, pets, state } = context;
  // The gallery may open a connection of its own to the shop (pet-stream.ts): a host builds the
  // frame's content security policy from this, and allows no network at all without it.
  const galleryMeta = { ui: { prefersBorder: true, csp: { connectDomains: [context.origin] } } };
  const server = new McpServer(
    { name: "dummy-petshop", version: "2.0.0" },
    {
      capabilities: {
        // SEP-3415's place for it, which a client of revision 2026-07-28 reads; and the tasks
        // extension, by which `wait_for_pet_event` answers such a client with a task
        extensions: { "io.modelcontextprotocol/events": {}, "io.modelcontextprotocol/tasks": {} },
        // and the design sketch's, which ChatGPT reads
        // (developers.openai.com/plugins/build/mcp-events). Spread, because the SDK's type of the
        // capabilities has no such key.
        ...{ events: {} },
      },
    },
  );

  /** The account's pets, each marked `adopted` once the account or a visitor adopted it. */
  const listed = () => petsOf(state, owner, pets);

  /** A client began to watch the account's pets: a quiet shop makes a few things happen by
   *  itself, so there is something to hear (shop-day.ts; once an hour for an account). */
  const watched = () => state.startShopDay(owner, AUTO_DAY);

  /** The account's events after `cursor` that a subscription to `name` and `species` hears. */
  const heard = (events: PetEvent[], { name, arguments: { species } }: z.output<typeof Listened>) =>
    events.filter(
      (event) => event.name === name && (species || event.data.species) === event.data.species,
    );

  server.registerTool(
    "list_pets",
    {
      description:
        "List the authenticated account's (entirely fictional) pets. One that the account adopted says `adopted: true`.",
    },
    async () => asText({ owner, pets: await listed() }),
  );

  server.registerTool(
    "get_pet",
    {
      description: "Fetch one pet by its id.",
      inputSchema: { id: z.string().describe("The pet id, e.g. pet-1.") },
    },
    async ({ id }) => {
      const pet = (await listed()).find((candidate) => candidate.id === id);
      if (!pet) {
        return {
          isError: true,
          content: [{ type: "text" as const, text: `No pet with id ${id}` }],
        };
      }
      return asText(pet);
    },
  );

  server.registerTool(
    "create_pet",
    {
      description: "Add a pet to the authenticated account.",
      inputSchema: {
        name: z.string().min(1).describe("The pet's name."),
        species: z.string().min(1).describe("The pet's species, e.g. beagle."),
      },
    },
    async ({ name, species }) => {
      const pet: Pet = { id: `pet-${pets.length + 1}`, name, species };
      pets.push(pet);
      const { deliveries } = await emitPetEvent(state, owner, "pet.created", pet);
      // a subscriber that does not take the event fails the call, so nothing is lost unseen
      const refused = deliveries.find(({ status }) => status < 200 || status > 299);
      if (refused) throw new Error(`${refused.url} answered ${refused.status}`);
      return asText(pet);
    },
  );

  server.registerResource(
    "pet-gallery",
    PETS_APP_URI,
    { title: "Pet gallery", mimeType: MCP_APP_MIME_TYPE, _meta: galleryMeta },
    (uri) => ({
      contents: [
        { uri: uri.href, mimeType: MCP_APP_MIME_TYPE, text: PETS_APP_HTML, _meta: galleryMeta },
      ],
    }),
  );

  /** What both gallery tools answer: the account's pets, of one species when one is named. */
  const shown = async ({ species }: { species?: string }) => {
    const all = await listed();
    return asData({ owner, pets: species ? all.filter((pet) => pet.species === species) : all });
  };
  const speciesInput = { species: z.string().optional().describe("One species, e.g. beagle.") };

  server.registerTool(
    "show_pets",
    {
      title: "Show the pets",
      description:
        "Show the authenticated account's pets that are up for adoption as an interactive gallery in the conversation. A person can adopt one there. The gallery stays live: after `adopt_pet`, or when the shop changes by itself, it shows the change by itself, so do not show it again. `species` limits it to one species. `open_pet_shop` shows the same gallery large.",
      inputSchema: speciesInput,
      // the nested key is the extension's; hosts older than it read the flat one
      _meta: { ui: { resourceUri: PETS_APP_URI }, "ui/resourceUri": PETS_APP_URI },
    },
    shown,
  );

  // The same page as a second resource, which asks to open large. Claude reads
  // `preferredDisplayMode` on the content item of `resources/read` and moves the view into its
  // side panel once, with no click (claude.com/docs/connectors/building/mcp-apps/display-modes).
  // It is no part of the MCP Apps specification, hence the cast.
  const panelMeta = { ui: { ...galleryMeta.ui, preferredDisplayMode: "fullscreen" } };
  server.registerResource(
    "pet-gallery-large",
    PETS_PANEL_URI,
    { title: "Pet gallery, large", mimeType: MCP_APP_MIME_TYPE, _meta: galleryMeta },
    (uri) => ({
      contents: [
        {
          uri: uri.href,
          mimeType: MCP_APP_MIME_TYPE,
          text: PETS_APP_HTML,
          _meta: panelMeta as typeof galleryMeta,
        },
      ],
    }),
  );

  server.registerTool(
    "open_pet_shop",
    {
      title: "Open the pet shop large",
      description:
        "Open the pet gallery as a large view: in a panel beside the conversation where the client has one. Call it when the person asks for the shop or the pets large, in a panel, beside the chat, full screen, or to keep the shop open while they talk. The view stays live like the one of `show_pets`. `species` limits it to one species.",
      inputSchema: speciesInput,
      _meta: { ui: { resourceUri: PETS_PANEL_URI } },
    },
    shown,
  );

  server.registerTool(
    "adopt_pet",
    {
      title: "Adopt a pet",
      description:
        'Adopt a pet for the person, by its id or by its name ("Goldie"). Call it when the person asks you to adopt a pet. A pet gallery that is open shows the adoption within seconds.',
      inputSchema: {
        id: z.string().optional().describe("The pet id, e.g. pet-1."),
        name: z
          .string()
          .optional()
          .describe("The pet's name, e.g. Goldie. Letter case is ignored."),
      },
      // the model and the gallery's Adopt button both call it
      _meta: { ui: { visibility: ["model", "app"] } },
    },
    async ({ id, name }) => {
      const wanted = name?.trim().toLowerCase();
      const pet = (await listed()).find((candidate) =>
        id ? candidate.id === id : Boolean(wanted) && candidate.name.toLowerCase() === wanted,
      );
      if (!pet) {
        const what = id ? `id ${id}` : `the name ${name || "(none given)"}`;
        return { isError: true, content: [{ type: "text" as const, text: `No pet with ${what}` }] };
      }
      await adoptPet(state, owner, pet, "account");
      return asData({ owner, pet: { ...pet, adopted: true }, pets: await listed() });
    },
  );

  server.registerTool(
    "wait_for_pet_event",
    {
      title: "Wait for the pet shop to change",
      description:
        "Wait until something happens to the account's pets: one is adopted (by the account, or by a visitor who walks into the shop), comes back, or is added. Call it when the person asks to watch the shop, or to be told or shown when something happens. A quiet shop that is watched makes a few things happen by itself within about a minute, once an hour; `simulate_shop_activity` makes more happen. The shop answers when it happens: at once to a client that follows MCP tasks, which then gets the result later, and otherwise by holding the call open for at most `waitSeconds`. An answer with no events means nothing happened yet: call again with the `cursor` it gave. The answer has the events and the pets as they are now.",
      inputSchema: waitInput,
      // the gallery has `watch_pets`, which is never a task
      _meta: { ui: { visibility: ["model"] } },
    },
    async ({ cursor, waitSeconds = 25 }, ctx) => {
      const after = cursor ? Number(cursor) : (await state.petEventsAfter(owner, null)).cursor;
      await watched();
      // A client that follows MCP tasks gets a task: it asks `tasks/get` until an event is there,
      // however long that takes, and the conversation goes on meanwhile.
      if (FollowsTasks.safeParse(ctx.mcpReq.envelope).success)
        // the SDK's type of a tool's answer knows no task yet
        return { resultType: "task", ...petWatchTask(after, Date.now()) } as never;
      const read = await state.petEventsAfter(owner, after, waitSeconds * 1000);
      return asData(await eventsAndPets(context, read));
    },
  );

  server.registerTool(
    "simulate_shop_activity",
    {
      title: "Make things happen in the shop",
      description:
        "Make things happen to the account's pets by themselves, behind the scenes, with no further call: a new pet comes into the shop, then a visitor walks in and adopts a pet, then that pet comes back, and round again, one thing every `everySeconds`. Call it when the person wants something to happen in the shop, or wants to test that a change reaches them with nobody asking: an event, a finished wait, a gallery that is open. It answers at once with the day it began; the things then happen while the conversation goes on, and each is a pet event. `happenings: 0` makes the shop quiet again.",
      inputSchema: {
        happenings: z
          .int()
          .min(0)
          .max(SHOP_DAY_MOST_HAPPENINGS)
          .optional()
          .describe(`How many things happen. ${ASKED_DAY.happenings} without it; 0 stops the day.`),
        everySeconds: z
          .number()
          .min(SHOP_DAY_LEAST_EVERY_MS / 1000)
          .max(SHOP_DAY_MOST_EVERY_MS / 1000)
          .optional()
          .describe(
            `The time between two things, and before the first. ${ASKED_DAY.everySeconds} without it.`,
          ),
      },
      // the model and the gallery's button both call it
      _meta: { ui: { visibility: ["model", "app"] } },
    },
    async ({ happenings = ASKED_DAY.happenings, everySeconds = ASKED_DAY.everySeconds }) => {
      const day = await state.startShopDay(owner, {
        happenings,
        everyMs: everySeconds * 1000,
        auto: false,
      });
      if (!day && happenings > 0)
        return {
          isError: true,
          content: [
            { type: "text" as const, text: "Too many accounts have a day now. Try again later." },
          ],
        };
      return asData({
        owner,
        day: dayOf(day),
        order: ["a pet comes into the shop", "a visitor adopts a pet", "that pet comes back"],
        pets: await listed(),
      });
    },
  );

  server.registerTool(
    "watch_pets",
    {
      title: "Watch the pets",
      description:
        "The pet gallery's own call, held open until something happens to the account's pets, for at most `waitSeconds`. It answers the events, the pets as they are now, and the address of the shop's stream of the same events, which the gallery opens where its host allows a connection. A model calls `wait_for_pet_event` instead.",
      inputSchema: waitInput,
      _meta: { ui: { visibility: ["app"] } },
    },
    async ({ cursor, waitSeconds = 25 }) => {
      const after = cursor ? Number(cursor) : (await state.petEventsAfter(owner, null)).cursor;
      const read = await state.petEventsAfter(owner, after, waitSeconds * 1000);
      return asData({
        ...(await eventsAndPets(context, read)),
        stream: await petStreamUrl(context, context.origin, owner),
      });
    },
  );

  server.server.setRequestHandler("events/list", { params: z.object({}) }, () => ({
    events: PET_EVENTS,
  }));

  server.server.setRequestHandler("events/poll", { params: PollParams }, async (listened) => {
    const read = await state.petEventsAfter(owner, cursorOf(listened.cursor));
    const fresh = notOlderThan(heard(read.events, listened), listened.maxAgeMs);
    const events = fresh.events.slice(0, listened.maxEvents);
    const hasMore = events.length < fresh.events.length;
    return {
      // poll carries the cursor on the answer, not on each event
      events: events.map((event) => ({ ...occurrenceOf(event), cursor: undefined })),
      cursor: String(hasMore ? events.at(-1)!.seq : read.cursor),
      truncated: read.truncated || fresh.skipped,
      hasMore,
      nextPollMs: 2000,
    };
  });

  // Push delivery: the request stays open, and each event is a notification on it. The shop
  // ends the stream after `STREAM_LASTS_MS`, and the client opens the next with its cursor.
  server.server.setRequestHandler(
    "events/stream",
    { params: PollParams },
    async (listened, ctx) => {
      const send = (kind: string, params: Record<string, unknown>) =>
        ctx.mcpReq.notify({
          method: `notifications/events/${kind}`,
          params: { ...params, _meta: { "io.modelcontextprotocol/subscriptionId": ctx.mcpReq.id } },
        });
      const active = (read: PetEventsRead, truncated: boolean) =>
        send("active", {
          cursor: String(read.cursor),
          truncated,
          heartbeatMs: STREAM_HEARTBEAT_MS,
        });
      const ends = Date.now() + STREAM_LASTS_MS;
      let read = await state.petEventsAfter(owner, cursorOf(listened.cursor));
      await watched();
      let fresh = notOlderThan(heard(read.events, listened), listened.maxAgeMs);
      await active(read, read.truncated || fresh.skipped);
      for (;;) {
        for (const event of fresh.events) await send("event", occurrenceOf(event));
        if (ctx.mcpReq.signal.aborted || Date.now() >= ends) return {};
        read = await state.petEventsAfter(owner, read.cursor, STREAM_HEARTBEAT_MS);
        fresh = { events: heard(read.events, listened), skipped: false };
        // events were skipped: the stream says where it goes on from
        if (read.truncated) await active(read, true);
        else if (fresh.events.length === 0)
          await send("heartbeat", { cursor: String(read.cursor) });
      }
    },
  );

  server.server.setRequestHandler("events/subscribe", { params: SubscribeParams }, async (key) => {
    const id = await subscriptionIdOf(owner, key);
    // The callback must answer a signed challenge before it gets any event.
    const challenge = crypto.randomUUID();
    const answer = await postSigned(id, key.delivery, `msg_verification_${challenge}`, {
      type: "verification",
      challenge,
    })
      .then((response) => (response.ok ? response.json() : null))
      .catch(() => null);
    if (z.object({ challenge: z.literal(challenge) }).safeParse(answer).error)
      throw new ProtocolError(-32015, "CallbackEndpointError", { reason: "challenge_failed" });
    const expiresAt = Date.now() + 60 * 60 * 1000;
    // a subscription that is new, and not one that a client keeps alive, begins a day
    const before = (await state.getState()).mcpEventSubscriptions?.[id];
    if (!before || before.expiresAt <= Date.now()) await watched();
    await state.setMcpEventSubscription(id, {
      owner,
      name: key.name,
      arguments: key.arguments,
      url: key.delivery.url,
      secret: key.delivery.secret,
      expiresAt,
    });
    return { id, refreshBefore: new Date(expiresAt).toISOString(), cursor: null, truncated: false };
  });

  server.server.setRequestHandler(
    "events/unsubscribe",
    { params: SubscriptionKey },
    async (key) => {
      await state.setMcpEventSubscription(await subscriptionIdOf(owner, key), null);
      return {};
    },
  );

  return server;
});

/** A subscription's id: the first 8 bytes of the SHA-256 of its owner, callback URL, event and
 *  arguments, so subscribing again names the same subscription and no one else can. */
async function subscriptionIdOf(owner: string, key: z.output<typeof SubscriptionKey>) {
  const digest = await crypto.subtle.digest(
    "SHA-256",
    new TextEncoder().encode(JSON.stringify([owner, key.delivery.url, key.name, key.arguments])),
  );
  return `sub_${[...new Uint8Array(digest, 0, 8)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
}

const PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource";

/**
 * RFC 9728's document for the MCP server, at the well-known path and at the same path with `/mcp`
 * after it: where an MCP client learns which authorization server gives a token for `/mcp`. It
 * is the shop itself (oauth-provider.ts). Null for any other request.
 */
export function mcpProtectedResourceResponse(request: Request): Response | null {
  const url = new URL(request.url);
  if (request.method !== "GET") return null;
  if (url.pathname !== PROTECTED_RESOURCE_PATH && url.pathname !== `${PROTECTED_RESOURCE_PATH}/mcp`)
    return null;
  return Response.json({
    resource: `${url.origin}/mcp`,
    authorization_servers: [url.origin],
    bearer_methods_supported: ["header"],
  });
}

/**
 * The answer to an MCP request with no live token: the 401 names the document above, which is
 * how a standard MCP client (Claude, Codex) starts its sign-in by itself.
 */
export function mcpUnauthorizedResponse(request: Request): Response {
  const { origin } = new URL(request.url);
  return Response.json(
    { error: "invalid_token" },
    {
      status: 401,
      headers: {
        "WWW-Authenticate": `Bearer resource_metadata="${origin}${PROTECTED_RESOURCE_PATH}/mcp"`,
      },
    },
  );
}

/**
 * Serve one MCP HTTP request with the authenticated owner + catalogue as the
 * tool context. The worker has already verified the bearer token; this only
 * threads the resolved principal through as pass-through `authInfo` (the raw
 * token is never re-exposed to tool bodies).
 */
export async function handleMcpRequest(
  request: Request,
  context: McpToolContext,
): Promise<Response> {
  const task = await petWatchTaskResponse(request, context);
  if (task) return task;
  return mcpHandler.fetch(request, {
    authInfo: {
      token: "sealed",
      clientId: "petshop",
      scopes: [],
      extra: context as unknown as Record<string, unknown>,
    },
  });
}