iterate.com / cloud

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

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

/**
 * The pet shop's MCP App (mcp.ts, mcp-app.ts), as an MCP Apps host reads it: `show_pets` names its
 * UI resource, the resource is the gallery's HTML under the extension's MIME type, and `adopt_pet`
 * is a tool for the app alone.
 */
import { expect, test } from "vitest";
import {
  handleMcpRequest,
  mcpProtectedResourceResponse,
  mcpUnauthorizedResponse,
  type McpToolContext,
} from "./mcp.ts";
import { memoryPetshop } from "./memory-state.ts";
import { seedPets } from "./pets.ts";

test("show_pets names the gallery, and the model and the gallery may both call adopt_pet", async () => {
  const { result } = await call(contextOf(), "tools/list");
  const tools = Object.fromEntries(result.tools.map((tool: { name: string }) => [tool.name, tool]));
  expect(tools.show_pets).toMatchObject({
    _meta: {
      ui: { resourceUri: "ui://petshop/pets.html?v=6" },
      "ui/resourceUri": "ui://petshop/pets.html?v=6",
    },
  });
  expect(tools.adopt_pet).toMatchObject({ _meta: { ui: { visibility: ["model", "app"] } } });
  // the model's wait may be an MCP task; the gallery's is its own tool, which never is
  expect(tools.wait_for_pet_event).toMatchObject({ _meta: { ui: { visibility: ["model"] } } });
  expect(tools.watch_pets).toMatchObject({ _meta: { ui: { visibility: ["app"] } } });
  // the tools that were there before say nothing of a UI
  expect(tools.list_pets._meta).toBeUndefined();
});

test("the gallery is one resource: HTML under the MCP Apps MIME type, which loads nothing", async () => {
  // the one origin the frame may connect to is the shop's own, for its stream of pet events
  const ui = { prefersBorder: true, csp: { connectDomains: ["https://petshop.example"] } };
  const listed = await call(contextOf(), "resources/list");
  expect(listed.result.resources).toMatchObject([
    { uri: "ui://petshop/pets.html?v=6", mimeType: "text/html;profile=mcp-app", _meta: { ui } },
    { uri: "ui://petshop/pets-panel.html?v=1", mimeType: "text/html;profile=mcp-app" },
  ]);
  const read = await call(contextOf(), "resources/read", { uri: "ui://petshop/pets.html?v=6" });
  const [content] = read.result.contents;
  expect(content).toMatchObject({
    uri: "ui://petshop/pets.html?v=6",
    mimeType: "text/html;profile=mcp-app",
    _meta: { ui },
  });
  expect(content.text).toContain('request("ui/initialize"');
  // a host's default policy allows no network: the page must not need any to show itself
  expect(content.text).not.toMatch(/<script[^>]+src=|<link[^>]+href=|@import/);
});

test("open_pet_shop names the same gallery as a resource that asks to open large", async () => {
  const context = contextOf();
  const { result } = await call(context, "tools/list");
  expect(
    result.tools.find((tool: { name: string }) => tool.name === "open_pet_shop"),
  ).toMatchObject({ _meta: { ui: { resourceUri: "ui://petshop/pets-panel.html?v=1" } } });
  const small = await call(context, "resources/read", { uri: "ui://petshop/pets.html?v=6" });
  const large = await call(context, "resources/read", { uri: "ui://petshop/pets-panel.html?v=1" });
  // Claude reads the preference on the content item, and opens the view in its side panel
  expect(large.result.contents).toMatchObject([
    {
      mimeType: "text/html;profile=mcp-app",
      text: small.result.contents[0].text,
      _meta: {
        ui: {
          preferredDisplayMode: "fullscreen",
          csp: { connectDomains: ["https://petshop.example"] },
        },
      },
    },
  ]);
  // the gallery in the conversation asks for nothing, and the page itself offers both sizes
  expect(small.result.contents[0]._meta.ui).not.toHaveProperty("preferredDisplayMode");
  expect(small.result.contents[0].text).toContain(
    'availableDisplayModes: ["inline", "fullscreen"]',
  );
  const opened = await call(context, "tools/call", { name: "open_pet_shop", arguments: {} });
  expect(opened.result).toMatchObject({ structuredContent: { pets: seedPets() } });
});

