iterate.com / kernel

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

kernel / core / mind-worker / src / library / mcp-in-workerd.test.tsmain at 949894f

// mcp-in-workerd.test.ts — what the connection of `itx.connectToMcp` leaves to the kernel, in
// workerd (./fixtures/mcp-in-workerd.ts): a schedule on the context whose event is a script run,
// and a script that reaches the connection again as the context's own code. The connection's own
// answers are ./mcp-events.test.ts and ./mcp-tasks.test.ts, in Node.
import { fileURLToPath } from "node:url";
import { build } from "esbuild";
import { Miniflare } from "miniflare";
import { COMPATIBILITY_DATE } from "iterate/compatibility-date";
import { expect, test } from "vitest";
import { z } from "zod";

const SHOP = "https://petshop.test/mcp";

test(
  "a subscription's renewal is a schedule of the context, and the kernel runs its script, which subscribes again",
  { timeout: 60_000 },
  async () => {
    await using mind = await mindInWorkerd();
    expect(
      await mind.run(
        `async (itx) => (await itx.connectToMcp("${SHOP}")).subscribe("pet.adopted", { species: "beagle" })`,
      ),
    ).toMatchObject({ id: "sub_1", cursor: "1" });
    const renewal = async () =>
      Renewals.parse(await mind.run("async (itx) => itx.schedules.list()")).find(({ key }) =>
        key.includes("mcp-subscription"),
      );
    const first = await renewal();
    // two thirds of the hour that the server granted, less the moment the answer took
    expect(first).toMatchObject({
      when: { afterMs: expect.closeTo(40 * 60_000, -3) },
      events: [{ type: "events.iterate.com/itx/run-requested" }],
    });
    // The renewal's own events, set a second from now in place of forty minutes: the kernel fires
    // them as it will fire the renewal.
    await mind.run(
      `async (itx) => itx.schedules.set({ key: "the-renewal-now", when: { afterMs: 1000 }, events: ${JSON.stringify(first?.events)} })`,
    );
    const subscribes = async () =>
      Asked.parse(
        await mind.run(`async (itx) => (await itx.connectToMcp("${SHOP}")).callTool("asked")`),
      ).asked;
    await expect.poll(subscribes, { timeout: 30_000, interval: 250 }).toHaveLength(2);
    // the script subscribed to the same event, from the cursor of the first grant
    expect(await subscribes()).toMatchObject([
      { params: { name: "pet.adopted", arguments: { species: "beagle" } } },
      { params: { name: "pet.adopted", arguments: { species: "beagle" }, cursor: "1" } },
    ]);
    // and the subscription that the script made set the context's renewal again
    await expect
      .poll(async () => (await renewal())?.scheduledAtOffset, { timeout: 10_000, interval: 250 })
      .toBeGreaterThan(first?.scheduledAtOffset || Infinity);
  },
);

test(
  "a tool call that the server runs as a task: the context's schedule asks five seconds on, and the end lands on the context",
  { timeout: 60_000 },
  async () => {
    await using mind = await mindInWorkerd();
    expect(
      await mind.run(`async (itx) => (await itx.connectToMcp("${SHOP}")).callTool("make_report")`),
    ).toMatchObject({ content: [], task: { taskId: "task-1", status: "working" } });
    // The script that made the call has ended, and nothing has asked the server yet. This script
    // only reads the context's log, to show what lands there.
    expect(
      await mind.run(
        `async (itx) => itx.waitForEvent({ type: "events.iterate.com/mcp/task-settled", afterOffset: 0, timeoutMs: 30000 })`,
      ),
    ).toMatchObject({
      type: "events.iterate.com/mcp/task-settled",
      payload: {
        server: SHOP,
        tool: "make_report",
        taskId: "task-1",
        status: "completed",
        result: { content: [{ type: "text", text: "3 pets" }] },
      },
    });
    // one ask, and no schedule left to ask again
    expect(
      Asked.parse(
        await mind.run(`async (itx) => (await itx.connectToMcp("${SHOP}")).callTool("asked")`),
      ).asked,
    ).toMatchObject([{ method: "tasks/get", params: { taskId: "task-1" } }]);
    expect(Renewals.parse(await mind.run("async (itx) => itx.schedules.list()"))).toEqual([]);
  },
);

const Renewals = z.array(
  z.looseObject({
    key: z.string(),
    scheduledAtOffset: z.number(),
    events: z.array(z.looseObject({ type: z.string() })),
  }),
);
const Asked = z.object({ asked: z.array(z.looseObject({ method: z.string() })) });

/** One module of the file at `entry`, for workerd, under the conditions a deployed Worker is
 *  bundled with. */
async function bundled(entry: URL): Promise<string> {
  const result = await build({
    entryPoints: [fileURLToPath(entry.href)],
    bundle: true,
    write: false,
    format: "esm",
    platform: "neutral",
    mainFields: ["module", "main"],
    conditions: ["workerd", "worker", "browser"],
    target: "es2022",
    external: ["cloudflare:*", "node:*"],
  });
  return result.outputFiles[0]!.text;
}

/** The fixture's Worker in workerd, and `run`: a script on its root context, as a member's. */
async function mindInWorkerd() {
  const [fixture, loadedWorker] = await Promise.all([
    bundled(new URL("./fixtures/mcp-in-workerd.ts", import.meta.url)),
    bundled(new URL("../../../lib/src/sdk/loaded-worker.ts", import.meta.url)),
  ]);
  const runtime = new Miniflare({
    workers: [
      {
        config: {
          name: "mind",
          compatibilityDate: COMPATIBILITY_DATE,
          compatibilityFlags: ["nodejs_compat", "allow_irrevocable_stub_storage"],
          manifest: {
            mainModule: "worker.js",
            modules: { "worker.js": { type: "esm" as const, contents: fixture } },
          },
          env: {
            CONTEXTS: {
              type: "durable-object",
              worker: "mind",
              exportName: "IterateContextDurableObject",
            },
            CF_VERSION_METADATA: { type: "version-metadata" },
            LOADER: { type: "worker-loader" },
            LOADED_WORKER: { type: "text", value: loadedWorker },
            COMPATIBILITY_DATE: { type: "text", value: COMPATIBILITY_DATE },
          },
          exports: {
            IterateContextDurableObject: { type: "durable-object", storage: "sqlite" },
            ItxEntrypoint: { type: "worker" },
          },
        },
      },
    ],
  });
  await runtime.ready;
  return {
    run: async (script: string) => {
      const answer = await runtime.dispatchFetch("http://mind.test/run", {
        method: "POST",
        body: script,
      });
      const { result, error } = z
        .object({ result: z.unknown(), error: z.string().optional() })
        .parse(await answer.json());
      if (error) throw new Error(error);
      return result;
    },
    [Symbol.asyncDispose]: () => runtime.dispose(),
  };
}