iterate.com / kernel

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

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

// A tool call that another MCP server runs as a task (MCP tasks, SEP-2663), as the connection of
// `itx.connectToMcp` handles it (./mcp.ts `callTool`, `getTask`, `cancelTask`, `followTask`),
// against a fake server and a context that records its schedules and its events. That the
// schedule's script runs on a real context is ./mcp-in-workerd.test.ts.
import { runInThisContext } from "node:vm";
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
import { createMcpHandler, McpServer } from "@modelcontextprotocol/server";
import { expect, onTestFinished, test, vi } from "vitest";
import { z } from "zod";
import type { LibraryItx } from "core-itx";
import { connectToMcp, followUpScript } from "./mcp.ts";

const SHOP = "https://petshop.test/mcp";
const NOW = Date.parse("2026-11-26T12:00:00Z");
const DAY_MS = 24 * 60 * 60_000;
const WORKING = {
  taskId: "task-1",
  status: "working" as const,
  statusMessage: "Counting the pets",
  createdAt: "2026-11-26T12:00:00Z",
  lastUpdatedAt: "2026-11-26T12:00:00Z",
  ttlMs: null,
  pollIntervalMs: 2000,
};
const REPORT = { content: [{ type: "text", text: "3 pets" }], structuredContent: { pets: 3 } };

// THE PIN of `carryTaskAnswers` (./mcp.ts): once the SDK hands a task answer to its caller, this
// fails, and the carrier can go.
test("the SDK's own client refuses a tool call that a server answers with a task", async () => {
  const client = new Client(
    { name: "bare", version: "1" },
    {
      versionNegotiation: { mode: "auto" },
      capabilities: { extensions: { "io.modelcontextprotocol/tasks": {} } },
    },
  );
  await client.connect(
    new StreamableHTTPClientTransport(new URL(SHOP), {
      fetch: (input, init) => contextOfFake().itx.fetch(new Request(input, init)),
    }),
  );
  await expect(client.callTool({ name: "make_report", arguments: {} })).rejects.toThrow(
    "Unsupported result type 'task' for tools/call",
  );
  await client.close();
});

test("a tool call that the server runs as a task answers the task at once, and sets the first ask", async () => {
  vi.useFakeTimers({ toFake: ["Date"], now: NOW });
  onTestFinished(() => void vi.useRealTimers());
  const headers = { authorization: 'Bearer getSecret("/secrets/petshop")' };
  const context = contextOfFake();
  const mcp = await connectToMcp(context.itx, SHOP, { headers }, noWebhook);
  // exact: the task crosses as the server gave it, and the answer has nothing else
  expect(await mcp.callToolResult("make_report", { month: "November" })).toEqual({
    content: [],
    task: WORKING,
  });
  // the server answers with a task only to a client that declares the extension
  expect(context.sent.at(-1)).toMatchObject({
    method: "tools/call",
    capabilities: { extensions: { "io.modelcontextprotocol/tasks": {} } },
  });
  // the first ask after five seconds: the server asks for two at least
  const follow = { taskId: "task-1", tool: "make_report", since: NOW, waitMs: 5000 };
  expect(context.schedules).toHaveLength(1);
  const key = z
    .tuple([z.literal("mcp-task"), z.string().regex(/^[0-9a-f]{32}$/)])
    .parse(context.schedules[0]?.set?.key);
  expect(context.schedules[0]?.set).toEqual({
    key,
    when: { afterMs: 5000 },
    events: [
      {
        type: "events.iterate.com/itx/run-requested",
        payload: {
          code: followUpScript({
            server: SHOP,
            options: { headers },
            key,
            call: ["followTask", follow],
            failed: {
              type: "events.iterate.com/mcp/task-settled",
              // the key of the asking's one end, as `followTask` writes it
              idempotencyKey: `mcp/task-settled:${key[1]}:${String(NOW)}`,
              payload: { server: SHOP, tool: "make_report", taskId: "task-1", status: "lost" },
            },
            // a task has no end of its own that the mind knows
            lapsesAt: null,
          }),
        },
      },
    ],
  });
  expect(context.appended).toEqual([]);
  // the same answer from `callTool`, which a tool's own method calls
  expect(await mcp.callTool("make_report")).toMatchObject({ task: { taskId: "task-1" } });
  await mcp.close();
});

