iterate.com / kernel

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

Merge iterate/private's core/ at 3a43222d

One kernel commit since 20e3895e: itx.connectToMcp speaks MCP Apps (d43677ff, #1423),
in core/lib's api and the mind worker's library/mcp.

No conflict, and nothing of the template came with it.

Checked on the merge: every package type-checks; 3,112 vitest tests and 85 node tests
pass; the userland repos type-check and their 244 tests pass against this SDK.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

Misha Kaletsky, 2026-11-26 09:52 UTC · 854506ccee4b7caa50c7823329cc6de6d7889fa0 · a merge of 093466a and 6b92e4b, shown against 093466a

4 files changed

M core/lib/src/api.ts
@@ -1104,9 +1104,34 @@
   serverInfo?: { name?: string; version?: string };
 };
 
-/** One tool as an MCP server's `tools/list` describes it. */
-export type McpTool = { name: string; description?: string; inputSchema?: unknown };
+/** One tool as an MCP server's `tools/list` describes it. `_meta.ui` is the MCP Apps extension's:
+ *  `resourceUri` (the tool's `ui://` view) and `visibility` (`"model"`, `"app"`). */
+export type McpTool = {
+  name: string;
+  title?: string;
+  description?: string;
+  inputSchema?: unknown;
+  _meta?: Record<string, unknown>;
+};
 