test("show_pets answers the pets as text and as data, and adopt_pet marks one", async () => {
  const context = contextOf();
  const shown = await call(context, "tools/call", { name: "show_pets", arguments: {} });
  expect(shown.result).toMatchObject({
    structuredContent: { owner: "ada@example.com", pets: seedPets() },
  });
  expect(JSON.parse(shown.result.content[0].text)).toEqual(shown.result.structuredContent);

  const beagles = await call(context, "tools/call", {
    name: "show_pets",
    arguments: { species: "beagle" },
  });
  expect(beagles.result.structuredContent).toMatchObject({ pets: [seedPets()[0]] });
  expect(beagles.result.structuredContent.pets).toHaveLength(1);

  // by name, as a model does it for "adopt goldie"; another isolate then reads the same state
  const adopted = await call(context, "tools/call", {
    name: "adopt_pet",
    arguments: { name: "goldie" },
  });
  expect(adopted.result.structuredContent).toMatchObject({
    pet: { ...seedPets()[1], adopted: true },
    pets: [seedPets()[0], { ...seedPets()[1], adopted: true }],
  });
  const elsewhere = { ...context, pets: seedPets() };
  const read = await call(elsewhere, "tools/call", { name: "list_pets", arguments: {} });
  expect(JSON.parse(read.result.content[0].text)).toMatchObject({
    pets: [seedPets()[0], { ...seedPets()[1], adopted: true }],
  });
  // another account's pets are not adopted
  const other = await call({ ...elsewhere, owner: "bo@example.com" }, "tools/call", {
    name: "show_pets",
    arguments: {},
  });
  expect(other.result).toMatchObject({ structuredContent: { pets: seedPets() } });

  const byId = await call(context, "tools/call", { name: "adopt_pet", arguments: { id: "pet-1" } });
  expect(byId.result.structuredContent).toMatchObject({ pet: { id: "pet-1", adopted: true } });

  for (const wrong of [{ id: "pet-9" }, { name: "Rex" }, {}]) {
    const missing = await call(context, "tools/call", { name: "adopt_pet", arguments: wrong });
    expect(missing.result).toMatchObject({ isError: true });
  }
});

test("a client with no token learns where to sign in: the 401 names RFC 9728's document", async () => {
  const refused = mcpUnauthorizedResponse(
    new Request("https://petshop.example/mcp", { method: "POST" }),
  );
  expect(refused).toMatchObject({ status: 401 });
  expect(refused.headers.get("www-authenticate")).toBe(
    'Bearer resource_metadata="https://petshop.example/.well-known/oauth-protected-resource/mcp"',
  );
  for (const path of [
    "/.well-known/oauth-protected-resource",
    "/.well-known/oauth-protected-resource/mcp",
  ]) {
    const described = mcpProtectedResourceResponse(new Request(`https://petshop.example${path}`));
    expect(await described!.json()).toEqual({
      resource: "https://petshop.example/mcp",
      authorization_servers: ["https://petshop.example"],
      bearer_methods_supported: ["header"],
    });
  }
  expect(mcpProtectedResourceResponse(new Request("https://petshop.example/api/pets"))).toBeNull();
});

/** One JSON-RPC call, as a client of protocol 2025-06-18 posts it. The handler answers JSON or
 *  one server-sent event: either way, the message. */
async function call(context: McpToolContext, method: string, params: Record<string, unknown> = {}) {
  const response = await handleMcpRequest(
    new Request("https://petshop.example/mcp", {
      method: "POST",
      headers: {
        "content-type": "application/json",
        accept: "application/json, text/event-stream",
        "mcp-protocol-version": "2025-06-18",
      },
      body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
    }),
    context,
  );
  const text = await response.text();
  const json = text.startsWith("{")
    ? text
    : text
        .split("\n")
        .find((line) => line.startsWith("data: "))!
        .slice(6);
  return JSON.parse(json) as { result?: any; error?: { message: string } };
}

// the shop's state over a map in memory, as the other tests of the shop have it
function contextOf(): McpToolContext {
  return {
    ...memoryPetshop(),
    owner: "ada@example.com",
    pets: seedPets(),
    origin: "https://petshop.example",
  };
}