test("getTask and cancelTask name the task in Mcp-Name, as the extension asks", async () => {
  const context = contextOfFake();
  const mcp = await connectToMcp(context.itx, SHOP, {}, noWebhook);
  // exact: the task as the server states it
  expect(await mcp.getTask("task-1")).toEqual(WORKING);
  await mcp.cancelTask("task-1");
  expect(context.sent.slice(-2)).toMatchObject([
    { method: "tasks/get", name: "task-1", params: { taskId: "task-1" } },
    { method: "tasks/cancel", name: "task-1", params: { taskId: "task-1" } },
  ]);
  await mcp.close();
});

test("an answer that says it is a task and names no task is refused, and so is a follow that is none", async () => {
  const context = contextOfFake();
  const mcp = await connectToMcp(context.itx, SHOP, {}, noWebhook);
  await expect(mcp.callTool("make_no_task")).rejects.toThrow("taskId");
  await expect(mcp.followTask({ taskId: "task-1", waitMs: -1 })).rejects.toThrow("waitMs");
  expect(context).toMatchObject({ schedules: [], appended: [] });
  await mcp.close();
});

test.for([
  { name: "three times the wait before", waitMs: 5000, pollIntervalMs: 2000, afterMs: 15_000 },
  { name: "ten minutes at most", waitMs: 5 * 60_000, pollIntervalMs: 2000, afterMs: 10 * 60_000 },
  { name: "no sooner than the server asks", waitMs: 5000, pollIntervalMs: 60_000, afterMs: 60_000 },
  // the server's own word is bounded too: no wait is longer than the asking
  { name: "a day at most", waitMs: 5000, pollIntervalMs: 7 * DAY_MS, afterMs: DAY_MS },
  // so that every asking ends within its day, whatever its caller says of its start
  {
    name: "and an asking that names a start after now began now",
    since: NOW + 7 * DAY_MS,
    waitMs: 5000,
    pollIntervalMs: 2000,
    afterMs: 15_000,
  },
])(
  "an ask that finds the task at work sets the next ask: $name",
  async ({ since = NOW, waitMs, pollIntervalMs, afterMs }) => {
    vi.useFakeTimers({ toFake: ["Date"], now: NOW });
    onTestFinished(() => void vi.useRealTimers());
    const context = contextOfFake();
    context.state({ ...WORKING, pollIntervalMs });
    const mcp = await connectToMcp(context.itx, SHOP, {}, noWebhook);
    expect(await mcp.followTask({ taskId: "task-1", tool: "make_report", since, waitMs })).toEqual({
      taskId: "task-1",
      status: "working",
    });
    expect(context).toMatchObject({
      schedules: [
        {
          set: {
            when: { afterMs },
            events: [
              {
                payload: {
                  code: expect.stringContaining(
                    JSON.stringify(JSON.stringify({ since: NOW, waitMs: afterMs })).slice(2, -2),
                  ),
                },
              },
            ],
          },
        },
      ],
      appended: [],
    });
    await mcp.close();
  },
);