+/** A tool's whole result (MCP's `CallToolResult`): an `isError` result is a result, not a throw. */
+export type McpToolResult = {
+  content?: unknown[];
+  structuredContent?: unknown;
+  isError?: boolean;
+  _meta?: Record<string, unknown>;
+};
+
+/** One part of a resource that `resources/read` answers: text, or base64 in `blob`. An MCP App's
+ *  view is text of the type `text/html;profile=mcp-app`, its `_meta.ui` the view's `csp`. */
+export type McpResourceContents = {
+  uri: string;
+  mimeType?: string;
+  text?: string;
+  blob?: string;
+  _meta?: Record<string, unknown>;
+};
+
 /** One event an MCP server offers (the draft MCP Events extension's `events/list`): its name, the
  *  delivery modes it supports, the subscription arguments it takes and the payload it delivers. */
 export type McpEvent = {
@@ -1130,6 +1155,12 @@
   /** The result's `structuredContent`, else its text content JSON-parsed when it parses, else the
    *  text; an `isError` result throws with that text. */
   callTool(name: string, args?: Record<string, unknown>): Promise<unknown>;
+  /** The tool's whole result, `isError` included: what an MCP App's view is given. */
+  callToolResult(name: string, args?: Record<string, unknown>): Promise<McpToolResult>;
+  /** `resources/read`: the resource's parts, at most 8 million characters in all (an MCP App's
+   *  `ui://` view, say). The connection declares the MCP Apps extension, so a server offers its
+   *  views. */
+  readResource(uri: string): Promise<{ contents: McpResourceContents[] }>;
   /** The events the server offers. */
   listEvents(): Promise<McpEvent[]>;
   /** Subscribe this context to the event `name` with its arguments: the server POSTs each one to
M core/mind-worker/src/library.ts
@@ -73,7 +73,7 @@
   },
   connectToMcp: {
     description:
-      "a live MCP handle: `(await itx.connectToMcp(url)).listTools()`, one method per tool; `subscribe(event, args)` lands the server's events here as `events.iterate.com/mcp/webhook-received`",
+      "a live MCP handle: `(await itx.connectToMcp(url)).listTools()`, one method per tool; `callToolResult(name, args)` the whole result and `readResource(uri)` a `ui://` view (MCP Apps); `subscribe(event, args)` lands the server's events here as `events.iterate.com/mcp/webhook-received`",
     build: ({ itx, path, connections }) =>
       connections &&
       (((url, options) =>
A core/mind-worker/src/library/mcp.test.ts
@@ -0,0 +1,164 @@
+// The connection that `itx.connectToMcp` answers (mcp.ts), against a fake MCP App server served by
+// the SDK's own handler: the MCP Apps extension in `initialize`, a tool's `title` and `_meta`, a
+// tool's whole result, and `resources/read`.
+import { createMcpHandler, McpServer } from "@modelcontextprotocol/server";
+import { expect, test } from "vitest";
+import { z } from "zod";
+import type { LibraryItx } from "core-itx";
+import { connectToMcp, MCP_RESOURCE_MAX_CHARS } from "./mcp.ts";
+
+const VIEW = "ui://petshop/board.html";
+const HTML = "<!doctype html><html><body>the board</body></html>";
+
+test("the client declares the MCP Apps extension, and a tool keeps its title and _meta", async () => {
+  const { itx, sent } = itxOfFake();
+  const mcp = await connectToMcp(itx, "https://petshop.test/mcp", {}, noWebhook);
+  // 2026-07-28 says the client's capabilities in each request's `_meta`; older ones, in `initialize`
+  type Sent = {
+    method?: string;
+    params?: { capabilities?: unknown; _meta?: Record<string, unknown> };
+  };
+  const declared = (sent as Sent[]).map(
+    ({ method, params }) =>
+      (method === "initialize" ? params?.capabilities : undefined) ??
+      params?._meta?.["io.modelcontextprotocol/clientCapabilities"],
+  );
+  expect(declared.length).toBeGreaterThan(0);
+  for (const capabilities of declared)
+    expect(capabilities).toEqual({
+      extensions: { "io.modelcontextprotocol/ui": { mimeTypes: ["text/html;profile=mcp-app"] } },
+    });
+  expect(await mcp.listTools()).toContainEqual(
+    expect.objectContaining({
+      name: "show_board",
+      title: "Show the board",
+      _meta: { ui: { resourceUri: VIEW } },
+    }),
+  );
+  await mcp.close();
+});
+
+test("callToolResult answers the whole result, and an isError result does not throw", async () => {
+  const { itx } = itxOfFake();
+  const mcp = await connectToMcp(itx, "https://petshop.test/mcp", {}, noWebhook);
+  expect(await mcp.callToolResult("show_board", { id: "b1" })).toMatchObject({
+    content: [{ type: "text", text: "board b1" }],
+    structuredContent: { id: "b1", pets: 3 },
+  });
+  expect(await mcp.callToolResult("refuse")).toMatchObject({
+    content: [{ type: "text", text: "no pets today" }],
+    isError: true,
+  });
+  // callTool keeps its meaning: the structured content, and a throw on isError
+  expect(await mcp.callTool("show_board", { id: "b2" })).toEqual({ id: "b2", pets: 3 });
+  await expect(mcp.callTool("refuse")).rejects.toThrow("MCP tool refuse failed: no pets today");
+  await mcp.close();
+});
+
+test("readResource answers the view's document and its _meta, and refuses one past the bound", async () => {
+  const { itx } = itxOfFake();
+  const mcp = await connectToMcp(itx, "https://petshop.test/mcp", {}, noWebhook);
+  expect(await mcp.readResource(VIEW)).toEqual({
+    contents: [
+      {
+        uri: VIEW,
+        mimeType: "text/html;profile=mcp-app",
+        text: HTML,
+        _meta: { ui: { csp: { connectDomains: ["wss://petshop.iterate.com"] } } },
+      },
+    ],
+  });
+  await expect(mcp.readResource("ui://petshop/huge.html")).rejects.toThrow(
+    `has more than ${String(MCP_RESOURCE_MAX_CHARS)} characters`,
+  );
+  await mcp.close();
+});
+
+test("listTools follows nextCursor to the last page (the SDK does), and refuses a listing that never ends", async () => {
+  const pages = (count: number) => () => {
+    const server = new McpServer({ name: "paged", version: "1" });
+    server.registerTool("unused", {}, () => ({ content: [] }));
+    // the SDK's own listing is one page: this one answers `count` pages of two tools each
+    server.server.setRequestHandler("tools/list", (request) => {
+      const page = Number(request.params?.cursor || 0);
+      return {
+        tools: [0, 1].map((n) => ({
+          name: `tool_${String(page)}_${String(n)}`,
+          inputSchema: { type: "object" as const },
+        })),
+        ...(page + 1 < count && { nextCursor: String(page + 1) }),
+      };
+    });
+    return server;
+  };
+  const itxOf = (count: number) =>
+    ({ fetch: createMcpHandler(pages(count)).fetch }) as unknown as LibraryItx;
+  const three = await connectToMcp(itxOf(3), "https://paged.test/mcp", {}, noWebhook);
+  expect((await three.listTools()).map((tool) => tool.name)).toEqual([
+    "tool_0_0",
+    "tool_0_1",
+    "tool_1_0",
+    "tool_1_1",
+    "tool_2_0",
+    "tool_2_1",
+  ]);
+  await three.close();
+  // the connection lists its tools to name its methods: an endless listing fails at connect
+  await expect(connectToMcp(itxOf(1000), "https://paged.test/mcp", {}, noWebhook)).rejects.toThrow(
+    "exceeded listMaxPages (64)",
+  );
+});
+
+function petshop() {
+  const server = new McpServer({ name: "petshop", version: "1" });
+  server.registerTool(
+    "show_board",
+    {
+      title: "Show the board",
+      inputSchema: z.object({ id: z.string() }),
+      _meta: { ui: { resourceUri: VIEW } },
+    },
+    ({ id }) => ({
+      content: [{ type: "text", text: `board ${id}` }],
+      structuredContent: { id, pets: 3 },
+    }),
+  );
+  server.registerTool("refuse", { _meta: { ui: { visibility: ["app"] } } }, () => ({
+    content: [{ type: "text", text: "no pets today" }],
+    isError: true,
+  }));
+  server.registerResource(
+    "board",
+    VIEW,
+    { mimeType: "text/html;profile=mcp-app" },
+    async (uri) => ({
+      contents: [
+        {
+          uri: uri.href,
+          mimeType: "text/html;profile=mcp-app",
+          text: HTML,
+          _meta: { ui: { csp: { connectDomains: ["wss://petshop.iterate.com"] } } },
+        },
+      ],
+    }),
+  );
+  server.registerResource("huge", "ui://petshop/huge.html", {}, async (uri) => ({
+    contents: [{ uri: uri.href, text: "x".repeat(MCP_RESOURCE_MAX_CHARS + 1) }],
+  }));
+  return server;
+}
+
+/** A context's itx whose `fetch` reaches the fake server, and the bodies it was sent. */
+function itxOfFake() {
+  const handler = createMcpHandler(petshop);
+  const sent: unknown[] = [];
+  const itx = {
+    fetch: async (request: Request) => {
+      if (request.method === "POST") sent.push(await request.clone().json());
+      return await handler.fetch(request);
+    },
+  } as unknown as LibraryItx;
+  return { itx, sent };
+}
+
+const noWebhook = () => Promise.reject(new Error("no webhook in this test"));
M core/mind-worker/src/library/mcp.ts
@@ -10,6 +10,13 @@
 
 type McpLiveClient = { client: Client; transport: StreamableHTTPClientTransport };
 
+/** The MCP Apps extension (modelcontextprotocol/ext-apps, 2026-01-26): a client that declares it
+ *  may read a tool's `ui://` resource and draw it. A server may then offer its tools' views. */
+const MCP_APPS = { "io.modelcontextprotocol/ui": { mimeTypes: ["text/html;profile=mcp-app"] } };
+/** 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;
+
 /** A tool named like one of the connection's own members is reachable through `callTool` only. */
 export async function connectToMcp(
   itx: LibraryItx,
@@ -22,7 +29,12 @@
   const connect = async (): Promise<McpLiveClient> => {
     const client = new Client(
       { name: "iterate-context", version: "1" },
-      { versionNegotiation: { mode: "auto" } },
+      {
+        versionNegotiation: { mode: "auto" },
+        capabilities: {
+          extensions: MCP_APPS,
+        },
+      },
     );
     const transport = new StreamableHTTPClientTransport(new URL(url), {
       fetch: async (input, init) =>
@@ -86,16 +98,21 @@
   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 callTool(...[name, args]: Parameters<McpConnectionApi["callTool"]>) {
+  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 },
-    );
+    return await client.callTool({ name, arguments: args || {} }, { timeout: RUN_DEADLINE_MS });
+  }
+  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);
     const text = result.content
       .flatMap((part) => (part.type === "text" ? [part.text] : []))
       .join("\n");
@@ -107,6 +124,18 @@
     } catch {
       return text;
     }
+  }
+  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;
+    if (size > MCP_RESOURCE_MAX_CHARS)
+      throw new Error(
+        `MCP resource ${uri} has more than ${String(MCP_RESOURCE_MAX_CHARS)} characters`,
+      );
+    return { contents };
   }
   async listEvents() {
     const client = await this.#client();