iterate.com / kernel

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

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

import { Client, ProtocolError, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
import { SkillsClient } from "@modelcontextprotocol/client/ext/skills";
import { RpcTarget } from "capnweb";
import { z } from "zod";
import type { McpConnectionApi, McpConnectOptions, McpServerInfo } from "iterate/api";
import { keySortedForPrint } from "iterate/expression";
import { bytesToBase64, STEP_FORGIVEN_EVERY_MS } from "iterate/lib";
import { basicCredentialOf, SECRET_PLACEHOLDER } from "iterate/secret-placeholder";
import { RUN_DEADLINE_MS } from "iterate/stream/run";
import { sha256Hex, type LibraryItx } from "core-itx";
import { subclassWithMethods } from "./connection.ts";

type McpWebhook = { url: string; secret: string };

type McpLiveClient = { client: Client; transport: StreamableHTTPClientTransport };

/** The extensions this client declares, in `initialize` and in each request of revision 2026-07-28.
 *  MCP Apps (modelcontextprotocol/ext-apps, 2026-01-26): the client may read a tool's `ui://`
 *  resource and draw it, so a server may offer its tools' views. MCP Events (SEP-3415): the client
 *  knows the extension. MCP tasks (SEP-2663): a server may answer a tool call with a task, and
 *  it must not answer so to a client that does not declare this. */
const MCP_EXTENSIONS = {
  "io.modelcontextprotocol/ui": { mimeTypes: ["text/html;profile=mcp-app"] },
  "io.modelcontextprotocol/events": {},
  "io.modelcontextprotocol/tasks": {},
};
/** A resource read answers at most this many characters of text and base64 in all: an event holds
 *  up to 8 million, and an MCP App's document is 0.1 to 5 MB as a rule. */
export const MCP_RESOURCE_MAX_CHARS = 8_000_000;
/** The lifetime this client suggests for a webhook subscription: a day, the longest that the
 *  extension recommends ("Recommended grants", SEP-3415). The server's grant decides. */
const MCP_SUBSCRIPTION_TTL_MS = 24 * 60 * 60_000;
/** How long after a follow-up's first try its second and last try runs. */
const MCP_FOLLOW_UP_SECOND_TRY_MS = 2 * 60_000;
/** How long after a follow-up's last try began the context is told that it did not end: longer
 *  than a script may run. */
const MCP_FOLLOW_UP_UNENDED_MS = RUN_DEADLINE_MS + 60_000;
/** The wait before the mind first asks a server about a task, and the longest wait. Each wait is
 *  three times the one before, so a task of seconds is noticed in seconds, and a task of hours
 *  costs one script run every ten minutes. Three asks fall into the first two minutes: the
 *  kernel's loop guard forgives one step in that time and counts three, of the sixteen that it
 *  allows a chain (core/itx/src/cause.ts). */
const MCP_TASK_FIRST_WAIT_MS = 5_000;
const MCP_TASK_LONGEST_WAIT_MS = 10 * 60_000;
/** How long the mind asks about one task. A task that still works then is `lost`, with the
 *  reason, and `followTask` asks again. */
const MCP_TASK_FOLLOWED_MS = 24 * 60 * 60_000;
/** Where a task answer is handed to the SDK (`carryTaskAnswers`). */
const MCP_TASK_META = "com.iterate/mcp-task";

/** A tool named like one of the connection's own members is reachable through `callTool` only. */
export async function connectToMcp(
  itx: LibraryItx,
  url: string,
  options: McpConnectOptions,
  webhook: () => Promise<McpWebhook>,
): Promise<McpConnectionRpcTarget> {
  const unfollowed = whyNoFollowUp(url, options);
  // A connection with no follow-up could not ask about a task later. So it does not declare MCP
  // tasks, and a server answers its tool calls with results, as it does to any client without.
  const { "io.modelcontextprotocol/tasks": _tasks, ...extensionsWithoutTasks } = MCP_EXTENSIONS;
  /** Every GET is answered 405: the older protocol's standing stream may be held open for good and
   *  keep this context resident, and nothing here listens. */
  const connect = async (): Promise<McpLiveClient> => {
    const client = new Client(
      { name: "iterate-context", version: "1" },
      {
        versionNegotiation: { mode: "auto" },
        capabilities: {
          extensions: unfollowed ? extensionsWithoutTasks : MCP_EXTENSIONS,
        },
      },
    );
    const transport = new StreamableHTTPClientTransport(new URL(url), {
      fetch: async (input, init) => {
        if (init?.method === "GET") return new Response(null, { status: 405 });
        const request = new Request(input, init);
        const eventName = eventNameHeaderOf(request.headers.get("mcp-method"), init?.body);
        if (eventName) request.headers.set("mcp-name", eventName);
        return itx.fetch(request);
      },
      requestInit: { headers: options.headers },
    });
    await client.connect(transport);
    carryTaskAnswers(transport);
    return { client, transport };
  };
  const live = await connect();
  try {
    const { tools } = await live.client.listTools();
    const Connection = subclassWithMethods(
      McpConnectionRpcTarget,
      tools.map((tool) => tool.name),
      (self, name, args) => self.callTool(name, args as Record<string, unknown> | undefined),
    );
    return new Connection(itx, url, options, live, connect, webhook, unfollowed);
  } catch (error) {
    await end(live);
    throw error;
  }
}

async function end({ client, transport }: McpLiveClient) {
  await transport.terminateSession().catch(() => undefined);
  await client.close();
}

export class McpConnectionRpcTarget extends RpcTarget implements McpConnectionApi {
  readonly #itx: LibraryItx;
  /** The URL the context connected to: the name of the server in everything the connection
   *  answers about it, whatever the server calls itself. */
  readonly #server: string;
  readonly #options: McpConnectOptions;
  readonly #connect: () => Promise<McpLiveClient>;
  readonly #webhook: () => Promise<McpWebhook>;
  readonly #serverInfo: McpServerInfo;
  #live: Promise<McpLiveClient> | null;
  /** Whether the server declares MCP Events, once it is known (`#offersEvents`). */
  #eventsDeclared: boolean | undefined;
  /** Why this connection has no follow-up (`whyNoFollowUp`), or null. */
  readonly #unfollowed: string | null;
  constructor(
    itx: LibraryItx,
    server: string,
    options: McpConnectOptions,
    live: McpLiveClient,
    connect: () => Promise<McpLiveClient>,
    webhook: () => Promise<McpWebhook>,
    unfollowed: string | null,
  ) {
    super();
    this.#itx = itx;
    this.#server = server;
    this.#options = options;
    this.#live = Promise.resolve(live);
    this.#connect = connect;
    this.#webhook = webhook;
    this.#unfollowed = unfollowed;
    this.#serverInfo = {
      protocolVersion: live.client.getNegotiatedProtocolVersion(),
      capabilities: live.client.getServerCapabilities(),
      serverInfo: live.client.getServerVersion(),
    };
  }
  async #client(): Promise<Client> {
    const live = (this.#live ??= this.#connect());
    try {
      return (await live).client;
    } catch (error) {
      if (this.#live === live) this.#live = null;
      throw error;
    }
  }
  serverInfo() {
    return this.#serverInfo;
  }
  /** Every page: with no cursor the SDK follows `nextCursor` to the end, and refuses a listing of
   *  more than 64 pages (its `listMaxPages`). */
  async listTools() {
    return (await (await this.#client()).listTools()).tools;
  }
  async #call(name: string, args: Record<string, unknown> | undefined) {
    const client = await this.#client();
    // a tool may run as long as a script may (the SDK's default stops it at 60 s)
    const result = await client.callTool(
      { name, arguments: args || {} },
      { timeout: RUN_DEADLINE_MS },
    );
    const carried = result._meta?.[MCP_TASK_META];
    if (!carried) return result;
    // THE SERVER RUNS THE CALL AS A TASK (MCP tasks, SEP-2663:
    // https://github.com/modelcontextprotocol/ext-tasks/blob/main/specification/2026-07-28/tasks.md).
    // The caller gets the task at once. The result comes when the server has it, which may be
    // hours on, so no script waits for it: the context's own schedule asks the server
    // (`followTask`), and the end lands on this context as `events.iterate.com/mcp/task-settled`.
    // An answer that says it is a task and is none (no id, a status nobody knows) is refused. So
    // is a task for a connection that did not declare MCP tasks: nothing here could follow it.
    if (this.#unfollowed)
      throw new Error(
        `the MCP server ${this.#server} answered the tool call ${name} with a task, and this connection did not declare MCP tasks: ${this.#unfollowed}`,
      );
    const task = Task.parse(carried);
    await this.#askAboutTaskLater({
      taskId: task.taskId,
      tool: name,
      since: Date.now(),
      waitMs: taskWaitMs(MCP_TASK_FIRST_WAIT_MS, task.pollIntervalMs),
    });
    return { content: [], task };
  }
  async callToolResult(...[name, args]: Parameters<McpConnectionApi["callToolResult"]>) {
    return await this.#call(name, args);
  }
  async callTool(...[name, args]: Parameters<McpConnectionApi["callTool"]>) {
    const result = await this.#call(name, args);
    if ("task" in result) return result;
    const text = result.content
      .flatMap((part) => (part.type === "text" ? [part.text] : []))
      .join("\n");
    if (result.isError) throw new Error(`MCP tool ${name} failed: ${text || "no message"}`);
    if (result.structuredContent !== undefined) return result.structuredContent;
    if (text === "") return result;
    try {
      return JSON.parse(text);
    } catch {
      return text;
    }
  }
  async getTask(taskId: string) {
    const client = await this.#client();
    const task = await client.request({ method: "tasks/get", params: { taskId } }, Task);
    // a server's answer about another task is no word on this one
    if (task.taskId !== taskId)
      throw new Error(
        `the MCP server ${this.#server} answered tasks/get for the task ${taskId} with another task (${JSON.stringify(task.taskId.slice(0, 80))})`,
      );
    return task;
  }
  async cancelTask(taskId: string) {
    const client = await this.#client();
    await client.request({ method: "tasks/cancel", params: { taskId } }, z.looseObject({}));
  }
  async followTask(follow: Parameters<McpConnectionApi["followTask"]>[0]) {
    if (this.#unfollowed)
      throw new Error(`this connection follows no task: ${this.#unfollowed}`);
    // a caller's word, and the script's: checked like any input
    const {
      taskId,
      tool,
      waitMs = MCP_TASK_FIRST_WAIT_MS,
      claim,
      ...asked
    } = TaskFollowed.parse(follow);
    // when the asking began: never later than now, so every asking ends within its day
    const since = Math.min(asked.since || Date.now(), Date.now());
    const key = await this.#scheduleKey("mcp-task", [taskId]);
    // One fact for one asking: an ask that finds the same end twice writes it once. An asking
    // that began later (`followTask` after a task was `lost`) writes its own. The end ends every
    // asking of the task: a caller's `followTask` beside the context's own schedule takes that
    // schedule away, and an ask of the schedule that runs just then finds its claim gone and
    // writes nothing (`#holds`).
    const settle = async (
      outcome: Pick<
        z.output<typeof Task>,
        "statusMessage" | "result" | "error" | "inputRequests"
      > & { status: z.output<typeof Task>["status"] | "lost" },
    ) => {
      if (!(await this.#holds(key, claim))) return { taskId, status: outcome.status };
      if (await this.#itx.builtins.schedules.get(key))
        await this.#itx.builtins.schedules.cancel(key);
      await this.#itx.builtins.append({
        type: "events.iterate.com/mcp/task-settled",
        idempotencyKey: `mcp/task-settled:${key[1]}:${String(since)}`,
        payload: { server: this.#server, tool, taskId, ...outcome },
      });
      return { taskId, status: outcome.status };
    };
    let task: z.output<typeof Task>;
    try {
      task = await this.getTask(taskId);
    } catch (error) {
      // -32602 is the server's answer for a task that it does not know, or knows no more: its
      // word on the task, and the end of the asking. Any other failure may pass, so it is
      // thrown, and the script that asks tries again.
      if (!(error instanceof ProtocolError) || error.code !== -32602) throw error;
      return settle({ status: "lost", error: error.message });
    }
    if (task.status !== "working") {
      const { status, statusMessage, result, error, inputRequests } = task;
      return settle({ status, statusMessage, result, error, inputRequests });
    }
    if (Date.now() - since > MCP_TASK_FOLLOWED_MS)
      return settle({
        status: "lost",
        error: "the task still works a day after the asking began: followTask asks again",
      });
    await this.#askAboutTaskLater(
      {
        taskId,
        tool,
        since,
        waitMs: taskWaitMs(Math.min(MCP_TASK_LONGEST_WAIT_MS, waitMs * 3), task.pollIntervalMs),
      },
      claim,
    );
    return { taskId, status: task.status };
  }
  /** The next ask about a task: a schedule of the context whose script calls `followTask`. When
   *  that script fails twice nothing asks any more, and it tells the context that the task is
   *  `lost` to the mind. An ask of the schedule sets the next one only while it holds its claim
   *  (`#holds`). */
  async #askAboutTaskLater(
    follow: { taskId: string; tool: string | undefined; since: number; waitMs: number },
    claim?: number,
  ) {
    const { taskId, tool } = follow;
    const key = await this.#scheduleKey("mcp-task", [taskId]);
    if (!(await this.#holds(key, claim))) return;
    await this.#itx.builtins.schedules.set({
      key,
      when: { afterMs: follow.waitMs },
      events: [
        {
          type: "events.iterate.com/itx/run-requested",
          payload: {
            code: followUpScript({
              server: this.#server,
              options: this.#options,
              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(follow.since)}`,
                payload: { server: this.#server, tool, taskId, status: "lost" },
              },
              lapsesAt: null,
            }),
          },
        },
      ],
    });
  }
  async readResource(uri: string) {
    const client = await this.#client();
    const { contents } = await client.readResource({ uri });
    // the SDK has checked the shape; the size is checked here, before it crosses to the caller
    let size = 0;
    for (const part of contents) size += ("text" in part ? part.text : part.blob).length;
    refuseOverBound(uri, size);
    return { contents };
  }
  // THE SKILLS OF ANOTHER SERVER (MCP's Skills extension, SEP-2640:
  // https://skills.extensions.modelcontextprotocol.io/specification/beta/skills). The SDK's
  // `SkillsClient` is the extension's host side: it checks each entry, and each file it reads
  // against its entry. A skill is that server's text, so it is data to whoever reads it: this
  // connection runs nothing of a skill, and gives a skill no reach.

  /** Every page. A server that does not declare the extension has no skill. A listing with an
   *  entry that breaks the extension's rules is refused, and the error names each such entry. */
  async listSkills() {
    return (await new SkillsClient(await this.#client()).list()).skills;
  }
  async getSkill(uri: string) {
    return (await new SkillsClient(await this.#client()).get(uri)).skill;
  }
  async readSkill(...[uri, file]: Parameters<McpConnectionApi["readSkill"]>) {
    const skills = new SkillsClient(await this.#client());
    // The entry as the server has it now. The extension asks a host to check a file against the
    // entry that it holds, and this connection holds none between two calls.
    const { skill } = await skills.get(uri);
    const read = await skills.read(skill, file);
    // text as the server sent it, and any other file as base64
    const blob = read.text ? undefined : bytesToBase64(read.bytes);
    refuseOverBound(read.uri, (read.text || blob || "").length);
    return {
      server: this.#server,
      uri: read.uri,
      mimeType: read.mimeType,
      text: read.text || undefined,
      blob,
      verified: read.verified,
    };
  }
  // THE EVENTS OF ANOTHER SERVER (MCP Events, SEP-3415:
  // https://github.com/modelcontextprotocol/ext-events/blob/main/specification/beta/events/events.mdx).
  // Of the extension's three delivery modes this client subscribes by WEBHOOK: the server POSTs
  // each event to the mind, and no connection is held open. `pollEvents` is one poll. The push
  // mode is a request held open for good, which would keep the context resident, so it has none.

  /** WHETHER THE SERVER DECLARES MCP EVENTS: a client sends no `events/*` request to one that does
   *  not. The extension's place for it is `capabilities.extensions`. Servers written for ChatGPT
   *  declare the top-level `capabilities.events` of the design sketch that came before (SEP-3415,
   *  "Backward Compatibility"), and the SDK keeps no capability that it does not know. So a
   *  server with no entry in `extensions` is asked `server/discover` once more, and that answer
   *  is read whole. A connection of a revision before 2026-07-28 has no `server/discover`, and
   *  no MCP Events: the extension is defined from that revision on. */
  async #offersEvents() {
    if (this.#eventsDeclared !== undefined) return this.#eventsDeclared;
    const { capabilities, protocolVersion } = this.#serverInfo;
    if (EventsInExtensions.safeParse(capabilities).success) return (this.#eventsDeclared = true);
    if (!protocolVersion || protocolVersion < "2026-07-28") return (this.#eventsDeclared = false);
    const discovered = await (
      await this.#client()
    ).request({ method: "server/discover" }, z.looseObject({ capabilities: z.unknown() }));
    return (this.#eventsDeclared = EventsInSketch.safeParse(discovered.capabilities).success);
  }
  async #refuseWithoutEvents() {
    if (!(await this.#offersEvents()))
      throw new Error(`the MCP server ${this.#server} does not declare MCP Events`);
  }
  async listEvents() {
    if (!(await this.#offersEvents())) return [];
    const client = await this.#client();
    const events: z.output<typeof EventsPage>["events"] = [];
    let cursor: string | undefined;
    // the bound of the SDK's own listings (`listMaxPages`)
    for (let page = 0; page < 64; page++) {
      const listed = await client.request(
        { method: "events/list", params: cursor ? { cursor } : {} },
        EventsPage,
      );
      events.push(...listed.events);
      if (!listed.nextCursor) return events;
      cursor = listed.nextCursor;
    }
    throw new Error(`the MCP server ${this.#server} lists its events on more than 64 pages`);
  }
  async pollEvents(...[name, args, options]: Parameters<McpConnectionApi["pollEvents"]>) {
    await this.#refuseWithoutEvents();
    const client = await this.#client();
    return await client.request(
      {
        method: "events/poll",
        params: {
          name,
          arguments: args || {},
          cursor: options?.cursor,
          maxEvents: options?.maxEvents,
        },
      },
      EventsPolled,
    );
  }
  async subscribe(...[name, args, options]: Parameters<McpConnectionApi["subscribe"]>) {
    await this.#refuseWithoutEvents();
    const schedules = this.#itx.builtins.schedules;
    const key = await this.#scheduleKey("mcp-subscription", [name, args || {}]);
    // A RENEWAL GOES ON ONLY WHILE IT HOLDS ITS CLAIM (`#holds`). It asks before it subscribes
    // and again before it sets the next renewal: `unsubscribe` may run beside it.
    const claim = options?.claim;
    const gone = "the subscription was ended, or subscribed again, while this renewal ran";
    if (!(await this.#holds(key, claim))) throw new Error(gone);
    const client = await this.#client();
    const { url, secret } = await this.#webhook();
    const subscription = await client.request(
      {
        method: "events/subscribe",
        params: {
          name,
          arguments: args || {},
          delivery: { mode: "webhook", url, secret },
          ttlMs: MCP_SUBSCRIPTION_TTL_MS,
          cursor: options?.cursor,
        },
      },
      Subscription,
    );
    if (!(await this.#holds(key, claim))) {
      // `unsubscribe` took the claim while the server was asked: what this renewal subscribed is
      // ended again. A claim that another `subscribe` took over is that one's subscription.
      if (!(await schedules.get(key))) await this.#endAtServer(name, args).catch(() => undefined);
      return { ...subscription, notRenewed: gone };
    }
    // only a server that was asked for no expiry may grant none, and this client does not ask
    if (!subscription.refreshBefore) return subscription;
    // THE RENEWAL. A subscription lapses at `refreshBefore` unless the client subscribes again,
    // and a context may be asleep by then. So the context's own schedule runs a script that
    // subscribes again (`followUpScript`), which sets the next schedule: the schedule is the
    // record that this context holds the subscription, and `itx.schedules.list()` shows it.
    // When that script fails twice nothing renews the subscription any more: it lapses, and
    // the script tells the context.
    //
    // After two thirds of the grant: the second try has the last third. No sooner than the
    // kernel's loop guard forgives a step (core/itx/src/cause.ts): each renewal is one step of
    // one chain, and a chain that goes faster is refused at its sixteenth step. No later than the
    // lifetime this client asked for.
    const lifetimeMs = Date.parse(subscription.refreshBefore) - Date.now();
    const afterMs = Math.min(
      MCP_SUBSCRIPTION_TTL_MS,
      Math.max(STEP_FORGIVEN_EVERY_MS, Math.floor((lifetimeMs * 2) / 3)),
    );
    // A GRANT THAT THIS CONTEXT DOES NOT RENEW says so, and why. Two reasons: the connection has
    // no follow-up, or the grant is over before a renewal may run. A renewal after the lapse
    // would be a new subscription with a gap that nobody sees.
    const notRenewed =
      this.#unfollowed ||
      (afterMs >= lifetimeMs
        ? `the server's grant lasts ${String(Math.max(0, Math.round(lifetimeMs / 1000)))} seconds, and a context renews no sooner than after ${String(STEP_FORGIVEN_EVERY_MS / 1000)}`
        : null);
    if (notRenewed) {
      // a renewal that an earlier, longer grant left is this subscription's no more
      if (claim === undefined && (await schedules.get(key))) await schedules.cancel(key);
      return {
        ...subscription,
        notRenewed: `${notRenewed}. Nothing renews the subscription: it lapses at ${subscription.refreshBefore}`,
      };
    }
    const subscribed = { name, arguments: args || {} };
    await schedules.set({
      key,
      when: { afterMs },
      events: [
        {
          type: "events.iterate.com/itx/run-requested",
          payload: {
            code: followUpScript({
              server: this.#server,
              options: this.#options,
              key,
              call: [
                "subscribe",
                subscribed.name,
                subscribed.arguments,
                { cursor: subscription.cursor || undefined },
              ],
              failed: {
                type: "events.iterate.com/mcp/subscription-ended",
                // one end for this renewal, whoever writes it: the moment names the renewal
                idempotencyKey: `mcp/subscription-ended:${key[1]}:${String(Date.now())}`,
                payload: { server: this.#server, ...subscribed },
              },
              lapsesAt: Date.parse(subscription.refreshBefore),
            }),
          },
        },
      ],
    });
    return subscription;
  }
  async unsubscribe(...[name, args]: Parameters<McpConnectionApi["unsubscribe"]>) {
    // The renewal goes first: whatever the server answers below, and whether it still declares
    // the extension, a subscription that nobody renews lapses at its `refreshBefore`.
    const schedules = this.#itx.builtins.schedules;
    const key = await this.#scheduleKey("mcp-subscription", [name, args || {}]);
    const endRenewal = async () => {
      if (await schedules.get(key)) await schedules.cancel(key);
    };
    await endRenewal();
    try {
      await this.#refuseWithoutEvents();
      await this.#endAtServer(name, args);
    } finally {
      // A renewal that began meanwhile has taken its claim, or has set the next renewal: that
      // goes too. A renewal that runs on finds its claim gone, and ends what it subscribed.
      await endRenewal();
    }
  }
  async #endAtServer(name: string, args: Record<string, unknown> | undefined) {
    const client = await this.#client();
    const { url } = await this.#webhook();
    await client.request(
      { method: "events/unsubscribe", params: { name, arguments: args || {}, delivery: { url } } },
      z.looseObject({}),
    );
  }
  /** WHETHER A FOLLOW-UP STILL HOLDS ITS SCHEDULE. A follow-up's script begins with a claim: it
   *  sets the follow-up's schedule again, to what happens when this try does not end
   *  (`followUpScript`), and hands the offset of that fact on as `claim`. While the schedule is
   *  still that one, the follow-up goes on. `unsubscribe`, or an end that another ask wrote,
   *  cancels the schedule; a later `subscribe` or `followTask` of a caller sets its own. Either
   *  way the claim is gone, and this follow-up sets no schedule and writes no end. A caller's
   *  own call has no claim: it begins a follow-up.
   *
   *  The check and the write after it are two calls, and a try starts a moment after its
   *  schedule fired. An `unsubscribe` that falls into one of those gaps can lose against a
   *  renewal: `unsubscribe` asks once more at its end, which catches a renewal that was faster. */
  async #holds(key: [string, string], claim: number | undefined) {
    if (claim === undefined) return true;
    return (await this.#itx.builtins.schedules.get(key))?.scheduledAtOffset === claim;
  }
  /** The key of a follow-up among the context's schedules: a subscription's renewal, or the next
   *  ask about a task. It names the server and how the client signs in there (two accounts are
   *  two subscriptions, and a task is one account's), and then what the follow-up is about: an
   *  event and its arguments, which is the extension's own key of a subscription, or a task's
   *  id. A hash, since a schedule's key holds at most 200 characters. */
  async #scheduleKey(kind: "mcp-subscription" | "mcp-task", about: unknown[]) {
    const named = [this.#server, this.#options, ...about];
    return [
      kind,
      (await sha256Hex(JSON.stringify(named, keySortedForPrint))).slice(0, 32),
    ] satisfies [string, string];
  }
  async close() {
    const live = this.#live;
    this.#live = null;
    const ended = await live?.catch(() => null);
    if (ended) await end(ended);
  }
  [Symbol.dispose](): void {
    void this.close();
  }
}

/** What a read answers crosses to the caller only within `MCP_RESOURCE_MAX_CHARS`. */
function refuseOverBound(uri: string, size: number) {
  if (size > MCP_RESOURCE_MAX_CHARS)
    throw new Error(
      `MCP resource ${uri} has more than ${String(MCP_RESOURCE_MAX_CHARS)} characters`,
    );
}

/** The wait before an ask about a task: the wait the mind wants, but no sooner than the server
 *  asks (`pollIntervalMs`), and never longer than an asking lasts. Whole milliseconds, as a
 *  schedule takes them. */
const taskWaitMs = (wanted: number, pollIntervalMs: number | undefined) =>
  Math.ceil(Math.min(MCP_TASK_FOLLOWED_MS, Math.max(pollIntervalMs || 0, wanted)));

/** WHY A CONNECTION HAS NO FOLLOW-UP, or null. A follow-up's script holds the address and the
 *  headers that the connection was made with, and the script is in the context's log. So a
 *  connection gets a follow-up only when no credential is written out in them: a header that
 *  carries one names a secret (`getSecret("/secrets/<name>")`, which egress fills in), and so
 *  does a password or a key in the address. Which header or parameter carries a credential is
 *  read from its name. */
export function whyNoFollowUp(url: string, options: McpConnectOptions): string | null {
  const address = new URL(url);
  const header = Object.entries(options.headers || {}).find(
    ([name, value]) => CREDENTIAL_NAME.test(name) && !headerIsASecretAlone(name, value),
  )?.[0];
  const parameter = [...address.searchParams].find(
    ([name, value]) => CREDENTIAL_NAME.test(name) && !ONE_SECRET.test(value),
  )?.[0];
  const what =
    header !== undefined
      ? `header ${JSON.stringify(header)}`
      : address.password && !ONE_SECRET.test(decodeURIComponent(address.password))
        ? "address's password"
        : parameter !== undefined
          ? `address's parameter ${JSON.stringify(parameter)}`
          : null;
  return (
    what &&
    `the connection's ${what} is written out, and a follow-up's script would keep it in this context's log. Name a secret in its place ('Bearer getSecret("/secrets/<name>")') and connect again`
  );
}
/** The name of a header or of an address's parameter that carries a credential. */
const CREDENTIAL_NAME = /auth|cookie|key|token|secret|passw|credential|session|signature/i;
/** One placeholder of a secret, and nothing beside it. */
const ONE_SECRET = new RegExp(`^(?:${SECRET_PLACEHOLDER.source})$`);
/** WHETHER A CREDENTIAL'S HEADER HOLDS SECRETS BY NAME ALONE. A header that names one secret and
 *  writes another out would leave the second in the script. So: each pair of a `cookie` is one
 *  placeholder; the password of a `Basic` credential is one; and any other value is one, after
 *  the word of its scheme at most (`Bearer`). */
function headerIsASecretAlone(name: string, value: string) {
  if (name.toLowerCase() === "cookie")
    return value
      .split(";")
      .filter((pair) => pair.trim())
      .every((pair) => ONE_SECRET.test(pair.slice(pair.indexOf("=") + 1).trim()));
  const basic = basicCredentialOf(value);
  if (basic !== null) return ONE_SECRET.test(basic.slice(basic.indexOf(":") + 1));
  return ONE_SECRET.test(value.trim().replace(/^[A-Za-z][A-Za-z-]{0,15}\s+/, ""));
}

/** THE SCRIPT OF A FOLLOW-UP, which a schedule of the context runs as that context's own code. It
 *  connects as the connection did and calls one method of it (`call`): `subscribe`, to renew a
 *  subscription, or `followTask`, to ask about a task. Each of the two sets the next schedule
 *  when there is more to follow.
 *
 *  IT TRIES TWICE, AND EACH TRY BEGINS WITH A CLAIM: the script sets the follow-up's schedule
 *  (`key`) again, to what happens when this try does not end. For the first try that is the
 *  second try, two minutes on. For the last try it is a script that writes the event `failed`.
 *  So the follow-up's schedule stands while a try runs: `unsubscribe`, or the end of a task,
 *  takes it away, and the try then sets no schedule and writes no end (`#holds`). A script that
 *  dies is no silence either. The claim's offset goes to the method as `claim`, in its last
 *  argument. So the script needs `itx.schedules` of its context, beside `itx.connectToMcp` and
 *  `itx.append`: a context whose rules give its code no schedules is told with the event
 *  `failed` at the first try.
 *
 *  A TRY IS THE LAST WHEN A SECOND ONE WOULD COME TOO LATE. `lapsesAt` is when what is followed
 *  ends by itself: a subscription's grant. A second try at or after it would subscribe anew and
 *  call that a renewal, with a gap that nobody sees. So a first try with less than two minutes
 *  left is the last, and a try that begins after the lapse asks the server nothing and tells the
 *  context that the grant lapsed.
 *
 *  ONE END FOR ONE FOLLOW-UP. When the last try fails nothing follows up any more, and the
 *  script tells the context with the event `failed`, to whose payload it adds the error's text.
 *  It tells the context the same way when a renewal's grant is one that the context does not
 *  renew (`notRenewed`). Every writer of that end uses `failed.idempotencyKey`: the script, the
 *  claim of the last try, and `followTask` for a task's end. So the log keeps one end, also
 *  when a try wrote it and could not take its claim away. The values go in as JSON text, so no
 *  value is read as code. */
export function followUpScript(followUp: {
  server: string;
  options: McpConnectOptions;
  key: [string, string];
  call: [method: "subscribe" | "followTask", ...args: unknown[]];
  failed: { type: string; idempotencyKey: string; payload: Record<string, unknown> };
  lapsesAt: number | null;
}) {
  const { failed } = followUp;
  // a second end under the key is refused by the log: that is the purpose, and no failure
  const once = '.catch((failure) => { if (!failure || failure.code !== "IDEMPOTENCY_CONFLICT") throw failure; })';
  // what the last try's claim runs when the try did not end
  const unended = [
    "async (itx) => {",
    `  await itx.append(JSON.parse(${JSON.stringify(JSON.stringify({ ...failed, payload: { ...failed.payload, error: "the last try of the follow-up did not end" } }))}))${once};`,
    "}",
  ].join("\n");
  const aTry = (retry: string | null) =>
    [
      "async (itx) => {",
      `  const { server, options, key, call: [method, ...args], failed, lapsesAt, retry, unended } = JSON.parse(${JSON.stringify(JSON.stringify({ ...followUp, retry, unended }))});`,
      "  const words = (failure) => String((failure && failure.message) || failure).slice(0, 1000);",
      `  const tell = (error) => itx.append({ ...failed, payload: { ...failed.payload, error } })${once};`,
      "  const lapsed = lapsesAt !== null && Date.now() >= lapsesAt;",
      `  const last = !retry || (lapsesAt !== null && Date.now() + ${String(MCP_FOLLOW_UP_SECOND_TRY_MS)} >= lapsesAt);`,
      "  const claim = await itx.schedules",
      "    .set({",
      "      key,",
      `      when: { afterMs: last ? ${String(MCP_FOLLOW_UP_UNENDED_MS)} : ${String(MCP_FOLLOW_UP_SECOND_TRY_MS)} },`,
      '      events: [{ type: "events.iterate.com/itx/run-requested", payload: { code: last ? unended : retry } }],',
      "    })",
      "    .catch(async (failure) => {",
      '      await tell("the follow-up could not hold its schedule: " + words(failure));',
      "      throw failure;",
      "    });",
      "  const held = async () => {",
      "    const now = await itx.schedules.get(key);",
      "    return !!now && now.scheduledAtOffset === claim.scheduledAtOffset;",
      "  };",
      "  const end = async (error) => {",
      "    if (!(await held())) return;",
      "    await tell(error);",
      "    await itx.schedules.cancel(claim);",
      "  };",
      "  if (lapsed) {",
      '    await end("the grant lapsed at " + new Date(lapsesAt).toISOString() + ", before a renewal ran");',
      "    return null;",
      "  }",
      "  try {",
      "    const given = args.pop();",
      "    const answer = await (await itx.connectToMcp(server, options))[method](...args, { ...given, claim: claim.scheduledAtOffset });",
      "    if (answer && answer.notRenewed) await end(words(answer.notRenewed));",
      "    else if (await held()) await itx.schedules.cancel(claim);",
      "    return answer;",
      "  } catch (failure) {",
      "    if (last) await end(words(failure));",
      "    throw failure;",
      "  }",
      "}",
    ].join("\n");
  return aTry(aTry(null));
}

/** A TASK ANSWER, HANDED TO THE SDK AS A RESULT IT TAKES. A server may answer a tool call with a
 *  task (`resultType: "task"`, SEP-2663). The SDK's client knows the kinds `complete` and
 *  `input_required` alone and refuses any other before its caller sees the answer ("Unsupported
 *  result type 'task'"; ./mcp-tasks.test.ts pins that). So this hands a task answer on as a
 *  complete tool result that carries the task in `_meta`, where `#call` reads it. `isError`
 *  keeps the SDK from holding the carrier against the tool's output schema. Remove it once the
 *  SDK hands an extension's kind of result to its caller (`acceptResultType`,
 *  https://github.com/modelcontextprotocol/typescript-sdk/pull/2820, in no release on 26 Nov
 *  2026). */
function carryTaskAnswers(transport: StreamableHTTPClientTransport) {
  const deliver = transport.onmessage;
  transport.onmessage = (message) => {
    const answer = TaskAnswer.safeParse(message);
    if (!answer.success) return deliver?.(message);
    const { resultType: _task, _meta, ...task } = answer.data.result;
    return deliver?.({
      ...message,
      result: {
        resultType: "complete",
        content: [],
        isError: true,
        _meta: { ..._meta, [MCP_TASK_META]: task },
      },
    });
  };
}

/** MCP Events' routing header (SEP-3415, "Streamable HTTP: Routing Headers"): a request that
 *  names an event carries the name in `Mcp-Name`, as a tool call carries its tool's. The SDK
 *  writes that header for the base protocol's methods alone and takes none from its caller, so
 *  it is written here, from the body that the SDK made. Only a request of revision 2026-07-28 has
 *  `Mcp-Method`, and only such a request gets the header. A name that is not plain ASCII goes as
 *  UTF-8 in base64, as the transport encodes a header's value. */
function eventNameHeaderOf(method: string | null, body: unknown) {
  if (!method?.startsWith("events/") || typeof body !== "string") return undefined;
  const named = NamesAnEvent.safeParse(JSON.parse(body));
  if (!named.success) return undefined;
  const { name } = named.data.params;
  return /^[\x21-\x7e](?:[\x20-\x7e]*[\x21-\x7e])?$/.test(name) && !name.startsWith("=?base64?")
    ? name
    : `=?base64?${bytesToBase64(new TextEncoder().encode(name))}?=`;
}

// An MCP server's answers are untrusted network data.

/** A task as a server states it (SEP-2663, "Tasks"), with what its status brings: a completed
 *  task's `result`, a failed one's `error`, and the `inputRequests` of one that asks for input.
 *  A status that the extension does not name is refused: the asking could not tell whether it
 *  is an end. So is a status without what it brings: an end with nothing in it would end the
 *  asking, and the context would never get the result. */
const Task = z
  .object({
    taskId: z.string().min(1),
    status: z.enum(["working", "input_required", "completed", "cancelled", "failed"]),
    statusMessage: z.string().optional(),
    createdAt: z.string().optional(),
    lastUpdatedAt: z.string().optional(),
    ttlMs: z.number().nullish(),
    pollIntervalMs: z.number().nonnegative().optional(),
    result: z.unknown().optional(),
    error: z.unknown().optional(),
    inputRequests: z.unknown().optional(),
  })
  .superRefine((task, context) => {
    const brings = (
      { completed: "result", failed: "error", input_required: "inputRequests" } as const
    )[task.status as "completed" | "failed" | "input_required"];
    if (brings && task[brings] == null)
      context.addIssue({
        code: "custom",
        message: `a task that is ${task.status} has no ${brings}`,
      });
  });
/** A JSON-RPC answer whose result is a task. */
const TaskAnswer = z.looseObject({
  result: z.looseObject({
    resultType: z.literal("task"),
    _meta: z.record(z.string(), z.unknown()).optional(),
  }),
});
/** What `followTask` takes: a task's id, the name the fact gives the task, when the asking began,
 *  the wait before this ask, and the claim of the schedule's own script (`#holds`). */
const TaskFollowed = z.object({
  taskId: z.string().min(1),
  tool: z.string().optional(),
  since: z.number().int().positive().optional(),
  waitMs: z.number().int().positive().optional(),
  claim: z.number().int().nonnegative().optional(),
});

const NamesAnEvent = z.object({ params: z.object({ name: z.string().min(1) }) });

/** A server's capabilities that declare MCP Events in the extension's own place. */
const EventsInExtensions = z.looseObject({
  extensions: z.looseObject({ "io.modelcontextprotocol/events": z.looseObject({}) }),
});
/** A server's capabilities that declare MCP Events as the design sketch did. */
const EventsInSketch = z.looseObject({ events: z.looseObject({}) });

const EventsPage = z.object({
  events: z.array(
    z.looseObject({
      name: z.string(),
      description: z.string().optional(),
      delivery: z.array(z.string()),
    }),
  ),
  nextCursor: z.string().optional(),
});

const EventsPolled = z.object({
  events: z.array(
    z.looseObject({
      eventId: z.string(),
      name: z.string(),
      timestamp: z.string(),
      data: z.unknown(),
    }),
  ),
  cursor: z.string().nullish(),
  truncated: z.boolean().optional(),
  hasMore: z.boolean().optional(),
  nextPollMs: z.number().optional(),
});

/** `refreshBefore` null: never lapses. A time that no clock reads is refused, since the renewal is
 *  set by it. */
const Subscription = z.object({
  id: z.string(),
  refreshBefore: z
    .string()
    .refine((time) => !Number.isNaN(Date.parse(time)), "refreshBefore is not a time")
    .nullable(),
  cursor: z.string().nullish(),
  truncated: z.boolean().optional(),
  deliveryStatus: z.record(z.string(), z.unknown()).optional(),
});