test.for([
  {
    name: "a completed task, with the tool's whole result",
    task: { ...WORKING, status: "completed", statusMessage: "Counted", result: REPORT },
    settled: { status: "completed", statusMessage: "Counted", result: REPORT },
  },
  {
    name: "a failed task, with the server's error",
    task: { ...WORKING, status: "failed", error: { code: -32603, message: "the shop burned" } },
    settled: { status: "failed", error: { code: -32603, message: "the shop burned" } },
  },
  {
    name: "a cancelled task",
    task: { ...WORKING, status: "cancelled", statusMessage: "Cancelled by the shop" },
    settled: { status: "cancelled", statusMessage: "Cancelled by the shop" },
  },
  {
    name: "a task that asks for input, which this client gives none",
    task: { ...WORKING, status: "input_required", inputRequests: { name: { method: "x" } } },
    settled: { status: "input_required", inputRequests: { name: { method: "x" } } },
  },
  {
    name: "a task that the server knows no more",
    task: null,
    settled: { status: "lost", error: expect.stringContaining("Unknown task task-1") },
  },
  {
    name: "a task that still works a day after the asking began",
    task: WORKING,
    since: NOW - DAY_MS - 1,
    settled: { status: "lost", error: expect.stringContaining("a day after the asking began") },
  },
])(
  "an ask ends with one fact on the context, and no further ask: $name",
  async ({ task, since = NOW, settled }) => {
    vi.useFakeTimers({ toFake: ["Date"], now: NOW });
    onTestFinished(() => void vi.useRealTimers());
    const context = contextOfFake();
    context.state(task);
    const mcp = await connectToMcp(context.itx, SHOP, {}, noWebhook);
    const follow = { taskId: "task-1", tool: "make_report", since, waitMs: 5000 };
    expect(await mcp.followTask(follow)).toEqual({ taskId: "task-1", status: settled.status });
    expect(context).toMatchObject({
      schedules: [],
      appended: [
        {
          type: "events.iterate.com/mcp/task-settled",
          // the task and the asking's start: a later asking of the same task writes its own
          idempotencyKey: expect.stringMatching(
            new RegExp(`^mcp/task-settled:[0-9a-f]{32}:${String(since)}$`),
          ),
          payload: { server: SHOP, tool: "make_report", taskId: "task-1", ...settled },
        },
      ],
    });
    await mcp.close();
  },
);

test("the script of an ask asks the server, and a task that has ended lands on the context", async () => {
  const context = contextOfFake();
  const mcp = await connectToMcp(context.itx, SHOP, {}, noWebhook);
  await mcp.callTool("make_report");
  context.state({ ...WORKING, status: "completed", result: REPORT });
  expect(await context.runScheduled(context.schedules[0])).toEqual({
    taskId: "task-1",
    status: "completed",
  });
  expect(context).toMatchObject({
    appended: [
      {
        type: "events.iterate.com/mcp/task-settled",
        payload: { tool: "make_report", status: "completed", result: REPORT },
      },
    ],
  });
  // The script's first act is its claim: the same key, set to the second try, two minutes on.
  // The end takes the claim away, so nothing asks again.
  const key = context.schedules[0]?.set?.key;
  expect(context.schedules.slice(1)).toMatchObject([
    { set: { key, when: { afterMs: 2 * 60_000 } } },
    { cancel: key },
  ]);
  await mcp.close();
});

test("an ask of the schedule that a caller's followTask overtakes writes no second end", async () => {
  const context = contextOfFake();
  const mcp = await connectToMcp(context.itx, SHOP, {}, noWebhook);
  await mcp.callTool("make_report");
  context.state({ ...WORKING, status: "completed", result: REPORT });
  // a caller asks while the server answers the schedule's own ask: it settles the task
  context.whileAsking(async () => {
    context.whileAsking(async () => undefined);
    await mcp.followTask({ taskId: "task-1" });
  });
  expect(await context.runScheduled(context.schedules[0])).toEqual({
    taskId: "task-1",
    status: "completed",
  });
  // the caller's ask took the claim away, so the schedule's ask found it gone and wrote nothing
  expect(context.appended).toHaveLength(1);
  expect(context.schedules.map((row) => (row.set ? "set" : "cancel"))).toEqual([
    "set",
    "set",
    "cancel",
  ]);
  await mcp.close();
});

