iterate.com / cloud

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

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

// mcp-app.ts: THE PET SHOP'S MCP APP: one UI resource, a gallery of the account's pets, which a
// host that supports MCP Apps (the extension io.modelcontextprotocol/ui) draws in a sandboxed
// frame when a model calls `show_pets` (mcp.ts). A person adopts a pet there: the gallery calls
// `adopt_pet`, which the model calls too when a person says "adopt Goldie".
//
// MCP Apps gives a host no message that pushes new data into a frame that is open. So the gallery
// fetches the news itself, the best way its host allows, and says which in its heading:
//
//   1. its own connection to the shop (pet-stream.ts), on which the shop pushes each pet event;
//      a host must honour the resource's `csp.connectDomains` for it
//   2. a `watch_pets` call that the shop holds open until something happens; a host must let the
//      frame call a tool with no person asked
//   3. `list_pets` every two seconds
//
// What a press here did not cause (the model's adoption, a walk-in visitor's: walk-in.ts) it says
// in its status line, and gives to the model as context (`ui/update-model-context`). With the
// person's tick it also sends it as a message (`ui/message`), which starts a turn.
//
// The page speaks the bridge by hand (JSON-RPC 2.0 over `window.parent.postMessage`, protocol
// 2026-01-26) and loads nothing, so it runs under a host's default policy, which allows inline
// script and style, and the network only to the origins that the resource names.

/** The gallery's address. A tool names it in `_meta.ui.resourceUri`. */
// The address names the page's version: a host may keep a resource by its address.
export const PETS_APP_URI = "ui://petshop/pets.html?v=6";

/** The same gallery under a second address, for the tool that opens it large: a host reads how a
 *  view wants to open from its resource, so one resource cannot open both ways (mcp.ts). */
export const PETS_PANEL_URI = "ui://petshop/pets-panel.html?v=1";

/** The MIME type of an MCP App's HTML. */
export const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";

