cloud / internal-packages / dummy-petshop / src / pet-events.tsmain at aacbc74
// pet-events.ts: WHAT HAPPENS TO AN ACCOUNT'S PETS, and how it leaves the shop with nobody asking.
//
// Three events: `pet.created`, `pet.adopted` and `pet.returned`. `emitPetEvent` keeps one in the
// shop's state (state.ts `recordPetEvent`), which is what a held read answers at that moment
// (state.ts `petEventsAfter`: MCP Events' poll and push delivery, and the gallery's
// `wait_for_pet_event`), and POSTs it to the account's webhook subscriptions.
//
// Two things change an account's pets: the account's own MCP client (mcp.ts `adopt_pet`,
// `create_pet`), and the shop acting by itself: a walk-in visitor at one press (walk-in.ts), or a
// day of happenings on a clock (shop-day.ts). The second is what a client has no call for: the
// test of whether a server can reach it.
import { Webhook } from "standardwebhooks";
import type { Pet } from "./pets.ts";
import type {
McpEventSubscription,
PetEvent,
PetEventName,
PetshopState,
ShopDeps,
} from "./state.ts";
const speciesFilter = {
type: "object",
properties: { species: { type: "string" } },
additionalProperties: false,
};
const petPayload = (more: Record<string, unknown> = {}) => ({
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
species: { type: "string" },
...more,
},
required: ["id", "name", "species"],
});
// every delivery mode of the extension: a client takes the one it has
const delivery = ["webhook", "poll", "push"];
/** The events as `events/list` describes them. `species` limits each to one species. */
export const PET_EVENTS: {
name: PetEventName;
description: string;
delivery: string[];
inputSchema: object;
payloadSchema: object;
}[] = [
{
name: "pet.created",
description:
"A pet was added to the authenticated account: the account's client added it, or it came into the shop by itself. `species` limits it to one species.",
delivery,
inputSchema: speciesFilter,
payloadSchema: petPayload(),
},
{
name: "pet.adopted",
description:
'A pet of the authenticated account was adopted: by the account (`by: "account"`), or by a visitor who walked into the shop (`by: "walk-in visitor"`). `species` limits it to one species.',
delivery,
inputSchema: speciesFilter,
payloadSchema: petPayload({ by: { type: "string", enum: ["account", "walk-in visitor"] } }),
},
{
name: "pet.returned",
description:
"An adopted pet of the authenticated account came back to the shop and is up for adoption again. `species` limits it to one species.",
delivery,
inputSchema: speciesFilter,
payloadSchema: petPayload(),
},
];
/** The events' names, as a schema's list of what a subscription may name. */
export const PET_EVENT_NAMES: [PetEventName, ...PetEventName[]] = [
"pet.created",
"pet.adopted",
"pet.returned",
];
/** An event as a client receives it, in every delivery mode: MCP Events' `EventOccurrence`. The
* cursor is the event's place in the shop's list, from which a poll or a stream goes on. */
export const occurrenceOf = ({ eventId, name, timestamp, data, seq }: PetEvent) => ({
eventId,
name,
timestamp,
data,
cursor: String(seq),
});
/** The account's pets: the shop's own (`pets`) and those that came in by themselves for the
* account (shop-day.ts), each marked `adopted` once the account's own client or a visitor adopted
* it. */
export async function petsOf(state: ShopDeps["state"], owner: string, pets: Pet[]): Promise<Pet[]> {
const { adoptedPets, arrivedPets } = await state.getState();
const adopted = new Set(adoptedPets?.[owner]);
return [...pets, ...(arrivedPets?.[owner] || [])].map((pet) =>
adopted.has(pet.id) ? { ...pet, adopted: true } : pet,
);
}
/**
* One event of `owner`'s pets: kept, so every held read answers now, and POSTed to each of the
* owner's live webhook subscriptions to that event and species. Answers the event and what each
* callback answered; a callback that could not be reached answers status 0.
*/
export async function emitPetEvent(
state: ShopDeps["state"],
owner: string,
name: PetEventName,
data: PetEvent["data"],
) {
const event = await state.recordPetEvent(owner, name, data);
return { event, deliveries: await deliverPetEvent(state, event) };
}
/** The live webhook subscriptions that hear `event`: its owner's, to that event and species. */
export const subscribersOf = (
{ mcpEventSubscriptions = {} }: Pick<PetshopState, "mcpEventSubscriptions">,
event: PetEvent,
) =>
Object.entries(mcpEventSubscriptions).filter(
([, subscription]) =>
subscription.owner === event.owner &&
(subscription.name || "pet.created") === event.name &&
subscription.expiresAt > Date.now() &&
(subscription.arguments.species || event.data.species) === event.data.species,
);
/** POST one kept event to one subscription. Answers what the callback answered: status 0 could
* not be reached. */
const postPetEvent = async (
event: PetEvent,
[id, subscription]: [string, McpEventSubscription],
) => ({
id,
url: subscription.url,
status: await postSigned(id, subscription, event.eventId, occurrenceOf(event)).then(
(response) => response.status,
() => 0,
),
});
/** One POST that is due: a kept event, and a subscription that hears it. */
export type DuePost = { event: PetEvent; subscriber: [string, McpEventSubscription] };
/**
* POST each kept event to its subscription, all at once, and keep what each callback answered
* (state.ts `webhookAnswers`), which the walk-in page's control shows: the one place where a
* person sees whether a client's receiver took an event. Answers the same.
*/
export async function postPetEvents(state: ShopDeps["state"], due: DuePost[]) {
const deliveries = await Promise.all(
due.map(({ event, subscriber }) => postPetEvent(event, subscriber)),
);
const at = new Date().toISOString();
await state.recordWebhookAnswers(
deliveries.map(({ id, status }, index) => {
const { owner, name } = due[index]!.event;
return { at, owner, name, id, status };
}),
);
return deliveries;
}
/** POST one kept event to every live webhook subscription that hears it, all at once. */
const deliverPetEvent = async (state: ShopDeps["state"], event: PetEvent) =>
postPetEvents(
state,
subscribersOf(await state.getState(), event).map((subscriber) => ({ event, subscriber })),
);
/** A pet of `owner` is adopted, and `pet.adopted` says by whom. Null when it already was. */
export async function adoptPet(
state: ShopDeps["state"],
owner: string,
pet: Pet,
by: NonNullable<PetEvent["data"]["by"]>,
) {
if ((await state.getState()).adoptedPets?.[owner]?.includes(pet.id)) return null;
await state.adoptPet(owner, pet.id, by);
const { id, name, species } = pet;
return await emitPetEvent(state, owner, "pet.adopted", { id, name, species, by });
}
/** POST one body to a subscription's callback, signed per Standard Webhooks with its secret. A
* redirect is an answer, never followed. */
export function postSigned(
id: string,
{ url, secret }: Pick<McpEventSubscription, "url" | "secret">,
webhookId: string,
body: unknown,
) {
const payload = JSON.stringify(body);
const now = new Date();
return fetch(url, {
method: "POST",
redirect: "manual",
signal: AbortSignal.timeout(10_000),
headers: {
"content-type": "application/json",
"webhook-id": webhookId,
"webhook-timestamp": String(Math.floor(now.getTime() / 1000)),
"webhook-signature": new Webhook(secret).sign(webhookId, now, payload),
"x-mcp-subscription-id": id,
},
body: payload,
});
}