test.for([
  {
    name: "names another task",
    task: { ...WORKING, taskId: "task-2", status: "completed", result: REPORT },
    refused: "with another task",
  },
  {
    name: "is completed and has no result",
    task: { ...WORKING, status: "completed" },
    refused: "a task that is completed has no result",
  },
  {
    name: "is failed and has no error",
    task: { ...WORKING, status: "failed" },
    refused: "a task that is failed has no error",
  },
  {
    name: "asks for input and names none",
    task: { ...WORKING, status: "input_required" },
    refused: "a task that is input_required has no inputRequests",
  },
])(
  "an answer about a task that $name is refused, and settles nothing",
  async ({ task, refused }) => {
    const context = contextOfFake();
    const mcp = await connectToMcp(context.itx, SHOP, {}, noWebhook);
    await mcp.callTool("make_report");
    context.state(task);
    await expect(mcp.followTask({ taskId: "task-1" })).rejects.toThrow(refused);
    await expect(mcp.getTask("task-1")).rejects.toThrow(refused);
    // no end is written, and the context's own ask still stands
    expect(context.appended).toEqual([]);
    expect(context.schedules).toHaveLength(1);
    await mcp.close();
  },
);

test("a connection with a credential written out declares no MCP tasks, and follows none", async () => {
  const context = contextOfFake();
  const headers = { authorization: "Bearer abc" };
  const mcp = await connectToMcp(context.itx, SHOP, { headers }, noWebhook);
  // the server answers such a client with a result, as it does to any client without the extension
  expect(await mcp.callTool("make_report")).toBe("no task for this client");
  expect(context.sent.at(-1)).toMatchObject({ method: "tools/call" });
  expect(context.sent.at(-1)?.capabilities).not.toHaveProperty([
    "extensions",
    "io.modelcontextprotocol/tasks",
  ]);
  // a server that answers with a task all the same is refused, and so is a follow
  const why = 'the connection\'s header "authorization" is written out';
  await expect(mcp.callTool("make_task_anyway")).rejects.toThrow(why);
  await expect(mcp.followTask({ taskId: "task-1" })).rejects.toThrow(why);
  // no script, so no copy of the credential in the context's log
  expect(context).toMatchObject({ schedules: [], appended: [] });
  await mcp.close();
});

test("followTask by a caller, beside the context's own ask, ends that ask: the end is written once", async () => {
  const context = contextOfFake();
  const mcp = await connectToMcp(context.itx, SHOP, {}, noWebhook);
  await mcp.callTool("make_report");
  context.state({ ...WORKING, status: "completed", result: REPORT });
  expect(await mcp.followTask({ taskId: "task-1" })).toEqual({
    taskId: "task-1",
    status: "completed",
  });
  // the ask that the call set would find the same end and write it again: it is cancelled
  expect(context.schedules.at(-1)).toEqual({ cancel: context.schedules[0]?.set?.key });
  expect(context.appended).toHaveLength(1);
  await mcp.close();
});

test("an ask that gets no answer twice, two minutes apart, tells the context that the task is lost", async () => {
  const context = contextOfFake();
  const mcp = await connectToMcp(context.itx, SHOP, {}, noWebhook);
  await mcp.callTool("make_report");
  context.state("unreachable");
  const [first] = context.schedules;
  const key = first?.set?.key;
  // the first try: its claim is the second try, and that stands when the try fails
  await expect(context.runScheduled(first)).rejects.toThrow("the shop is closed");
  expect(context.schedules).toMatchObject([first, { set: { key, when: { afterMs: 120_000 } } }]);
  expect(context.appended).toEqual([]);
  // the second try, as the schedule fires it: its claim is the fact that it did not end
  await expect(context.runScheduled(context.schedules[1])).rejects.toThrow("the shop is closed");
  expect(context.sent.filter(({ method }) => method === "tasks/get")).toHaveLength(2);
  const lost = [
    {
      type: "events.iterate.com/mcp/task-settled",
      // the key that a `followTask` of this asking writes its end under
      idempotencyKey: expect.stringMatching(/^mcp\/task-settled:[0-9a-f]{32}:\d+$/),
      payload: {
        server: SHOP,
        tool: "make_report",
        taskId: "task-1",
        status: "lost",
        error: expect.stringContaining("the shop is closed"),
      },
    },
  ];
  expect(context.appended).toEqual(lost);
  // the last claim is a script that would have said so by itself after eleven minutes; the try
  // took it away, and nothing asks again
  expect(context.schedules.slice(2)).toMatchObject([
    {
      set: {
        key,
        when: { afterMs: 11 * 60_000 },
        events: [{ type: "events.iterate.com/itx/run-requested" }],
      },
    },
    { cancel: key },
  ]);
  // ONE END FOR ONE ASKING: had the claim stayed and fired, its script writes under the same key,
  // and the log keeps the end that the try wrote
  await context.runScheduled(context.schedules[2]);
  expect(context.appended).toEqual(lost);
  await mcp.close();
});