export const PETS_APP_HTML = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pet gallery</title>
<style>
  :root { color-scheme: light dark; }
  body { margin: 0; padding: 20px 16px 12px; font: 14px/1.4 var(--font-sans, system-ui, sans-serif);
    color: var(--color-text-primary, CanvasText); background: var(--color-background-primary, Canvas); }
  h1 { font-size: 15px; margin: 0 0 12px; }
  .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 8px; }
  .pet { border: 1px solid var(--color-border-primary, #8884); border-radius: var(--border-radius-md, 8px);
    padding: 10px; display: flex; flex-direction: column; gap: 4px; }
  .pet b { font-size: 15px; } .face { font-size: 32px; } .muted { opacity: .65; font-size: 12px; }
  .adopted { opacity: .55; }
  button { font: inherit; cursor: pointer; border-radius: var(--border-radius-md, 8px); padding: 4px 8px;
    border: 1px solid var(--color-border-primary, #8886); background: var(--color-background-secondary, ButtonFace);
    color: inherit; }
  button.primary { background: var(--color-text-primary, #111); color: var(--color-background-primary, #fff); }
  .bar { display: flex; gap: 6px; margin-top: 10px; flex-wrap: wrap; }
  .bar label { display: flex; align-items: center; gap: 4px; font-size: 12px; }
  #status { margin-top: 8px; min-height: 1.4em; }
  /* a side panel or full screen: larger cards */
  @media (min-width: 560px) {
    .grid { grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 12px; }
    .pet { padding: 16px; gap: 6px; } .pet b { font-size: 17px; } .face { font-size: 52px; }
    button { padding: 7px 10px; }
  }
</style>
</head>
<body>
<h1>🐾 The pet shop <span class="muted" id="count"></span> <span class="muted" id="live"></span></h1>
<div class="grid" id="grid"><span class="muted">Waiting for the host…</span></div>
<div class="bar">
  <button id="refresh">Refresh</button>
  <button id="tell">Tell the agent what is left</button>
  <button id="site">Open the shop's floor</button>
  <button id="busy">Make the shop busy</button>
  <button id="big">Full size</button>
  <label><input type="checkbox" id="telling"> Tell the agent when the shop changes</label>
</div>
<div id="status" class="muted"></div>
<script>
(() => {
  // MCP Apps, by hand: JSON-RPC 2.0 over postMessage to the frame's parent.
  let nextId = 1;
  const waiting = new Map();
  const post = (message) => parent.postMessage({ jsonrpc: "2.0", ...message }, "*");
  const request = (method, params) => new Promise((resolve, reject) => {
    const id = nextId++;
    waiting.set(id, { resolve, reject });
    post({ id, method, params });
  });
  const notify = (method, params) => post({ method, params });
  const status = (text) => { document.getElementById("status").textContent = text; };

  let pets = [];
  let species;
  let owner = "Demo User";
  let shop = "https://dummy-petshop.iterate.workers.dev";
  // the pets that a press here adopted: the shop's word of those is no news
  const pressed = new Set();
  const FACES = { beagle: "🐶", dog: "🐶", goldfish: "🐠", fish: "🐠", cat: "🐱", tortoise: "🐢", parakeet: "🦜", rabbit: "🐰", hamster: "🐹" };
  const draw = () => {
    document.getElementById("count").textContent = pets.length ? "· " + pets.filter((p) => !p.adopted).length + " of " + pets.length + " need a home" : "";
    const grid = document.getElementById("grid");
    grid.textContent = "";
    for (const pet of pets) {
      const card = document.createElement("div");
      card.className = "pet" + (pet.adopted ? " adopted" : "");
      const face = document.createElement("div"); face.className = "face"; face.textContent = pet.emoji || FACES[pet.species] || "🐾";
      const name = document.createElement("b"); name.textContent = pet.name;
      const about = document.createElement("div"); about.className = "muted"; about.textContent = pet.species + (pet.age ? ", " + pet.age + " y" : "");
      const button = document.createElement("button");
      button.className = "primary"; button.disabled = Boolean(pet.adopted);
      button.textContent = pet.adopted ? "Adopted" : "Adopt " + pet.name;
      button.onclick = async () => {
        button.disabled = true; status("Adopting " + pet.name + "…");
        pressed.add(pet.id);
        try {
          const answer = await request("tools/call", { name: "adopt_pet", arguments: { id: pet.id } });
          if (answer.isError) throw new Error(answer.content?.[0]?.text || "refused");
          take(answer); status(pet.name + " is adopted.");
          request("ui/update-model-context", { content: [{ type: "text", text: "The person adopted " + pet.name + " (" + pet.id + ") in the pet gallery." }] }).catch(() => {});
        } catch (error) { pressed.delete(pet.id); button.disabled = false; status("The shop refused: " + error.message); }
      };
      card.append(face, name, about, button);
      grid.append(card);
    }
  };
  // some hosts hand over no structuredContent: the text holds the same JSON
  const dataOf = (toolResult) => {
    if (toolResult?.structuredContent) return toolResult.structuredContent;
    try { return JSON.parse(toolResult?.content?.[0]?.text || "null"); } catch { return null; }
  };
  const take = (toolResult) => takePets(dataOf(toolResult));
  const takePets = (data) => {
    if (data?.owner) owner = data.owner;
    let next = data?.pets;
    if (!Array.isArray(next)) return;
    if (species) next = next.filter((pet) => pet.species === species);
    // an adoption that did not come from a press here: the person told the model
    const before = new Map(pets.map((pet) => [pet.id, pet.adopted]));
    const newly = next.filter((pet) => pet.adopted && before.has(pet.id) && !before.get(pet.id));
    const same = JSON.stringify(next) === JSON.stringify(pets);
    pets = next;
    if (!same) draw();
    if (newly.length) status(newly.map((pet) => pet.name).join(" and ") + (newly.length > 1 ? " are" : " is") + " adopted.");
  };

  // What the shop says happened, by any of the three ways below. A press here is no news.
  let cursor;
  const said = (event) => event.data.name + (event.name === "pet.adopted" ? " was adopted by " + (event.data.by === "walk-in visitor" ? "a visitor who walked into the shop" : "the agent") : event.name === "pet.returned" ? " is back in the shop" : " arrived in the shop");
  const hear = (data, how) => {
    if (data?.cursor) cursor = data.cursor;
    takePets(data);
    const news = (data?.events || []).filter((event) => !(event.name === "pet.adopted" && event.data.by === "account" && pressed.delete(event.data.id)));
    if (!news.length) return;
    const text = news.map(said).join(". ") + ".";
    status("The shop says: " + text + " (" + how + ")");
    const left = pets.filter((p) => !p.adopted).map((p) => p.name).join(", ") || "none";
    // the model reads this with the person's next message
    request("ui/update-model-context", { content: [{ type: "text", text: "The pet shop changed by itself, with no call from this conversation. " + text + " Up for adoption now: " + left + "." }] }).catch(() => {});
    // and at once when the person ticked the box: a message, which starts a turn
    if (document.getElementById("telling").checked) request("ui/message", { role: "user", content: [{ type: "text", text: "The pet shop says: " + text + " Tell me what changed, and show the shop again." }] }).then(() => {}, (error) => status("The host took no message: " + error.message));
  };

  const live = (text) => { document.getElementById("live").textContent = text; };
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
  const call = async (name, args) => {
    const answer = await request("tools/call", { name, arguments: args });
    if (answer.isError) throw new Error(answer.content?.[0]?.text || "refused");
    return answer;
  };
  // 1. The gallery's own connection. The promise ends when the stream is of no use: a host that
  // does not allow the connection never opens it, and the shop closes one whose ticket is old.
  const stream = (address) => new Promise((resolve) => {
    let opened = false;
    let source;
    try { source = new EventSource(address + "&cursor=" + cursor); } catch { return resolve(); }
    source.onopen = () => { opened = true; live("· live: the shop pushes on the gallery's own stream"); };
    source.onmessage = (message) => hear(JSON.parse(message.data), "pushed on the gallery's own stream");
    source.onerror = () => { if (!opened || source.readyState === 2) { source.close(); resolve(); } };
  });
  const watch = async () => {
    let held = true;
    try {
      const first = dataOf(await call("watch_pets", { waitSeconds: 0 }));
      hear(first, "");
      if (first.stream) { shop = new URL(first.stream).origin; await stream(first.stream); }
    } catch { held = false; }
    for (;;) {
      if (document.hidden) { await sleep(1000); continue; }
      try {
        if (held) {
          // 2. a call that the shop holds open
          live("· live: the shop answers a call it holds open");
          hear(dataOf(await call("watch_pets", { cursor, waitSeconds: 25 })), "answered on a call the shop held open");
        } else {
          // 3. asking
          live("· asking every 2 s");
          take(await call("list_pets", {}));
          await sleep(2000);
        }
      } catch { held = false; await sleep(2000); }
    }
  };

  addEventListener("message", (event) => {
    if (event.source !== parent) return;
    const message = event.data;
    if (!message || message.jsonrpc !== "2.0") return;
    if (message.id !== undefined && !message.method) {
      const held = waiting.get(message.id); waiting.delete(message.id);
      if (held) message.error ? held.reject(new Error(message.error.message)) : held.resolve(message.result);
      return;
    }
    if (message.method === "ui/notifications/tool-input") species = message.params?.arguments?.species;
    if (message.method === "ui/notifications/tool-result") take(message.params);
    if (message.method === "ui/notifications/host-context-changed") theme(message.params);
    if (message.method === "ui/resource-teardown" && message.id !== undefined) post({ id: message.id, result: {} });
    if (message.method === "ping" && message.id !== undefined) post({ id: message.id, result: {} });
  });

  const theme = (context) => {
    const variables = context?.styles?.variables || {};
    for (const [name, value] of Object.entries(variables)) document.documentElement.style.setProperty(name, value);
    if (context?.theme) document.documentElement.style.colorScheme = context.theme;
  };

  document.getElementById("refresh").onclick = async () => { take(await request("tools/call", { name: "list_pets", arguments: {} })); status("Refreshed."); };
  document.getElementById("tell").onclick = () => request("ui/message", { role: "user", content: [{ type: "text", text: "In the pet shop these still need a home: " + pets.filter((p) => !p.adopted).map((p) => p.name).join(", ") + "." }] }).then(() => status("Sent to the chat."), (error) => status("The host said no: " + error.message));
  document.getElementById("site").onclick = () => request("ui/open-link", { url: shop + "/walk-in?account=" + encodeURIComponent(owner) }).catch((error) => status("The host said no: " + error.message));
  document.getElementById("busy").onclick = async () => {
    const answer = await request("tools/call", { name: "simulate_shop_activity", arguments: {} }).catch((error) => ({ isError: true, content: [{ text: error.message }] }));
    const day = dataOf(answer)?.day;
    status(answer.isError || !day ? "The shop refused: " + (answer.content?.[0]?.text || "no day") : day.happeningsLeft + " things will happen by themselves, one every " + day.everySeconds + " seconds.");
  };
  document.getElementById("big").onclick = () => request("ui/request-display-mode", { mode: "fullscreen" }).then((answer) => status("The host answered: " + answer.mode), (error) => status("The host said no: " + error.message));

  new ResizeObserver(() => notify("ui/notifications/size-changed", { width: document.documentElement.scrollWidth, height: document.documentElement.scrollHeight })).observe(document.documentElement);

  request("ui/initialize", { protocolVersion: "2026-01-26", appInfo: { name: "petshop-gallery", version: "3" }, appCapabilities: { availableDisplayModes: ["inline", "fullscreen"] } })
    .then((answer) => { theme(answer.hostContext); notify("ui/notifications/initialized", {}); status(""); watch(); })
    .catch((error) => status("No host answered: " + error.message));
})();
</script>
</body>
</html>`;