test("the end that a last claim writes by itself does not stand beside a task's end", async () => {
  vi.useFakeTimers({ toFake: ["Date"], now: NOW });
  onTestFinished(() => void vi.useRealTimers());
  const context = contextOfFake();
  const mcp = await connectToMcp(context.itx, SHOP, {}, noWebhook);
  await mcp.callTool("make_report");
  context.state("unreachable");
  await expect(context.runScheduled(context.schedules[0])).rejects.toThrow("the shop is closed");
  // the second try finds the end, and writes it under the asking's key
  context.state({ ...WORKING, status: "completed", result: REPORT });
  expect(await context.runScheduled(context.schedules[1])).toEqual({
    taskId: "task-1",
    status: "completed",
  });
  const completed = [
    {
      idempotencyKey: expect.stringMatching(new RegExp(`^mcp/task-settled:[0-9a-f]{32}:${String(NOW)}$`)),
      payload: { status: "completed", result: REPORT },
    },
  ];
  expect(context.appended).toMatchObject(completed);
  // its claim, had it stayed: the script's "lost" has the same key, so the log refuses it
  await context.runScheduled(context.schedules[2]);
  expect(context.appended).toHaveLength(1);
  expect(context.appended).toMatchObject(completed);
  await mcp.close();
});

const noWebhook = () => Promise.reject(new Error("no webhook in this test"));

type Scheduled = { set?: { key: unknown; when: unknown; events: unknown[] }; cancel?: unknown };

/** A context whose `fetch` reaches a fake server with the tool `make_report`, which the server
 *  runs as the task `task-1` for a client that declares MCP tasks, and the tool `make_no_task`,
 *  whose answer says it is a task and has no id. What it recorded: each request the server got
 *  (its method, its `Mcp-Name` header, its params, the capabilities it declared), each schedule
 *  set, and each event appended. `state` says what the server answers about the task from then
 *  on: a task, null for a task it does not know, or "unreachable" for a server whose answer is
 *  an internal error. `runScheduled` runs the script of a schedule as the context would. */
function contextOfFake() {
  let task: Record<string, unknown> | null | "unreachable" = WORKING;
  const DeclaresTasks = z.looseObject({
    "io.modelcontextprotocol/clientCapabilities": z.looseObject({
      extensions: z.looseObject({ "io.modelcontextprotocol/tasks": z.looseObject({}) }),
    }),
  });
  const handler = createMcpHandler(() => {
    const server = new McpServer({ name: "fake-petshop", version: "1" });
    server.registerTool("make_report", {}, (ctx) =>
      DeclaresTasks.safeParse(ctx.mcpReq.envelope).success
        ? // the cast: the SDK's type of a tool's answer knows no task, and hands this one on
          ({ resultType: "task", ...WORKING } as never)
        : { content: [{ type: "text", text: "no task for this client" }] },
    );
    // the cast: as above
    server.registerTool(
      "make_no_task",
      {},
      () => ({ resultType: "task", status: "working" }) as never,
    );
    // a server that answers with a task to a client that declared none, against the extension
    server.registerTool("make_task_anyway", {}, () => ({ resultType: "task", ...WORKING }) as never);
    return server;
  });
  const sent: { method: string; name: string | null; params: unknown; capabilities: unknown }[] =
    [];
  const schedules: Scheduled[] = [];
  const fired = new Set<Scheduled | undefined>();
  const appended: { idempotencyKey?: string }[] = [];
  // as the log: a key that comes back with the same body writes nothing, and with another body
  // it is refused
  const append = async (event: { idempotencyKey?: string }) => {
    const kept = appended.find(
      (row) => event.idempotencyKey && row.idempotencyKey === event.idempotencyKey,
    );
    if (!kept) return void appended.push(event);
    if (JSON.stringify(kept) !== JSON.stringify(event))
      throw Object.assign(new Error(`${String(event.idempotencyKey)}: another body`), {
        code: "IDEMPOTENCY_CONFLICT",
      });
  };
  // THE CONTEXT'S SCHEDULES, as the kernel keeps them: `schedules` is every `set` and `cancel` in
  // order, and a row's place is its offset. The schedule of a key stands while its newest row is
  // a `set` that has not fired. A receipt cancels the one definition that it names.
  const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
  const standing = (key: unknown) => {
    const at = schedules.findLastIndex((row) => same(row.set?.key, key) || same(row.cancel, key));
    const row = schedules[at];
    return row?.set && !fired.has(row) ? { ...row.set, scheduledAtOffset: at } : null;
  };
  const Receipt = z.object({ key: z.string(), scheduledAtOffset: z.number() });
  const scheduleTable = {
    set: async (set: NonNullable<Scheduled["set"]>) => ({
      key: JSON.stringify(set.key),
      scheduledAtOffset: schedules.push({ set }) - 1,
    }),
    get: async (key: unknown) => standing(key),
    cancel: async (named: unknown) => {
      const receipt = Receipt.safeParse(named);
      if (!receipt.success) return void schedules.push({ cancel: named });
      const key: unknown = JSON.parse(receipt.data.key);
      if (standing(key)?.scheduledAtOffset === receipt.data.scheduledAtOffset)
        schedules.push({ cancel: key });
    },
  };
  let asking: (() => Promise<void>) | undefined;
  const Sent = z.object({
    id: z.union([z.string(), z.number()]).optional(),
    method: z.string(),
    params: z
      .looseObject({
        _meta: z
          .looseObject({ "io.modelcontextprotocol/clientCapabilities": z.unknown() })
          .optional(),
      })
      .optional(),
  });
  const itx = {
    fetch: async (request: Request) => {
      if (request.method !== "POST") return await handler.fetch(request);
      const {
        id,
        method,
        params: { _meta, ...params } = {},
      } = Sent.parse(await request.clone().json());
      sent.push({
        method,
        name: request.headers.get("mcp-name"),
        params,
        capabilities: _meta?.["io.modelcontextprotocol/clientCapabilities"],
      });
      // The SDK's server (2.1.0) answers "Method not found" to the tasks extension's own
      // methods, so a server of the extension answers them before it, as the dummy pet shop does.
      if (!method.startsWith("tasks/")) return await handler.fetch(request);
      await asking?.();
      if (task === "unreachable" || !task)
        return Response.json({
          jsonrpc: "2.0",
          id,
          error: task
            ? { code: -32603, message: "the shop is closed" }
            : { code: -32602, message: "Unknown task task-1" },
        });
      return Response.json({
        jsonrpc: "2.0",
        id,
        result: { resultType: "complete", ...(method === "tasks/get" && task) },
      });
    },
    builtins: {
      schedules: scheduleTable,
      append,
    },
    // the cast: the connection uses `fetch`, its schedules and `append` alone of a context's itx
  } as unknown as LibraryItx;
  return {
    itx,
    sent,
    schedules,
    appended,
    state: (next: typeof task) => void (task = next),
    whileAsking: (hook: () => Promise<void>) => void (asking = hook),
    runScheduled: async (scheduled: Scheduled | undefined) => {
      // as the kernel: a schedule that fires is gone before its script runs
      fired.add(scheduled);
      const { code } = z
        .object({ payload: z.object({ code: z.string() }) })
        .parse(scheduled?.set?.events[0]).payload;
      // the script is the text of a function of the context's itx, as the kernel runs it
      const script: (itx: unknown) => Promise<unknown> = runInThisContext(`(${code})`);
      return await script({
        connectToMcp: (server: string, options: { headers?: Record<string, string> }) =>
          connectToMcp(itx, server, options, noWebhook),
        append,
        schedules: scheduleTable,
      });
    },
  };
}