Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Bot pages can call the connector tools they declare, with the person's own connection (#7678)
Milind Soni3529752e965e
diff --git a/packages/phone-protocol/src/app-rpc.ts b/packages/phone-protocol/src/app-rpc.tsindex e218992c23..4d5a530a95 100644--- a/packages/phone-protocol/src/app-rpc.ts+++ b/packages/phone-protocol/src/app-rpc.ts@@ -19,9 +19,20 @@ export type AppRpcMethod = (typeof APP_RPC_METHODS)[number];/** What a bot's page may ask its own server for, each only when the page declared it (show_html `uses`):* `mausbot/data/query` {sql, params?} → {columns, rows, truncated}; `mausbot/state/get` {key} → {value?};- * `mausbot/state/set` {key, value?} (no value removes the key) → {}; `mausbot/state/keys` {} → {keys}. */-export const PAGE_RPC_METHODS = ["mausbot/data/query", "mausbot/state/get", "mausbot/state/set", "mausbot/state/keys"] as const;+ * `mausbot/state/set` {key, value?} (no value removes the key) → {}; `mausbot/state/keys` {} → {keys};+ * `mausbot/connectors/call` {connector | server, tool, arguments?, engaged} → {result, truncated?} where `engaged` is the+ * host's own word on whether the person clicked in the page just now, never the page's;+ * `mausbot/connectors/list` {} → {connectors: [{connector | server, label, connected, tools}]}. */+export const PAGE_RPC_METHODS = [+ "mausbot/data/query", "mausbot/state/get", "mausbot/state/set", "mausbot/state/keys", "mausbot/connectors/call", "mausbot/connectors/list",+] as const;export type PageRpcMethod = (typeof PAGE_RPC_METHODS)[number];+/** What a page method needs the page to have declared. */+export type PageUse = "data" | "state" | "connectors";++export function pageMethodUse(method: PageRpcMethod): PageUse {+ return method === "mausbot/data/query" ? "data" : method.startsWith("mausbot/connectors/") ? "connectors" : "state";+}export const RPC_METHOD_NOT_FOUND = -32601;export const RPC_INVALID_PARAMS = -32602;diff --git a/packages/phone-protocol/src/app.ts b/packages/phone-protocol/src/app.tsindex b00d4b7bd6..7bc4f0d25e 100644--- a/packages/phone-protocol/src/app.ts+++ b/packages/phone-protocol/src/app.ts@@ -1,6 +1,7 @@// Chat apps: HTML in a sandboxed frame inside a chat row, speaking the MCP Apps bridge// (io.modelcontextprotocol/ui, SEP-1865). Bot HTML (show_html) and an MCP server's UI// (_meta.ui.resourceUri) share the one wire kind, `app`.+import { CONNECTOR_TOOL_NAME_PATTERN } from "./wire.ts";export const APP_MIME = "text/html;profile=mcp-app";export const APP_PROTOCOL_VERSION = "2026-01-26";@@ -40,6 +41,17 @@ export const APP_LIMITS = {pageStateValueBytes: 64 * 1024,pageStateBytes: 256 * 1024,pageStateKeys: 200,+ /** show_html `uses` connector tools: connected apps and MCP servers one page names, and tools in all. */+ pageConnectors: 8,+ pageConnectorTools: 24,+ /** mausbot.connectors.call: arguments' JSON bytes, the answer's JSON bytes before it is cut, its wall clock, a tool's+ * own error text, and calls per page and per bot and connector each minute. */+ pageConnectorArgsBytes: 64 * 1024,+ pageConnectorResultBytes: 512 * 1024,+ pageConnectorMs: 60_000,+ pageConnectorErrorChars: 1_000,+ pageConnectorCallsPerMinute: 30,+ connectorCallsPerMinute: 60,} as const;/** What a bot's page may ask the host for beyond the bridge's basics, declared with show_html `uses`: `data`, read-only@@ -47,6 +59,11 @@ export const APP_LIMITS = {export const APP_USES = ["data", "state"] as const;export type AppUse = (typeof APP_USES)[number];+/** Connector tools a bot's page declared it calls (show_html `uses`), each tool by its exact name: a connected app's by its+ * toolkit (`connector`, as "gmail:GMAIL_FETCH_EMAILS" in `uses`), or an MCP server's by the server's name (`server`, as+ * "mcp:notes:search"). Calls run with the viewing person's own connection and the bot's own grants. */+export type AppConnectorUse = { connector: string; tools: string[] } | { server: string; tools: string[] };+/** Versions of one bot page kept for stepping back, the current one included. */export const APP_PAGE_VERSIONS = 10;@@ -157,6 +174,8 @@ export interface AppCan {/** A bot's page that declared `data` or `state` (show_html `uses`), outside a room. */data?: boolean;state?: boolean;+ /** The connector tools the page declared, outside a room; whether each can run is decided when it is called. */+ connectors?: AppConnectorUse[];}export interface AppToolDefinition {@@ -216,6 +235,8 @@ export interface ShowHtmlInput {/** Reload the page in place whenever a file in its folder changes; only with `path`. */live?: boolean;uses?: AppUse[];+ /** Given exactly when `uses` is. */+ connectors?: AppConnectorUse[];}export interface UpdateHtmlInput {@@ -230,6 +251,8 @@ export interface UpdateHtmlInput {live?: boolean;/** Kept as the page's current version declared when omitted. */uses?: AppUse[];+ /** Given exactly when `uses` is. */+ connectors?: AppConnectorUse[];}export type AppInputResult<T> = { ok: true; value: T } | { ok: false; error: string };@@ -319,10 +342,74 @@ function checkLive(value: unknown, path: string | undefined): AppInputResult<booreturn { ok: true, value };}-const USES_HELP = 'uses: a list of "data" and "state", e.g. ["data", "state"].';+const USES_HELP = 'uses: a list of "data", "state" and connector tools by exact name: "gmail:GMAIL_FETCH_EMAILS" for a connected app, '+ + '"mcp:<server>:<tool>" for an MCP server; no wildcards. E.g. ["data", "gmail:GMAIL_FETCH_EMAILS"].';+const TOOLKIT_NAME = /^[a-z0-9_][a-z0-9_-]{0,63}$/;+const SERVER_NAME = /^[a-z][a-z0-9_-]{0,31}$/;+const SERVER_TOOL_NAME = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/;++type ConnectorEntry = { kind: "connector" | "server"; name: string; tool: string };+type DeclaredUses = { uses: AppUse[]; connectors: AppConnectorUse[] };++/** A connected app's own tool, by exact name: never Composio's own tools or its connection tools. */+function connectorToolProblem(toolkit: string, tool: string): string | null {+ if (!TOOLKIT_NAME.test(toolkit) || toolkit === "composio") return `uses: "${toolkit}" is not a connected app's name.`;+ if (!CONNECTOR_TOOL_NAME_PATTERN.test(tool) || !tool.startsWith(`${toolkit.toUpperCase()}_`)) {+ return `uses: "${tool}" is not one of ${toolkit}'s tools; name each tool exactly, e.g. "gmail:GMAIL_FETCH_EMAILS".`;+ }+ if (/_(?:MANAGE|WAIT_FOR)_CONNECTIONS$/.test(tool)) return `uses: a page cannot call ${tool}.`;+ return null;+}++function connectorEntries(item: unknown): AppInputResult<ConnectorEntry[]> {+ if (typeof item === "string") {+ const parts = item.trim().split(":").map((part) => part.trim());+ if (parts.length === 3 && parts[0]!.toLowerCase() === "mcp") return { ok: true, value: [{ kind: "server", name: parts[1]!.toLowerCase(), tool: parts[2]! }] };+ if (parts.length === 2) return { ok: true, value: [{ kind: "connector", name: parts[0]!.toLowerCase(), tool: parts[1]!.toUpperCase() }] };+ return { ok: false, error: USES_HELP };+ }+ if (!isRecord(item)) return { ok: false, error: USES_HELP };+ const server = typeof item.server === "string" ? item.server : undefined;+ const connector = [item.connector, item.app, item.toolkit].find((value): value is string => typeof value === "string");+ if ((server === undefined) === (connector === undefined)) return { ok: false, error: USES_HELP };+ const given = item.tools ?? item.tool;+ const tools = typeof given === "string" ? given.split(",") : Array.isArray(given) ? given : null;+ if (!tools?.length || tools.some((tool) => typeof tool !== "string")) return { ok: false, error: USES_HELP };+ return {+ ok: true,+ value: (tools as string[]).map((tool) => server !== undefined+ ? { kind: "server" as const, name: server.trim().toLowerCase(), tool: tool.trim() }+ : { kind: "connector" as const, name: connector!.trim().toLowerCase(), tool: tool.trim().toUpperCase() }),+ };+}++function groupConnectors(entries: ConnectorEntry[]): AppInputResult<AppConnectorUse[]> {+ const groups = new Map<string, AppConnectorUse>();+ let count = 0;+ for (const entry of entries) {+ if (entry.tool.includes("*")) return { ok: false, error: "uses: name each tool exactly; wildcards are not allowed." };+ if (entry.kind === "connector") {+ const problem = connectorToolProblem(entry.name, entry.tool);+ if (problem) return { ok: false, error: problem };+ } else if (!SERVER_NAME.test(entry.name) || !SERVER_TOOL_NAME.test(entry.tool)) {+ return { ok: false, error: `uses: "mcp:${entry.name}:${entry.tool}" does not name an MCP server and one of its tools.` };+ }+ const key = `${entry.kind}\u0000${entry.name}`;+ const group = groups.get(key) ?? (entry.kind === "connector" ? { connector: entry.name, tools: [] } : { server: entry.name, tools: [] });+ groups.set(key, group);+ if (group.tools.includes(entry.tool)) continue;+ group.tools.push(entry.tool);+ count += 1;+ }+ if (groups.size > APP_LIMITS.pageConnectors || count > APP_LIMITS.pageConnectorTools) {+ return { ok: false, error: `uses: at most ${APP_LIMITS.pageConnectors} connected apps or servers and ${APP_LIMITS.pageConnectorTools} tools in all.` };+ }+ return { ok: true, value: [...groups.values()] };+}-/** A list of names; a string holding one name, several separated by commas, or a JSON list is read as that list. */-function checkUses(value: unknown): AppInputResult<AppUse[] | undefined> {+/** A list of names; a string holding one name, several separated by commas, or a JSON list is read as that list. An entry+ * may also be an object, {connector, tools} or {server, tools}. */+function checkUses(value: unknown): AppInputResult<DeclaredUses | undefined> {if (value === undefined || value === null) return { ok: true, value: undefined };let list: unknown = value;if (typeof list === "string") {@@ -331,12 +418,24 @@ function checkUses(value: unknown): AppInputResult<AppUse[] | undefined> {}if (!Array.isArray(list)) return { ok: false, error: USES_HELP };const uses: AppUse[] = [];+ const entries: ConnectorEntry[] = [];for (const item of list) {const name = typeof item === "string" ? item.trim().toLowerCase() : "";- if (!(APP_USES as readonly string[]).includes(name)) return { ok: false, error: USES_HELP };- if (!uses.includes(name as AppUse)) uses.push(name as AppUse);+ if ((APP_USES as readonly string[]).includes(name)) {+ if (!uses.includes(name as AppUse)) uses.push(name as AppUse);+ continue;+ }+ const found = connectorEntries(item);+ if (!found.ok) return found;+ entries.push(...found.value);}- return { ok: true, value: uses };+ const connectors = groupConnectors(entries);+ return connectors.ok ? { ok: true, value: { uses, connectors: connectors.value } } : connectors;+}++/** `uses` as one list of strings, the form checkUses reads back. */+export function appUsesList(uses: readonly AppUse[], connectors: readonly AppConnectorUse[] = []): string[] {+ return [...uses, ...connectors.flatMap((group) => group.tools.map((tool) => ("server" in group ? `mcp:${group.server}:${tool}` : `${group.connector}:${tool}`)))];}export function parseShowHtmlInput(input: unknown): AppInputResult<ShowHtmlInput> {@@ -354,7 +453,10 @@ export function parseShowHtmlInput(input: unknown): AppInputResult<ShowHtmlInputif (live.value) out.live = true;const uses = checkUses(input.uses);if (!uses.ok) return uses;- if (uses.value?.length) out.uses = uses.value;+ if (uses.value?.uses.length || uses.value?.connectors.length) {+ out.uses = uses.value.uses;+ out.connectors = uses.value.connectors;+ }if (input.height !== undefined && input.height !== null) {if (typeof input.height !== "number" || !Number.isFinite(input.height)) return { ok: false, error: "height: must be a number of pixels, 80 to 720." };out.height = Math.round(Math.min(APP_LIMITS.heightMax, Math.max(APP_LIMITS.heightMin, input.height)));@@ -384,7 +486,10 @@ export function parseUpdateHtmlInput(input: unknown): AppInputResult<UpdateHtmlIif (live.value !== undefined) out.live = live.value;const uses = checkUses(input.uses);if (!uses.ok) return uses;- if (uses.value !== undefined) out.uses = uses.value;+ if (uses.value !== undefined) {+ out.uses = uses.value.uses;+ out.connectors = uses.value.connectors;+ }if (input.title !== undefined && input.title !== null) {const title = checkTitle(input.title);if (!title.ok) return title;diff --git a/server/app-docs.ts b/server/app-docs.tsindex c1c1c14517..73e8a30e8c 100644--- a/server/app-docs.ts+++ b/server/app-docs.ts@@ -5,7 +5,7 @@ import { createHash, randomBytes } from "node:crypto";import { mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";import { join } from "node:path";-import type { AppNetwork, AppSource, AppToolDefinition, AppToolResult, AppUse } from "../shared/app.ts";+import type { AppConnectorUse, AppNetwork, AppSource, AppToolDefinition, AppToolResult, AppUse } from "../shared/app.ts";import type { PageVideo } from "./pages/bundle.ts";export const APP_DOCS_MAX_BYTES = 512 * 1024 * 1024;@@ -26,6 +26,8 @@ export interface AppDocData {videos?: Record<string, PageVideo>;/** What a bot's page declared it uses (show_html `uses`). */uses?: AppUse[];+ /** The connector tools a bot's page declared it calls (show_html `uses`). */+ connectors?: AppConnectorUse[];tool?: AppToolDefinition;toolInput?: Record<string, unknown>;toolResult?: AppToolResult;diff --git a/server/chat-apps-mcp.test.ts b/server/chat-apps-mcp.test.tsindex e0c18146cd..1fe0829cb9 100644--- a/server/chat-apps-mcp.test.ts+++ b/server/chat-apps-mcp.test.ts@@ -8,6 +8,7 @@ import { APP_LIMITS, APP_MIME, type AppPayload } from "../shared/app.ts";import { createChatApps, type ChatApps } from "./chat-apps.ts";import { APP_WRITE_DECLINED, createChatAppsMcp, type ChatAppsMcp, type ChatAppsMcpOAuth, type ChatAppsMcpStore } from "./chat-apps-mcp.ts";import { createAgentCard } from "./chat-widgets.ts";+import { createConnectorGate, type ConnectorCaller } from "./connector-gate.ts";import type { McpServerSpec } from "./contracts.ts";import { McpOAuthManager, withMcpSignIn } from "./mcp-oauth.ts";import { probeMcpServer, SIGN_IN_CHECK_TOOL } from "./mcp-probe.ts";@@ -479,3 +480,38 @@ describe("a server that lists tools before anyone signs in", () => {expect(oauth.authState("open", fake.url)).toBe("none");});});++describe("a bot page's call to one of its bot's MCP servers, through the connector gate", () => {+ const gateFor = (mcp: ChatAppsMcp, bot: BotRecord, full = false) => {+ const gate = createConnectorGate({ bot: (id) => (id === bot.id ? bot : undefined), servers: { open: mcp.openServer }, decide: () => {}, log: () => {} });+ const caller = (engaged = false): ConnectorCaller => ({+ botId: bot.id, person: null, declared: [{ server: "board", tools: ["show_board", "paint_board", "save_board", "peek_board"] }],+ fullAccess: () => full, engaged, audit: { label: "page m1", key: `${THREAD}:m1`, threadId: THREAD },+ });+ return { gate, caller };+ };++ it("reads with a tool its own listing marks read-only, and changes only at Full access after a click", async () => {+ const { mcp, bot } = setup();+ const { gate, caller } = gateFor(mcp, bot);+ expect(await gate.call(caller(), { server: "board", tool: "show_board" }, { cards: 5 })).toEqual({ ok: true, result: { cards: 5 } });+ expect(await gate.call(caller(), { server: "board", tool: "peek_board" }, {})).toEqual({ ok: true, result: "3 cards" });+ expect(await gate.call(caller(true), { server: "board", tool: "paint_board" }, { color: "red" })).toMatchObject({ ok: false, reason: "needs-access" });+ const full = gateFor(mcp, bot, true);+ expect(await full.gate.call(full.caller(false), { server: "board", tool: "paint_board" }, { color: "red" })).toMatchObject({ ok: false, reason: "needs-click" });+ expect(await full.gate.call(full.caller(true), { server: "board", tool: "paint_board" }, { color: "red" })).toEqual({ ok: true, result: "Painted red" });+ // A tool only the server's own app may call is not one of the bot's.+ expect(await full.gate.call(full.caller(true), { server: "board", tool: "save_board" }, {})).toMatchObject({ ok: false, reason: "not-granted" });+ expect(await gate.list(caller())).toEqual([{ server: "board", label: "board", connected: true, tools: ["show_board", "paint_board", "save_board", "peek_board"] }]);+ }, 30_000);++ it("refuses a server the bot's selection leaves out, one switched off, and one waiting for a sign-in", async () => {+ const scoped = setup({ scope: { allow: ["mcp:other:*"] } });+ expect(await gateFor(scoped.mcp, scoped.bot).gate.call(gateFor(scoped.mcp, scoped.bot).caller(), { server: "board", tool: "show_board" }, {})).toMatchObject({ ok: false, reason: "not-granted" });+ const off = setup({ servers: { board: { ...board(), enabled: false } } });+ expect(await gateFor(off.mcp, off.bot).gate.call(gateFor(off.mcp, off.bot).caller(), { server: "board", tool: "show_board" }, {})).toMatchObject({ ok: false, reason: "not-connected" });+ const signedOut = setup({ servers: { board: { url: "https://mcp.example/board", enabled: true } }, needsSignIn: ["board"] });+ expect(await gateFor(signedOut.mcp, signedOut.bot).gate.call(gateFor(signedOut.mcp, signedOut.bot).caller(), { server: "board", tool: "show_board" }, {}))+ .toEqual({ ok: false, reason: "not-connected", status: 409, message: "Connect board in Settings first." });+ });+});diff --git a/server/chat-apps-mcp.ts b/server/chat-apps-mcp.tsindex aaf548ae17..776bf70f61 100644--- a/server/chat-apps-mcp.ts+++ b/server/chat-apps-mcp.ts@@ -18,6 +18,7 @@ import { lenientToolValidator, schemaProblems } from "./mcp-schema-validator.ts"import { redactSecretsInText } from "./redact.ts";import type { McpRpcAnswer, McpRpcRequest } from "./routes/chat-apps.ts";import type { BotRecord, Message, Store } from "./store.ts";+import type { GateServers } from "./connector-gate.ts";export const APP_RESOURCE_CACHE_MS = 10 * 60_000;const STARTUP_PROBE_DELAY_MS = 20_000;@@ -75,6 +76,9 @@ export interface ChatAppsMcp {turnMounts(custom: Record<string, McpServerSpec>, toolScope?: unknown): { mcpApps?: Record<string, { extension: boolean }> };hasApps(name: string): boolean | undefined;probeOptions(name: string, server: StoredMcpServer): McpProbeOptions;+ /** One of the bot's MCP servers for a call made outside a turn, through the same connection an app's own calls use. A+ * server each person connects for themselves is not reached this way. */+ openServer: GateServers["open"];serverChanged(name: string): void;forgetServer(name: string): void;close(): void;@@ -117,6 +121,12 @@ function redactedDone(done: AppDoneState): AppDoneState {const rpcError = (status: number, code: number, message: string, extra: Json = {}): McpRpcAnswer => ({ status, body: { error: { code, message }, ...extra } });+/** Whether the bot, in this conversation, runs a change without asking: what an app's change outside a turn follows. */+export function botApproval(store: Pick<Store, "projectBotForTask">, botId: string, threadId: string): "full" | "confirm" {+ const task = store.projectBotForTask(botId, threadId);+ return task && approvalModeFor({ ...task, threadId }) === "full" ? "full" : "confirm";+}+export function createChatAppsMcp(deps: ChatAppsMcpDeps): ChatAppsMcp {const { store, apps } = deps;const now = deps.now ?? Date.now;@@ -270,10 +280,7 @@ export function createChatAppsMcp(deps: ChatAppsMcpDeps): ChatAppsMcp {return { can: { ...CLOSED }, blocked: { reason, text: appBlockedText(reason, ref?.serverTitle ?? ref?.server) } };}- const approvalOf = (botId: string, threadId: string): "full" | "confirm" => {- const task = store.projectBotForTask(botId, threadId);- return task && approvalModeFor({ ...task, threadId }) === "full" ? "full" : "confirm";- };+ const approvalOf = (botId: string, threadId: string) => botApproval(store, botId, threadId);/** Nothing configured and nothing secret-shaped reaches the view. */const serverErrorText = (detail: string, server: McpServerSpec): string => {@@ -338,6 +345,37 @@ export function createChatAppsMcp(deps: ChatAppsMcpDeps): ChatAppsMcp {return { status: 200, body };}+ const openServer: GateServers["open"] = async (bot, _person, name) => {+ const stored = storedServer(name, deps.storedServers()[name]);+ const label = name;+ if (!stored) return { ok: false, reason: "not-granted", label };+ if (deps.personMcp?.().includes(name) || !stored.enabled) return { ok: false, reason: "not-connected", label };+ if (isRemoteMcpServer(stored) && deps.oauth.authState(name, stored.url) === "needs-sign-in") return { ok: false, reason: "not-connected", label };+ const full = store.bot(bot.id);+ const mounted = full ? deps.mountedServers(full) : {};+ if (!full || !Object.hasOwn(mounted, name) || !canUseMcpServer(full.toolScope, name)) return { ok: false, reason: "not-granted", label };+ const server = await signedIn(name, mounted[name]!);+ if (!server) return { ok: false, reason: "not-connected", label };+ const extension = extensionFor(name, server);+ return {+ ok: true,+ server: {+ label,+ tools: (signal) => connections.tools(name, server, signal, extension),+ async call(tool, args, signal) {+ try {+ const result = await connections.request(name, server, "tools/call", { name: tool, arguments: args }, signal, extension);+ return { ok: true, body: isRecord(result) ? result : { content: [] } };+ } catch (error) {+ if (error instanceof McpRpcError) return { ok: false, text: serverErrorText(error.detail, server) };+ if (error instanceof McpHttpError && error.status === 401) return { ok: false, text: `Sign in to ${name} again.` };+ throw error;+ }+ },+ },+ };+ };+async function rpc(request: McpRpcRequest): Promise<McpRpcAnswer> {const { bot, threadId, row, method, params } = request;const ref = row.app.mcp;@@ -440,7 +478,7 @@ export function createChatAppsMcp(deps: ChatAppsMcpDeps): ChatAppsMcp {startup?.unref?.();const service: ChatAppsMcp = {- catalog, connections, recordMcpAppCall, access, rpc, turnMounts, probeOptions, serverChanged,+ catalog, connections, recordMcpAppCall, access, rpc, turnMounts, probeOptions, serverChanged, openServer,hasApps(name) {const raw = deps.storedServers()[name];return raw && typeof raw === "object" ? catalog.get(name, raw as Record<string, unknown>)?.apps : undefined;diff --git a/server/chat-apps.ts b/server/chat-apps.tsindex c0e7c9a29e..19b73ab241 100644--- a/server/chat-apps.ts+++ b/server/chat-apps.ts@@ -2,7 +2,7 @@ import type { IncomingMessage, ServerResponse } from "node:http";import {APP_LIMITS, APP_PAGE_VERSIONS, appBlockedText, htmlFallbackText, oneLine, parseShowHtmlInput, parseUpdateHtmlInput, utf8Bytes,- type AppCan, type AppDocument, type AppPayload, type AppUse,+ type AppCan, type AppConnectorUse, type AppDocument, type AppPayload, type AppUse,} from "../shared/app.ts";import { BOT_HTML_NETWORK } from "../shared/app-frame/csp.ts";import { botHtmlDocument, mcpAppDocument, publishedBotHtml, ROOM_CAN } from "../shared/app-frame/document.ts";@@ -49,7 +49,8 @@ function scrubbed(html: string, title: string): { html: string; title: string; m}/** A folder page also carries the files beside its index.html and where they were read. */-type PageText = { html: string; format?: "jsx"; files?: PageFile[]; folder?: string; videos?: AppDocData["videos"]; uses?: AppUse[] };+type PageText = { html: string; format?: "jsx"; files?: PageFile[]; folder?: string; videos?: AppDocData["videos"]; uses?: AppUse[];+ connectors?: AppConnectorUse[] };type MadePage = { ok: true; page: PageText; title: string; masked: boolean; leftOut?: string };/** The page's text, scrubbed; a jsx page is transpiled first, so one that cannot run is refused with where. */@@ -90,7 +91,7 @@ async function folderPage(path: string, title: string, folders: BotFolders): Profunction storePage(docs: AppDocs, page: PageText): AppDocPut {const data = { ...(page.format ? { format: page.format } : {}), ...(page.folder ? { folder: page.folder } : {}), ...(page.videos ? { videos: page.videos } : {}),- ...(page.uses?.length ? { uses: page.uses } : {}) };+ ...(page.uses?.length ? { uses: page.uses } : {}), ...(page.connectors?.length ? { connectors: page.connectors } : {}) };return docs.put({ source: "html", html: page.html, ...(Object.keys(data).length ? { data } : {}), ...(page.files ? { files: page.files } : {}) });}@@ -130,11 +131,11 @@ export function createAppCard(args: {function placePage(args: { store: AgentCardStore; docs: AppDocs; bot: { id: string; name: string; color: MausColor }; threadId: string; authored?(messageId: string): void },- value: { appId?: string; height?: number; fallbackText?: string; frameless?: boolean; live?: boolean; uses?: AppUse[] },+ value: { appId?: string; height?: number; fallbackText?: string; frameless?: boolean; live?: boolean; uses?: AppUse[]; connectors?: AppConnectorUse[] },given: MadePage,): AgentCardResult {const { store, docs, bot, threadId } = args;- const made = value.uses === undefined ? given : { ...given, page: { ...given.page, uses: value.uses } };+ const made = value.uses === undefined ? given : { ...given, page: { ...given.page, uses: value.uses, connectors: value.connectors ?? [] } };const { page } = made;if (value.appId === undefined) {const stored = storePage(docs, page);@@ -167,7 +168,8 @@ function replacePage(options: { frameless?: boolean; live?: boolean } = {},): Message | null {// A version that says nothing about `uses` (a live folder's reload, a replacement without it) keeps what the page declared.- const page = made.page.uses !== undefined ? made.page : { ...made.page, uses: docs.read(existing.app.doc)?.data?.uses };+ const before = made.page.uses !== undefined ? undefined : docs.read(existing.app.doc)?.data;+ const page = before === undefined ? made.page : { ...made.page, uses: before?.uses, connectors: before?.connectors };const stored = storePage(docs, page);const border = options.frameless === undefined ? existing.app.border : !options.frameless;// Only a page from a folder can stay live; a page sent as html or jsx stops being live.@@ -236,7 +238,7 @@ export function appDocument(args: {? `${args.files.origin}${args.files.folder({ threadId: args.threadId, messageId: row.id, doc: version.doc })}` : undefined;return botHtmlDocument({ messageId: row.id, rev, html: stored.html, title: row.app.title,...(stored.data?.format === "jsx" ? { format: "jsx" as const } : {}), ...(files ? { files } : {}), ...(room ? { room } : {}),- ...(stored.data?.uses?.length ? { uses: stored.data.uses } : {}) });+ ...(stored.data?.uses?.length ? { uses: stored.data.uses } : {}), ...(stored.data?.connectors?.length ? { connectors: stored.data.connectors } : {}) });}if (!stored.data?.tool) return null;const access: ReturnType<McpAppAccess> = room ? { can: ROOM_CAN } : (args.mcpAccess ?? MCP_READ_ONLY)(row, args.threadId);@@ -463,6 +465,8 @@ export interface ChatApps {readonly states: AppStates;/** What the current version of a bot's page declared it uses; none for an MCP app or a missing row. */declaredUses(threadId: string, messageId: string): AppUse[];+ /** The connector tools the current version of a bot's page declared; none for an MCP app or a missing row. */+ declaredConnectors(threadId: string, messageId: string): AppConnectorUse[];/** True while the workspace is being backed up or restored: a page's state waits. */paused(): boolean;createAppCard(args: {@@ -624,6 +628,10 @@ export function createChatApps(deps: {const row = appRow(deps.store, threadId, messageId);return row?.app.source === "html" && row.app.doc ? docs.read(row.app.doc)?.data?.uses ?? [] : [];},+ declaredConnectors: (threadId, messageId) => {+ const row = appRow(deps.store, threadId, messageId);+ return row?.app.source === "html" && row.app.doc ? docs.read(row.app.doc)?.data?.connectors ?? [] : [];+ },paused: () => deps.paused?.() ?? false,createAppCard: (args) => {const result = createAppCard({ ...args, store: deps.store, docs });diff --git a/server/composio.test.ts b/server/composio.test.tsindex ebbc747977..95af6b8d8d 100644--- a/server/composio.test.ts+++ b/server/composio.test.ts@@ -72,7 +72,7 @@ let emptyConnectedAccounts = false;let connectedAccountsOverride: Array<{ id: string; alias?: string; status?: string; toolkit: { slug: string } }> | null = null;// The grant editor's tools/list fixture: null keeps the legacy one-frame// {source:"broker"} answer the relayMcp tests assert on.-let brokerMcpTools: Array<{ name: string; description?: string }> | null = null;+let brokerMcpTools: Array<{ name: string; description?: string; annotations?: Record<string, unknown> }> | null = null;let brokerToolsListFail = false;// What /broker/v1/connectors/connected serves; null falls back to github// only, the state the existing validation tests were written against.@@ -1549,6 +1549,26 @@ describe("connector tool inventory", () => {}});+ it("marks a tool read-only only when its own listing says it reads and does not destroy", async () => {+ setManagedBrokerAccess({ url: origin + "/broker", token: "f".repeat(64) });+ brokerConnectedServicesBody = { services: { gmail: { connected: true, status: "ACTIVE" } } };+ brokerMcpTools = [+ { name: "GMAIL_SEND_EMAIL", annotations: { readOnlyHint: true } },+ { name: "GMAIL_FETCH_EMAILS" },+ { name: "GMAIL_LIST_LABELS", annotations: { readOnlyHint: true, destructiveHint: true } },+ { name: "GMAIL_GET_PROFILE", annotations: { readOnlyHint: "yes" } },+ ];+ try {+ await expect(listConnectorTools({})).resolves.toEqual({ gmail: [+ { name: "GMAIL_FETCH_EMAILS" }, { name: "GMAIL_GET_PROFILE" }, { name: "GMAIL_LIST_LABELS" }, { name: "GMAIL_SEND_EMAIL", readOnly: true },+ ] });+ } finally {+ brokerMcpTools = null;+ brokerConnectedServicesBody = null;+ setManagedBrokerAccess(null);+ }+ });+it("re-walks after a backend switch instead of serving the cached inventory", async () => {setManagedBrokerAccess({ url: origin + "/broker", token: "d".repeat(64) });brokerMcpTools = [{ name: "GITHUB_CREATE_ISSUE" }];diff --git a/server/composio.ts b/server/composio.tsindex 4b4310f50f..2ec3ffa596 100644--- a/server/composio.ts+++ b/server/composio.ts@@ -515,6 +515,8 @@ export async function validateConnectorGrants(export interface ConnectorToolListing {name: string;description?: string;+ /** The tool's own listing says it only reads: annotations.readOnlyHint, and not destructiveHint. */+ readOnly?: true;}/** The picker offers exactly what a granted bot's bridge would see. */@@ -618,7 +620,10 @@ function connectorToolListing(tool: unknown): ConnectorToolListing | null {const trimmed = typeof description === "string"? description.replace(/\s+/g, " ").trim().slice(0, TOOL_DESCRIPTION_MAX): "";- return trimmed ? { name, description: trimmed } : { name };+ const annotations = (tool as { annotations?: unknown }).annotations;+ const hints = annotations && typeof annotations === "object" && !Array.isArray(annotations) ? annotations as { readOnlyHint?: unknown; destructiveHint?: unknown } : {};+ const readOnly = hints.readOnlyHint === true && hints.destructiveHint !== true ? { readOnly: true as const } : {};+ return { name, ...(trimmed ? { description: trimmed } : {}), ...readOnly };}async function collectConnectorTools(cfg: AppConfig): Promise<Record<string, ConnectorToolListing[]>> {diff --git a/server/connector-gate.test.ts b/server/connector-gate.test.tsnew file mode 100644index 0000000000..995a490940--- /dev/null+++ b/server/connector-gate.test.ts@@ -0,0 +1,295 @@+// The gate a connector call made outside a turn goes through, with a fake connected-apps installation and a fake MCP+// server: no call leaves this process.+import { describe, expect, it } from "vitest";++import { APP_LIMITS, type AppConnectorUse } from "../shared/app.ts";+import { bindConnectorGate, createConnectorGate, fitResult, type AppInstallation, type ConnectorCaller, type GateBot, type GateServers, type OpenedServer } from "./connector-gate.ts";+import type { DecisionRow } from "./decision-log.ts";++type Json = Record<string, unknown>;++/** Composio's multi-execute answer for one tool. */+function executed(slug: string, data: unknown, successful = true, error?: string): Json {+ const body = { successful: true, data: { results: [{ tool_slug: slug, response: { successful, ...(successful ? { data } : { error }) } }] } };+ return { content: [{ type: "text", text: JSON.stringify(body) }] };+}++function installation(id: string, options: { connected?: boolean; accounts?: Array<{ id: string; status: string }>; readOnly?: string[]; answer?: (frame: Json) => Json | Promise<Json>; hang?: boolean; status?: number } = {}) {+ const frames: Array<{ frame: Json; session: string | undefined }> = [];+ const value: AppInstallation = {+ id,+ connected: async () => ({ gmail: { connected: options.connected !== false, accounts: options.accounts ?? [{ id: "ca_1", status: "ACTIVE" }] } }),+ serviceSlugs: async () => ["gmail", "notion"],+ readOnlyTools: async () => new Set(options.readOnly ?? ["GMAIL_FETCH_EMAILS"]),+ async relay(frame, session, signal) {+ frames.push({ frame, session });+ if (frame.method === "initialize") return { status: 200, bytes: new TextEncoder().encode(JSON.stringify({ jsonrpc: "2.0", id: frame.id, result: {} })), transportSessionId: `${id}-session` };+ if (frame.method !== "tools/call") return { status: 202, bytes: new Uint8Array() };+ if (options.hang) await new Promise((_, reject) => signal.addEventListener("abort", () => reject(signal.reason), { once: true }));+ if (options.status) return { status: options.status, bytes: new Uint8Array() };+ const params = frame.params as { arguments: { tools: Array<{ tool_slug: string }> } };+ const result = options.answer ? await options.answer(frame) : executed(params.arguments.tools[0]!.tool_slug, { messages: [{ id: "m1", subject: "Hi" }] });+ return { status: 200, bytes: new TextEncoder().encode(JSON.stringify({ jsonrpc: "2.0", id: frame.id, result })) };+ },+ };+ return { value, frames, calls: () => frames.filter((one) => one.frame.method === "tools/call").map((one) => one.frame) };+}++function fakeServer(tools: Json[], answer: (tool: string, args: Json) => Json = (tool) => ({ content: [{ type: "text", text: `ran ${tool}` }] })) {+ const calls: Array<{ tool: string; args: Json }> = [];+ const server: OpenedServer = {+ label: "notes",+ tools: async () => tools,+ async call(tool, args) { calls.push({ tool, args }); return { ok: true, body: answer(tool, args) }; },+ };+ return { server, calls };+}++function fixture(options: { bot?: Partial<GateBot>; shared?: ReturnType<typeof installation>; own?: ReturnType<typeof installation> | null; personApps?: string[]; policy?: string; servers?: GateServers; callMs?: number } = {}) {+ const bot: GateBot = { id: "b1", name: "Scout", ...options.bot };+ const bots = new Map([[bot.id, bot]]);+ const rows: Array<Omit<DecisionRow, "at">> = [];+ const lines: string[] = [];+ const shared = options.shared ?? installation("shared");+ const asked: Array<{ person: string | null; toolkit: string }> = [];+ const gate = createConnectorGate({+ bot: (id) => bots.get(id),+ apps: {+ configured: () => true,+ installation: (person, toolkit) => {+ asked.push({ person, toolkit });+ if (!(options.personApps ?? []).includes(toolkit)) return shared.value;+ return person && options.own ? options.own.value : null;+ },+ policyRefusal: () => options.policy,+ },+ ...(options.servers ? { servers: options.servers } : {}),+ decide: (row) => rows.push(row),+ log: (line) => lines.push(line),+ ...(options.callMs ? { callMs: options.callMs } : {}),+ });+ return { gate, bot, bots, rows, lines, shared, asked };+}++const GMAIL: AppConnectorUse = { connector: "gmail", tools: ["GMAIL_FETCH_EMAILS", "GMAIL_ADD_LABEL_TO_EMAIL", "GMAIL_SEND_EMAIL", "GMAIL_TRASH_MESSAGE"] };+let pages = 0;+function caller(over: Partial<ConnectorCaller> = {}): ConnectorCaller {+ pages += 1;+ return {+ botId: "b1", person: null, declared: [GMAIL], fullAccess: () => true, engaged: false,+ audit: { label: `page p${pages}`, key: `t1:p${pages}`, threadId: "t1" }, ...over,+ };+}++describe("a connected app's tool, called outside a turn", () => {+ it("runs a declared read with the account the server chooses, and answers with the tool's data alone", async () => {+ const shared = installation("shared", { accounts: [{ id: "ca_new", status: "ACTIVE" }, { id: "ca_old", status: "ACTIVE" }] });+ const { gate } = fixture({ shared });+ const answer = await gate.call(caller(), { connector: "gmail", tool: "GMAIL_FETCH_EMAILS" }, { max_results: 3, account: "ca_someone_else" });+ expect(answer).toEqual({ ok: true, result: { messages: [{ id: "m1", subject: "Hi" }] } });+ // Exactly the declared tool, with the page's arguments as the tool's own, and the account the server picked.+ expect(shared.calls()).toEqual([{+ jsonrpc: "2.0", id: expect.any(Number), method: "tools/call",+ params: { name: "COMPOSIO_MULTI_EXECUTE_TOOL", arguments: { tools: [{ tool_slug: "GMAIL_FETCH_EMAILS", arguments: { max_results: 3, account: "ca_someone_else" }, account: "ca_new" }] } },+ }]);+ expect(shared.frames[0]!.frame.method).toBe("initialize");+ expect(shared.frames.at(-1)!.session).toBe("shared-session");+ });++ it("uses an account the bot is limited to, and the calling person's own installation where each person connects the app", async () => {+ const own = installation("person:ada", { accounts: [{ id: "ca_a", status: "ACTIVE" }, { id: "ca_b", status: "ACTIVE" }] });+ const { gate, shared, asked } = fixture({ own, personApps: ["gmail"], bot: { connectorScopes: { apps: { gmail: "write" }, accounts: { gmail: ["ca_b"] } } as GateBot["connectorScopes"] } });+ expect((await gate.call(caller({ person: "ada" }), { connector: "gmail", tool: "GMAIL_FETCH_EMAILS" }, {})).ok).toBe(true);+ expect(asked).toEqual([{ person: "ada", toolkit: "gmail" }]);+ expect(own.calls()[0]).toMatchObject({ params: { arguments: { tools: [{ account: "ca_b" }] } } });+ expect(shared.frames).toEqual([]);+ const nobody = await gate.call(caller({ person: null }), { connector: "gmail", tool: "GMAIL_FETCH_EMAILS" }, {});+ expect(nobody).toEqual({ ok: false, reason: "not-connected", status: 409, message: "Connect Gmail in Apps first." });+ });++ it("refuses in order: not declared, not granted, not connected, the access level, then a missing click", async () => {+ const tool = { connector: "gmail", tool: "GMAIL_ADD_LABEL_TO_EMAIL" };+ const undeclared = fixture();+ expect(await undeclared.gate.call(caller({ declared: [] }), tool, {})).toMatchObject({ ok: false, reason: "not-declared", message: 'This page did not declare GMAIL_ADD_LABEL_TO_EMAIL: list "gmail:GMAIL_ADD_LABEL_TO_EMAIL" in show_html uses to call it.' });++ const ungranted = fixture({ bot: { connectorTools: { gmail: { tools: ["GMAIL_FETCH_EMAILS"] } } } });+ expect(await ungranted.gate.call(caller(), tool, {})).toMatchObject({ ok: false, reason: "not-granted", message: "Scout is not allowed GMAIL_ADD_LABEL_TO_EMAIL in Gmail. The person can allow it in Scout's Apps settings." });+ const appsOff = fixture({ bot: { composio: false } });+ expect(await appsOff.gate.call(caller(), tool, {})).toMatchObject({ ok: false, reason: "not-granted", message: "Scout cannot use connected apps." });+ const readScope = fixture({ bot: { connectorScopes: { apps: { gmail: "read" } } } });+ expect(await readScope.gate.call(caller({ engaged: true }), tool, {})).toMatchObject({ ok: false, reason: "not-granted" });+ const policy = fixture({ policy: "Acme does not allow bots to use Gmail." });+ expect(await policy.gate.call(caller(), tool, {})).toMatchObject({ ok: false, reason: "not-granted", message: "Acme does not allow bots to use Gmail." });++ const unconnected = fixture({ shared: installation("shared", { connected: false }) });+ expect(await unconnected.gate.call(caller(), tool, {})).toEqual({ ok: false, reason: "not-connected", status: 409, message: "Connect Gmail in Apps first." });++ const asks = fixture();+ expect(await asks.gate.call(caller({ fullAccess: () => false, engaged: true }), tool, {})).toEqual({+ ok: false, reason: "needs-access", status: 403,+ message: "Scout asks before it changes anything, so this page can only read Gmail. Ask Scout in the chat to do it, or set Scout to Full access.",+ });+ expect(await asks.gate.call(caller(), tool, {})).toEqual({ ok: false, reason: "needs-click", status: 403, message: "This changes something in Gmail, so it runs only right after the person clicks in this page." });+ expect(asks.shared.calls()).toEqual([]);+ expect(await asks.gate.call(caller({ engaged: true }), tool, {})).toMatchObject({ ok: true });+ });++ it("decides read-only by the tool's own listing, never by its name, and a send also follows the bot's own sending rule", async () => {+ // A tool named like a read that its listing does not mark read-only is a change; one named like a send that it marks is a read.+ const named = fixture({ shared: installation("shared", { readOnly: ["GMAIL_SEND_EMAIL"] }) });+ expect(await named.gate.call(caller(), { connector: "gmail", tool: "GMAIL_FETCH_EMAILS" }, {})).toMatchObject({ ok: false, reason: "needs-click" });+ expect(await named.gate.call(caller({ fullAccess: () => false }), { connector: "gmail", tool: "GMAIL_SEND_EMAIL" }, {})).toMatchObject({ ok: true });++ const careful = fixture({ shared: installation("shared", { readOnly: [] }), bot: { outbound: { policy: "ask" } } });+ expect(await careful.gate.call(caller({ engaged: true }), { connector: "gmail", tool: "GMAIL_SEND_EMAIL" }, {})).toEqual({+ ok: false, reason: "needs-access", status: 403,+ message: "Scout asks before it sends anything for you, so this page cannot send through Gmail. Ask Scout in the chat to send it.",+ });+ expect(await careful.gate.call(caller({ engaged: true }), { connector: "gmail", tool: "GMAIL_TRASH_MESSAGE" }, {})).toMatchObject({ ok: true });+ });++ it("reads the bot again just before the call goes out", async () => {+ let fixtureRef: ReturnType<typeof fixture> | undefined;+ const shared = installation("shared");+ const slow: AppInstallation = { ...shared.value, readOnlyTools: async () => { fixtureRef!.bots.set("b1", { ...fixtureRef!.bot, composio: false }); return new Set(["GMAIL_FETCH_EMAILS"]); } };+ fixtureRef = fixture({ shared: { ...shared, value: slow } });+ expect(await fixtureRef.gate.call(caller(), { connector: "gmail", tool: "GMAIL_FETCH_EMAILS" }, {})).toMatchObject({ ok: false, reason: "not-granted" });+ expect(shared.calls()).toEqual([]);+ });++ it("passes the tool's own failure on, cleaned and capped, and a plain-text answer as text", async () => {+ const failing = fixture({ shared: installation("shared", { answer: () => executed("GMAIL_FETCH_EMAILS", null, false, `bad token sk-ant-api03-${"x".repeat(40)} ${"y".repeat(3_000)}`) }) });+ const failed = await failing.gate.call(caller(), { connector: "gmail", tool: "GMAIL_FETCH_EMAILS" }, {});+ expect(failed).toMatchObject({ ok: false, reason: "tool-failed", status: 502 });+ const message = failed.ok ? "" : failed.message;+ expect(message.startsWith("Gmail said: bad token")).toBe(true);+ expect(message).not.toContain("sk-ant-api03-x");+ expect(message.length).toBeLessThanOrEqual(APP_LIMITS.pageConnectorErrorChars + "Gmail said: ".length);+ const plain = fixture({ shared: installation("shared", { answer: () => ({ content: [{ type: "text", text: "Done: 3 messages" }] }) }) });+ expect(await plain.gate.call(caller(), { connector: "gmail", tool: "GMAIL_FETCH_EMAILS" }, {})).toEqual({ ok: true, result: "Done: 3 messages" });+ });++ it("cuts a large answer to the limit and says so", async () => {+ const many = Array.from({ length: 4_000 }, (_, i) => ({ id: `m${i}`, snippet: "z".repeat(200) }));+ const { gate } = fixture({ shared: installation("shared", { answer: () => executed("GMAIL_FETCH_EMAILS", { messages: many, next: "tok" }) }) });+ const answer = await gate.call(caller(), { connector: "gmail", tool: "GMAIL_FETCH_EMAILS" }, {});+ expect(answer).toMatchObject({ ok: true, truncated: true, result: { next: "tok" } });+ const kept = answer.ok ? (answer.result as { messages: unknown[] }).messages : [];+ expect(kept.length).toBeGreaterThan(0);+ expect(kept.length).toBeLessThan(many.length);+ expect(Buffer.byteLength(JSON.stringify(answer.ok ? answer.result : null))).toBeLessThanOrEqual(APP_LIMITS.pageConnectorResultBytes);+ expect(fitResult("x".repeat(100), 10)).toEqual({ value: "\"xxxxxxxxx", truncated: true });+ });++ it("refuses arguments over the limit, and a call past its time", async () => {+ const { gate } = fixture();+ expect(await gate.call(caller(), { connector: "gmail", tool: "GMAIL_FETCH_EMAILS" }, { q: "x".repeat(APP_LIMITS.pageConnectorArgsBytes) })).toMatchObject({ ok: false, reason: "too-large", status: 413 });+ const slow = fixture({ shared: installation("shared", { hang: true }), callMs: 30 });+ expect(await slow.gate.call(caller(), { connector: "gmail", tool: "GMAIL_FETCH_EMAILS" }, {})).toEqual({ ok: false, reason: "timeout", status: 504, message: "The call ran past 0 seconds." });+ });++ it("holds every read the checks make to the time limit too", async () => {+ const shared = installation("shared");+ const stalled = { ...shared, value: { ...shared.value, readOnlyTools: () => new Promise<ReadonlySet<string>>(() => {}) } };+ const { gate, rows } = fixture({ shared: stalled, callMs: 30 });+ expect(await gate.call(caller(), { connector: "gmail", tool: "GMAIL_FETCH_EMAILS" }, {})).toMatchObject({ ok: false, reason: "timeout", status: 504 });+ expect(shared.calls()).toEqual([]);+ expect(rows[0]).toMatchObject({ decision: "auto-denied", summary: expect.stringContaining(": timeout (gmail)") });+ });++ it("sends a call that may change something once, and sends a read again on a fresh session when the first try fails", async () => {+ const down = fixture({ shared: installation("shared", { status: 502, readOnly: [] }) });+ expect(await down.gate.call(caller({ engaged: true }), { connector: "gmail", tool: "GMAIL_TRASH_MESSAGE" }, {})).toMatchObject({ ok: false, reason: "unavailable" });+ expect(down.shared.calls()).toHaveLength(1);+ // Sent, so recorded as allowed, with what came of it.+ expect(down.rows[0]).toMatchObject({ decision: "auto-approved", summary: expect.stringContaining(": ran, unavailable (gmail)") });+ const read = fixture({ shared: installation("shared", { status: 502 }) });+ expect(await read.gate.call(caller(), { connector: "gmail", tool: "GMAIL_FETCH_EMAILS" }, {})).toMatchObject({ ok: false, reason: "unavailable" });+ expect(read.shared.calls()).toHaveLength(2);+ expect(read.shared.frames.filter((one) => one.frame.method === "initialize")).toHaveLength(2);+ });++ it("limits calls per page and per bot and app", async () => {+ const { gate } = fixture();+ const page = caller();+ for (let i = 0; i < APP_LIMITS.pageConnectorCallsPerMinute; i++) expect((await gate.call(page, { connector: "gmail", tool: "GMAIL_FETCH_EMAILS" }, {})).ok).toBe(true);+ expect(await gate.call(page, { connector: "gmail", tool: "GMAIL_FETCH_EMAILS" }, {})).toEqual({ ok: false, reason: "rate-limited", status: 429, message: "Too many calls from this page. Wait a minute." });+ const other = caller();+ for (let i = 0; i < APP_LIMITS.connectorCallsPerMinute - APP_LIMITS.pageConnectorCallsPerMinute; i++) expect((await gate.call(other, { connector: "gmail", tool: "GMAIL_FETCH_EMAILS" }, {})).ok).toBe(true);+ expect(await gate.call(caller(), { connector: "gmail", tool: "GMAIL_FETCH_EMAILS" }, {})).toMatchObject({ ok: false, reason: "rate-limited", message: "Too many calls to Gmail from this page's bot. Wait a minute." });+ });++ it("records every call, allowed or refused, without its arguments or answer", async () => {+ const { gate, rows, lines } = fixture();+ const page = caller({ audit: { label: "page m9", key: "t1:m9", threadId: "t1" } });+ await gate.call(page, { connector: "gmail", tool: "GMAIL_FETCH_EMAILS" }, { q: "secret words" });+ await gate.call(page, { connector: "gmail", tool: "GMAIL_ADD_LABEL_TO_EMAIL" }, { q: "secret words" });+ expect(rows).toEqual([+ { threadId: "t1", botId: "b1", botName: "Scout", tool: "GMAIL_FETCH_EMAILS", summary: "page m9: ran (gmail)", decision: "auto-approved", source: "connector-scope", rule: "outside-turn:gmail" },+ { threadId: "t1", botId: "b1", botName: "Scout", tool: "GMAIL_ADD_LABEL_TO_EMAIL", summary: "page m9: needs-click (gmail)", decision: "auto-denied", source: "connector-scope", rule: "outside-turn:gmail" },+ ]);+ expect(lines).toEqual([expect.stringMatching(/^page m9 bot=b1 gmail tool=GMAIL_FETCH_EMAILS → ok \d+ms$/), expect.stringMatching(/^page m9 bot=b1 gmail tool=GMAIL_ADD_LABEL_TO_EMAIL → needs-click \d+ms$/)]);+ expect(JSON.stringify([rows, lines])).not.toContain("secret words");+ });++ it("is callable by server code with a declaration of its own and a fixed caller", async () => {+ const { gate, shared } = fixture();+ const { declared: _declared, ...identity } = caller();+ const call = bindConnectorGate(gate, identity);+ expect(await call([GMAIL], "gmail", "GMAIL_FETCH_EMAILS", {})).toMatchObject({ ok: true });+ expect(await call([], "gmail", "GMAIL_FETCH_EMAILS", {})).toMatchObject({ ok: false, reason: "not-declared" });+ expect(await call([GMAIL], "mcp:notes", "search", {})).toMatchObject({ ok: false, reason: "not-declared" });+ expect(shared.calls()).toHaveLength(1);+ });++ it("lists the declared tools with whether each app is connected for this person", async () => {+ const { gate } = fixture({ personApps: ["notion"] });+ expect(await gate.list(caller({ declared: [GMAIL, { connector: "notion", tools: ["NOTION_SEARCH"] }] }))).toEqual([+ { connector: "gmail", label: "Gmail", connected: true, tools: GMAIL.tools },+ { connector: "notion", label: "Notion", connected: false, tools: ["NOTION_SEARCH"] },+ ]);+ });+});++describe("an MCP server's tool, called outside a turn", () => {+ const NOTES: AppConnectorUse = { server: "notes", tools: ["search", "wipe", "list_items", "app_only"] };+ const tools = [+ { name: "search", annotations: { readOnlyHint: true }, inputSchema: { type: "object" } },+ { name: "wipe", annotations: { readOnlyHint: true } },+ { name: "list_items" },+ { name: "app_only", annotations: { readOnlyHint: true }, _meta: { ui: { visibility: ["app"] } } },+ ];+ const servers = (opened: Awaited<ReturnType<GateServers["open"]>>): GateServers & { asked: string[] } => {+ const asked: string[] = [];+ return { asked, open: async (_bot, person, name) => { asked.push(`${person ?? "-"}:${name}`); return opened; } };+ };++ it("runs a read by the tool's own annotation, whatever its name, and answers with its structured content", async () => {+ const fake = fakeServer(tools, (tool) => ({ content: [{ type: "text", text: "x" }], structuredContent: { tool } }));+ const { gate } = fixture({ servers: servers({ ok: true, server: fake.server }) });+ const page = caller({ declared: [NOTES], fullAccess: () => false });+ expect(await gate.call(page, { server: "notes", tool: "wipe" }, { all: true })).toEqual({ ok: true, result: { tool: "wipe" } });+ expect(await gate.call(page, { server: "notes", tool: "list_items" }, {})).toMatchObject({ ok: false, reason: "needs-access" });+ expect(await gate.call(caller({ declared: [NOTES] }), { server: "notes", tool: "list_items" }, {})).toMatchObject({ ok: false, reason: "needs-click" });+ expect(fake.calls).toEqual([{ tool: "wipe", args: { all: true } }]);+ });++ it("refuses a tool the bot's selection leaves out, one only the server's own app may call, and a server not connected", async () => {+ const fake = fakeServer(tools);+ const scoped = fixture({ servers: servers({ ok: true, server: fake.server }), bot: { toolScope: { allow: ["mcp:notes:list_items"] } } });+ expect(await scoped.gate.call(caller({ declared: [NOTES] }), { server: "notes", tool: "search" }, {})).toMatchObject({ ok: false, reason: "not-granted" });+ const open = fixture({ servers: servers({ ok: true, server: fake.server }) });+ expect(await open.gate.call(caller({ declared: [NOTES] }), { server: "notes", tool: "app_only" }, {})).toMatchObject({ ok: false, reason: "not-granted", message: "notes has no tool app_only for Scout." });+ const signedOut = fixture({ servers: servers({ ok: false, reason: "not-connected", label: "notes" }) });+ expect(await signedOut.gate.call(caller({ declared: [NOTES] }), { server: "notes", tool: "search" }, {})).toEqual({ ok: false, reason: "not-connected", status: 409, message: "Connect notes in Settings first." });+ expect(fake.calls).toEqual([]);+ });++ it("opens the server for the calling person", async () => {+ const fake = fakeServer(tools);+ const opener = servers({ ok: true, server: fake.server });+ const { gate } = fixture({ servers: opener });+ expect(await gate.call(caller({ declared: [NOTES], person: "ada" }), { server: "notes", tool: "search" }, { q: "x" })).toEqual({ ok: true, result: "ran search" });+ expect(opener.asked).toEqual(["ada:notes"]);+ });+});diff --git a/server/connector-gate.ts b/server/connector-gate.tsnew file mode 100644index 0000000000..0c934a8b64--- /dev/null+++ b/server/connector-gate.ts@@ -0,0 +1,383 @@+// One connector tool call made outside a bot's turn, by something the bot made that declared the tools it calls (a bot's+// page today). Security invariant: such a call is never allowed more than the bot's own turn would be. It runs only a tool+// the caller declared by exact name; only on a connected app or MCP server the bot is granted, with the same grant checks a+// turn's call meets; only with the calling person's own connection, chosen here and never named by the caller; and a tool+// that changes something only when its own listing does not say it reads, the person clicked just now, and the bot's+// access level would let a turn run it without asking. Nothing that would ask is turned into a question here: it is+// refused with the reason.+import { APP_LIMITS, type AppConnectorUse } from "../shared/app.ts";+import { pageConnectorUndeclared } from "../shared/app-frame/bridge.ts";+import { accountLimit, connectorAccessDecision } from "../shared/connector-scopes.ts";+import { isOutboundTool } from "../shared/outbound.ts";+import { redactSecretsInText } from "../shared/redact.ts";+import { allowsTool, canUseMcpServer } from "../shared/tool-scope.ts";+import type { ConnectorToolGrant } from "../shared/wire.ts";+import { rowRate } from "./chat-apps.ts";+import { toolData } from "./connected-reads.ts";+import { parseMcpResponse } from "./connector-tools-list.ts";+import { modelVisible } from "./mcp-app-observer.ts";+import { connectorScopeRefusalText, evaluateConnectorTools } from "./connector-verdict.ts";+import type { DecisionRow } from "./decision-log.ts";+import { sendsWithoutAsking } from "./outbound-hold.ts";+import { appFrame } from "./skill-burger/executors.ts";+import type { BotRecord } from "./store.ts";+import { appLabel } from "./team-connections.ts";++type Json = Record<string, unknown>;++export type ConnectorTarget = { connector: string; tool: string } | { server: string; tool: string };++/** The bot fields the gate judges a call by, read again just before the call is sent. */+export type GateBot = Pick<BotRecord, "id" | "name" | "composio" | "connectorTools" | "connectorScopes" | "outbound" | "toolScope">;++export type GateRefusal =+ | "not-declared" | "not-granted" | "not-connected" | "needs-access" | "needs-click" | "rate-limited" | "too-large" | "timeout" | "tool-failed" | "unavailable";++export type GateAnswer = { ok: true; result: unknown; truncated?: true } | { ok: false; reason: GateRefusal; status: number; message: string };++/** Who calls, and for whom. */+export interface ConnectorCaller {+ botId: string;+ /** The person whose own connections a call uses where each person connects their own (a Team Cloud); null elsewhere. */+ person: string | null;+ /** The tools this caller declared, by exact name. */+ declared: readonly AppConnectorUse[];+ /** Whether a turn of this bot, where the call comes from, would run a change without asking: Full access. */+ fullAccess(): boolean;+ /** The person clicked in what made the call just now, as the host saw it. */+ engaged: boolean;+ /** `label` names the caller in the audit line ("page m1"); `key` is its own rate limit; `threadId` the conversation it is+ * in, when it is in one. */+ audit: { label: string; key: string; threadId?: string };+ /** What the person reads the caller as, in a refusal: "this page" unless given. */+ what?: string;+}++/** One installation of the connected apps: this computer's or the team's, or a person's own. */+export interface AppInstallation {+ /** One id per installation: a transport session is reused only there. */+ id: string;+ connected(): Promise<Record<string, { connected: boolean; accounts?: ReadonlyArray<{ id: string; status: string }> }>>;+ /** The real service slugs, so an underscored app (bland_ai) is not read as another (bland). */+ serviceSlugs(): Promise<readonly string[]>;+ /** The tools whose own listing marks them read-only (annotations.readOnlyHint, not destructive). */+ readOnlyTools(): Promise<ReadonlySet<string>>;+ relay(frame: Json, session: string | undefined, signal: AbortSignal): Promise<{ status: number; bytes: Uint8Array; transportSessionId?: string }>;+}++export interface GateApps {+ configured(): boolean;+ /** Where `person`'s calls of `toolkit` go, or null when they have no such installation. */+ installation(person: string | null, toolkit: string): AppInstallation | null;+ /** The organisation's rules' refusal of these tools, if any. */+ policyRefusal(slugs: readonly string[], serviceSlugs: readonly string[]): string | undefined;+ /** The app's name as people read it ("Gmail"). */+ label?(toolkit: string): string;+}++/** An MCP server as the bot's own turns would mount it, outside a turn. */+export interface OpenedServer {+ label: string;+ tools(signal: AbortSignal): Promise<Json[]>;+ /** The tool's answer, or the server's own error text, cleaned of anything configured or secret-shaped. */+ call(tool: string, args: Json, signal: AbortSignal): Promise<{ ok: true; body: Json } | { ok: false; text: string }>;+}++export interface GateServers {+ open(bot: GateBot, person: string | null, name: string): Promise<{ ok: true; server: OpenedServer } | { ok: false; reason: "not-granted" | "not-connected"; label: string }>;+}++export interface ConnectorGateDeps {+ bot(id: string): GateBot | undefined;+ apps?: GateApps;+ servers?: GateServers;+ decide(row: Omit<DecisionRow, "at">): void;+ log?(line: string): void;+ now?(): number;+ /** Overrides APP_LIMITS.pageConnectorMs. */+ callMs?: number;+}++export interface ConnectorListing {+ connector?: string;+ server?: string;+ label: string;+ connected: boolean;+ tools: string[];+}++export interface ConnectorGate {+ call(caller: ConnectorCaller, target: ConnectorTarget, args: unknown): Promise<GateAnswer>;+ /** The caller's declared tools, with whether the person has each connected now. */+ list(caller: ConnectorCaller): Promise<ConnectorListing[]>;+}++const SESSION_MS = 10 * 60_000;++function isRecord(value: unknown): value is Json {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++function clip(text: string, limit: number): string {+ return text.length <= limit ? text : `${text.slice(0, limit - 1)}…`;+}++const bytesOf = (value: unknown): number => Buffer.byteLength(JSON.stringify(value) ?? "null");++/** The answer within `limit` JSON bytes: a list, or an object's longest list, loses items from its end; anything else+ * becomes its JSON text, cut. */+export function fitResult(value: unknown, limit: number): { value: unknown; truncated: boolean } {+ if (bytesOf(value) <= limit) return { value, truncated: false };+ const shorten = (list: unknown[], rebuild: (kept: unknown[]) => unknown): unknown => {+ let low = 0, high = list.length;+ while (low < high) {+ const mid = Math.ceil((low + high) / 2);+ if (bytesOf(rebuild(list.slice(0, mid))) <= limit) low = mid; else high = mid - 1;+ }+ const kept = rebuild(list.slice(0, low));+ return bytesOf(kept) <= limit ? kept : undefined;+ };+ if (Array.isArray(value)) {+ const kept = shorten(value, (items) => items);+ if (kept !== undefined) return { value: kept, truncated: true };+ } else if (isRecord(value)) {+ const longest = Object.entries(value).filter(([, field]) => Array.isArray(field)).sort(([, a], [, b]) => bytesOf(b) - bytesOf(a))[0];+ if (longest) {+ const kept = shorten(longest[1] as unknown[], (items) => ({ ...value, [longest[0]]: items }));+ if (kept !== undefined) return { value: kept, truncated: true };+ }+ }+ const text = JSON.stringify(value) ?? "";+ let cut = text.slice(0, limit);+ while (Buffer.byteLength(cut) > limit) cut = cut.slice(0, Math.floor(cut.length * 0.9));+ return { value: cut, truncated: true };+}++/** A tool's own failure text, as a page may show it. */+function failureText(label: string, text: string): string {+ const own = clip(redactSecretsInText(text).replace(/\s+/g, " ").trim(), APP_LIMITS.pageConnectorErrorChars);+ return own ? `${label} said: ${own}` : `${label} could not do that.`;+}++/** The text an MCP tools/call result carries. */+function contentText(result: Json): string {+ return (Array.isArray(result.content) ? result.content : []).flatMap((part) => (isRecord(part) && typeof part.text === "string" ? [part.text] : [])).join("\n");+}++const refusal = (reason: GateRefusal, status: number, message: string): GateAnswer => ({ ok: false, reason, status, message });++export function createConnectorGate(deps: ConnectorGateDeps): ConnectorGate {+ const now = deps.now ?? Date.now;+ const log = deps.log ?? ((line: string) => console.info(`connector gate: ${line}`));+ const callerRate = rowRate(APP_LIMITS.pageConnectorCallsPerMinute, 60_000);+ const connectorRate = rowRate(APP_LIMITS.connectorCallsPerMinute, 60_000);+ const sessions = new Map<string, { id: string | undefined; at: number }>();+ const callMs = deps.callMs ?? APP_LIMITS.pageConnectorMs;+ const appLabelOf = (toolkit: string) => deps.apps?.label?.(toolkit) ?? appLabel(toolkit);++ /** `sent`: the call passed every check and went out, so it is recorded as allowed whatever came back. */+ const audit = (caller: ConnectorCaller, bot: GateBot | undefined, target: ConnectorTarget, answer: GateAnswer, started: number, sent: boolean): GateAnswer => {+ const where = "server" in target ? `mcp:${target.server}` : target.connector;+ // Every call is recorded; its arguments and answer never are.+ log(`${caller.audit.label} bot=${caller.botId} ${where} tool=${target.tool.slice(0, 128)} → ${answer.ok ? "ok" : answer.reason} ${now() - started}ms`);+ deps.decide({+ threadId: caller.audit.threadId ?? "",+ botId: caller.botId,+ ...(bot ? { botName: bot.name } : {}),+ tool: target.tool,+ summary: `${caller.audit.label}: ${answer.ok ? "ran" : sent ? `ran, ${answer.reason}` : answer.reason} (${where})`.slice(0, 240),+ decision: answer.ok || sent ? "auto-approved" : "auto-denied",+ source: "connector-scope",+ rule: `outside-turn:${where}`,+ });+ return answer;+ };++ /** Would a turn of this bot run a change without asking? A send also follows the bot's own sending rule. */+ const accessRefusal = (caller: ConnectorCaller, bot: GateBot, label: string, sends: boolean): string | null => {+ const what = caller.what ?? "this page";+ if (!caller.fullAccess()) {+ return `${bot.name} asks before it changes anything, so ${what} can only read ${label}. Ask ${bot.name} in the chat to do it, or set ${bot.name} to Full access.`;+ }+ if (sends && !sendsWithoutAsking(bot.outbound, true, false)) {+ return `${bot.name} asks before it sends anything for you, so ${what} cannot send through ${label}. Ask ${bot.name} in the chat to send it.`;+ }+ return null;+ };++ const NEEDS_CLICK = (caller: ConnectorCaller, label: string) => `This changes something in ${label}, so it runs only right after the person clicks in ${caller.what ?? "this page"}.`;++ /** The bot's grant for one Composio tool, as the turn's relay judges it; null when granted. */+ const appGrantRefusal = (bot: GateBot | undefined, tool: string, toolkit: string, account: string | undefined, slugs: readonly string[]): string | null => {+ const label = appLabelOf(toolkit);+ if (!bot || bot.composio === false || !deps.apps?.configured() || !canUseMcpServer(bot.toolScope, "composio")) return `${bot?.name ?? "This bot"} cannot use connected apps.`;+ const policy = deps.apps.policyRefusal([tool], slugs);+ if (policy) return policy;+ if (!evaluateConnectorTools([tool], bot.connectorTools as Record<string, ConnectorToolGrant> | undefined, slugs).allowed) {+ return `${bot.name} is not allowed ${tool} in ${label}. The person can allow it in ${bot.name}'s Apps settings.`;+ }+ const access = connectorAccessDecision(bot.connectorScopes, [{ slug: tool, ...(account ? { account } : {}) }], slugs);+ if (!access.ok && access.reason !== "account") return connectorScopeRefusalText({ kind: "tools", invoked: tool, names: [tool] }, access.reason, bot.name, label, tool);+ return null;+ };++ async function session(installation: AppInstallation, signal: AbortSignal, fresh: boolean): Promise<string | undefined> {+ const kept = sessions.get(installation.id);+ if (!fresh && kept && now() - kept.at < SESSION_MS) return kept.id;+ const init = await installation.relay({+ jsonrpc: "2.0", id: "omb-gate-init", method: "initialize",+ params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "openmausbot-pages", version: "1" } },+ }, undefined, signal);+ if (init.status !== 200) throw new Error(`connected apps answered HTTP ${init.status}`);+ // Streamable-HTTP MCP servers expect the initialized notification before the first request.+ await installation.relay({ jsonrpc: "2.0", method: "notifications/initialized" }, init.transportSessionId, signal).catch(() => undefined);+ sessions.set(installation.id, { id: init.transportSessionId, at: now() });+ if (sessions.size > 100) for (const [id, entry] of sessions) if (now() - entry.at >= SESSION_MS) sessions.delete(id);+ return init.transportSessionId;+ }++ async function callApp(caller: ConnectorCaller, target: { connector: string; tool: string }, args: Json, signal: AbortSignal, sent: () => void): Promise<GateAnswer> {+ const { connector: toolkit, tool } = target;+ const label = appLabelOf(toolkit);+ const bot = deps.bot(caller.botId);+ const installation = deps.apps?.configured() ? deps.apps.installation(caller.person, toolkit) : null;+ const slugs = installation ? await installation.serviceSlugs().catch(() => [] as readonly string[]) : [];+ const granted = appGrantRefusal(bot, tool, toolkit, undefined, slugs);+ if (granted) return refusal("not-granted", 403, granted);+ if (!installation) return refusal("not-connected", 409, `Connect ${label} in Apps first.`);+ let services: Awaited<ReturnType<AppInstallation["connected"]>>;+ try { services = await installation.connected(); } catch { return refusal("unavailable", 503, "Connected apps can't be reached right now. Try again in a few minutes."); }+ const state = Object.hasOwn(services, toolkit) ? services[toolkit] : undefined;+ const active = (state?.accounts ?? []).filter((one) => /^active$/i.test(one.status)).map((one) => one.id);+ if (!state?.connected) return refusal("not-connected", 409, `Connect ${label} in Apps first.`);+ // The account is chosen here, as the bot's own reads choose it: one the bot may use, else the newest active one.+ const allowed = accountLimit(bot!.connectorScopes, toolkit);+ const account = allowed ? active.find((id) => allowed.includes(id)) : active.length > 1 ? active[0] : undefined;+ if (allowed && !account) return refusal("not-connected", 409, `Connect the ${label} account ${bot!.name} may use in Apps first.`);+ const readOnly = (await installation.readOnlyTools().catch(() => new Set<string>())).has(tool);+ if (!readOnly) {+ const refused = accessRefusal(caller, bot!, label, isOutboundTool(tool));+ if (refused) return refusal("needs-access", 403, refused);+ if (!caller.engaged) return refusal("needs-click", 403, NEEDS_CLICK(caller, label));+ }+ // The bot as it is now, just before the call goes out: a grant taken away meanwhile wins.+ const again = appGrantRefusal(deps.bot(caller.botId), tool, toolkit, account, slugs);+ if (again) return refusal("not-granted", 403, again);+ const { frame } = appFrame(tool, args, account, Math.floor(Math.random() * 1e9));+ const send = async (fresh: boolean) => {+ const transport = await session(installation, signal, fresh);+ sent();+ return installation.relay(frame, transport, signal);+ };+ let relayed = await send(false);+ // A call that may have changed something is never sent twice.+ if (relayed.status !== 200 && readOnly) relayed = await send(true);+ if (relayed.status !== 200) return refusal("unavailable", 502, `${label} could not be reached. Try again in a moment.`);+ const answer = parseMcpResponse(new TextDecoder().decode(relayed.bytes), frame.id);+ if (!answer) return refusal("unavailable", 502, `${label} sent no answer.`);+ const error = isRecord(answer.error) ? answer.error.message : undefined;+ if (typeof error === "string") return refusal("tool-failed", 502, failureText(label, error));+ const result = isRecord(answer.result) ? answer.result : {};+ if (result.isError === true) return refusal("tool-failed", 502, failureText(label, contentText(result)));+ try {+ return { ok: true, result: toolData(tool, answer) };+ } catch (failure) {+ const text = contentText(result);+ let json = true;+ try { JSON.parse(text); } catch { json = false; }+ if (text && !json) return { ok: true, result: text };+ return refusal("tool-failed", 502, failureText(label, failure instanceof Error ? failure.message : String(failure)));+ }+ }++ async function callServer(caller: ConnectorCaller, target: { server: string; tool: string }, args: Json, signal: AbortSignal, sent: () => void): Promise<GateAnswer> {+ const { server: name, tool } = target;+ const bot = deps.bot(caller.botId);+ const toolGranted = (one: GateBot | undefined) => Boolean(one && canUseMcpServer(one.toolScope, name) && allowsTool(one.toolScope, { kind: "mcp", server: name, name: tool }));+ if (!deps.servers || !bot || !toolGranted(bot)) return refusal("not-granted", 403, `${bot?.name ?? "This bot"} is not allowed ${tool} on ${name}. The person can allow it in its tool settings.`);+ const opened = await deps.servers.open(bot, caller.person, name);+ if (!opened.ok) {+ return opened.reason === "not-granted"+ ? refusal("not-granted", 403, `${bot.name} does not use ${opened.label}.`)+ : refusal("not-connected", 409, `Connect ${opened.label} in Settings first.`);+ }+ const { server } = opened;+ let tools: Json[];+ try { tools = await server.tools(signal); } catch { return refusal("unavailable", 503, `${server.label} can't be reached right now.`); }+ const definition = tools.find((one) => one.name === tool);+ // A tool only an MCP server's own app may call is not one of the bot's tools.+ if (!definition || !modelVisible(definition)) return refusal("not-granted", 403, `${server.label} has no tool ${tool} for ${bot.name}.`);+ const annotations = isRecord(definition.annotations) ? definition.annotations : {};+ if (annotations.readOnlyHint !== true) {+ const refused = accessRefusal(caller, bot, server.label, false);+ if (refused) return refusal("needs-access", 403, refused);+ if (!caller.engaged) return refusal("needs-click", 403, NEEDS_CLICK(caller, server.label));+ }+ if (!toolGranted(deps.bot(caller.botId))) return refusal("not-granted", 403, `${bot.name} is no longer allowed ${tool} on ${name}.`);+ sent();+ const answer = await server.call(tool, args, signal);+ if (!answer.ok) return refusal("tool-failed", 502, failureText(server.label, answer.text));+ if (answer.body.isError === true) return refusal("tool-failed", 502, failureText(server.label, contentText(answer.body)));+ return { ok: true, result: answer.body.structuredContent !== undefined ? answer.body.structuredContent : contentText(answer.body) };+ }++ async function call(caller: ConnectorCaller, target: ConnectorTarget, args: unknown): Promise<GateAnswer> {+ const started = now();+ const bot = deps.bot(caller.botId);+ let sent = false;+ const done = (answer: GateAnswer) => audit(caller, bot, target, answer, started, sent);+ const declared = caller.declared.some((group) => ("server" in target+ ? "server" in group && group.server === target.server+ : "connector" in group && group.connector === target.connector) && group.tools.includes(target.tool));+ if (!declared) return done(refusal("not-declared", 409, pageConnectorUndeclared(target)));+ if (args !== undefined && !isRecord(args)) return done(refusal("too-large", 400, "A connector call's arguments are one object."));+ const given = (args ?? {}) as Json;+ if (bytesOf(given) > APP_LIMITS.pageConnectorArgsBytes) return done(refusal("too-large", 413, `A connector call's arguments are at most ${APP_LIMITS.pageConnectorArgsBytes} bytes of JSON.`));+ const where = "server" in target ? `mcp:${target.server}` : target.connector;+ const at = now();+ if (!callerRate.take(caller.audit.key, at)) return done(refusal("rate-limited", 429, `Too many calls from ${caller.what ?? "this page"}. Wait a minute.`));+ if (!connectorRate.take(`${caller.botId}\u0000${where}`, at)) {+ return done(refusal("rate-limited", 429, `Too many calls to ${"server" in target ? target.server : appLabelOf(target.connector)} from ${caller.what ?? "this page"}'s bot. Wait a minute.`));+ }+ const signal = AbortSignal.timeout(callMs);+ // The time limit holds for every read the checks make too, not only for the call itself.+ const expired = new Promise<never>((_, reject) => signal.addEventListener("abort", () => reject(signal.reason), { once: true }));+ const went = () => { sent = true; };+ try {+ const answer = await Promise.race([+ "server" in target ? callServer(caller, target, given, signal, went) : callApp(caller, target, given, signal, went),+ expired,+ ]);+ if (!answer.ok) return done(answer);+ const fitted = fitResult(answer.result, APP_LIMITS.pageConnectorResultBytes);+ return done({ ok: true, result: fitted.value, ...(fitted.truncated ? { truncated: true as const } : {}) });+ } catch (error) {+ if (signal.aborted) return done(refusal("timeout", 504, `The call ran past ${Math.round(callMs / 1000)} seconds.`));+ log(`${caller.audit.label} failed: ${error instanceof Error ? error.message : String(error)}`);+ return done(refusal("unavailable", 502, "That connected app could not be reached. Try again in a moment."));+ }+ }++ async function list(caller: ConnectorCaller): Promise<ConnectorListing[]> {+ const bot = deps.bot(caller.botId);+ return Promise.all(caller.declared.map(async (group): Promise<ConnectorListing> => {+ if ("server" in group) {+ const opened = bot && deps.servers ? await deps.servers.open(bot, caller.person, group.server).catch(() => null) : null;+ return { server: group.server, label: opened?.ok ? opened.server.label : opened?.label ?? group.server, connected: opened?.ok === true, tools: [...group.tools] };+ }+ const installation = deps.apps?.configured() ? deps.apps.installation(caller.person, group.connector) : null;+ const services = installation ? await installation.connected().catch(() => null) : null;+ const connected = Boolean(services && Object.hasOwn(services, group.connector) && services[group.connector]?.connected);+ return { connector: group.connector, label: appLabelOf(group.connector), connected, tools: [...group.tools] };+ }));+ }++ return { call, list };+}++/** The gate as a caller with a fixed identity sees it: one call names its declaration, the connected app (or "mcp:<server>")+ * and the tool. */+export function bindConnectorGate(gate: ConnectorGate, caller: Omit<ConnectorCaller, "declared">) {+ return (declaration: readonly AppConnectorUse[], connector: string, tool: string, args: unknown): Promise<GateAnswer> =>+ gate.call({ ...caller, declared: declaration }, connector.startsWith("mcp:") ? { server: connector.slice(4), tool } : { connector, tool }, args);+}diff --git a/server/drivers/agents-app-tools.ts b/server/drivers/agents-app-tools.tsindex d04938d18d..c557fd1e1f 100644--- a/server/drivers/agents-app-tools.ts+++ b/server/drivers/agents-app-tools.ts@@ -15,7 +15,7 @@ export const APP_TOOL_DEFINITIONS = [fallback_text: { type: "string", description: "Optional plain text for clients without pages." },frameless: { type: "boolean", description: "true drops the card frame; a replacement keeps its frame unless given." },live: { type: "boolean", description: "With path: true reloads it when its folder changes." },- uses: { type: "array", items: { type: "string", enum: ["data", "state"] } },+ uses: { type: "array", items: { type: "string" } },app_id: { type: "string", description: "Only to replace a page you showed." },},},diff --git a/server/drivers/agents-call-cards.ts b/server/drivers/agents-call-cards.tsindex acd6250a7c..bfda4a1e61 100644--- a/server/drivers/agents-call-cards.ts+++ b/server/drivers/agents-call-cards.ts@@ -1,7 +1,7 @@// The agents tools that put something in front of the person: the Watcher's options card, the widget tools and the// page tools.import { agentsCallMember } from "../../shared/agents-tool-names.ts";-import { parseShowHtmlInput, parseUpdateHtmlInput } from "../../shared/app.ts";+import { appUsesList, parseShowHtmlInput, parseUpdateHtmlInput } from "../../shared/app.ts";import { parseOptionsCardInput, WATCHER_OPTIONS_CARD_BOT_ID } from "../../shared/options-card.ts";import { parseWidgetInput, widgetAdvice } from "../../shared/widget.ts";@@ -21,7 +21,7 @@ async function callAppTool(name: "show_html" | "update_html", args: Json, contexconst page = parsed.value.jsx !== undefined ? { jsx: args.jsx } : parsed.value.path !== undefined ? { path: args.path } : { html: args.html };const frameless = parsed.value.frameless !== undefined ? { frameless: parsed.value.frameless } : {};const live = parsed.value.live !== undefined ? { live: parsed.value.live } : {};- const uses = parsed.value.uses !== undefined ? { uses: parsed.value.uses } : {};+ const uses = parsed.value.uses !== undefined ? { uses: appUsesList(parsed.value.uses, parsed.value.connectors) } : {};const body = updating? { tool: name, app_id: args.app_id, ...page, ...(typeof args.title === "string" ? { title: args.title } : {}), ...frameless, ...live, ...uses }: {diff --git a/server/drivers/agents-catalog-goldens/antigravity-cli.tools-list.json b/server/drivers/agents-catalog-goldens/antigravity-cli.tools-list.jsonindex 988330cce1..a69b4362e1 100644--- a/server/drivers/agents-catalog-goldens/antigravity-cli.tools-list.json+++ b/server/drivers/agents-catalog-goldens/antigravity-cli.tools-list.json@@ -465,11 +465,7 @@"uses": {"type": "array","items": {- "type": "string",- "enum": [- "data",- "state"- ]+ "type": "string"}},"app_id": {diff --git a/server/drivers/agents-catalog-goldens/full.tools-list.json b/server/drivers/agents-catalog-goldens/full.tools-list.jsonindex a6a6b85bd7..ffbfa524b3 100644--- a/server/drivers/agents-catalog-goldens/full.tools-list.json+++ b/server/drivers/agents-catalog-goldens/full.tools-list.json@@ -668,11 +668,7 @@"uses": {"type": "array","items": {- "type": "string",- "enum": [- "data",- "state"- ]+ "type": "string"}},"app_id": {diff --git a/server/drivers/agents-catalog-goldens/profiles.json b/server/drivers/agents-catalog-goldens/profiles.jsonindex 1ac7673b4e..a2fb2be528 100644--- a/server/drivers/agents-catalog-goldens/profiles.json+++ b/server/drivers/agents-catalog-goldens/profiles.json@@ -1,7 +1,7 @@{"default": {- "bytes": 62651,- "sha256": "f971ff532c8ca9aa0e45102c2cf471a98bcf707fa14b1bef0046bf01d96786ab",+ "bytes": 62627,+ "sha256": "a87bc176ad0b181def31a64480449cf43fa2059be643c315953ac87c620d9b49","tools": ["tool_result_read","list_room_targets",@@ -62,8 +62,8 @@]},"voice": {- "bytes": 63432,- "sha256": "efb91749198708eba5984a96b8fdf633ca3671bc0f704946cd7357425c4f22c6",+ "bytes": 63408,+ "sha256": "e1db135fbbd430d7f24cf5977ac161dfc879e17d0ec51c1ed828d3add01eef31","tools": ["tool_result_read","list_room_targets",@@ -125,8 +125,8 @@]},"shared": {- "bytes": 64916,- "sha256": "dbe76b09cf20c884f131ad458aa9d9780fad7dc332d27cede960ff6cf9e18303",+ "bytes": 64892,+ "sha256": "84197168506e111e0381fe08ab276c286fcf248e396325558d5b8c9e35b0db37","tools": ["tool_result_read","list_shared_computers",@@ -189,8 +189,8 @@]},"shared+voice": {- "bytes": 65697,- "sha256": "ea25d09d3cf93096968028ae0f37bff887ed8ff92b0e128562dbb0249627fb80",+ "bytes": 65673,+ "sha256": "1f11f4554421d45368eb7c086aa9fd565838984aba94a14dd0d00e8b8bcca05c","tools": ["tool_result_read","list_shared_computers",@@ -254,8 +254,8 @@]},"skills": {- "bytes": 65074,- "sha256": "54e4a92acdb910bbc43396c36c094d4cd16e289da4f418bbe45d6c29d09df933",+ "bytes": 65050,+ "sha256": "b7dde8a2f6c51570beb8d6319dfd4fd3f4411a549a2295d9e23cf39e31fd913c","tools": ["tool_result_read","list_room_targets",@@ -318,8 +318,8 @@]},"skills+voice": {- "bytes": 65855,- "sha256": "5498058e312314b1772d013480875bdf52296224260a14d74a0593d051739daa",+ "bytes": 65831,+ "sha256": "8ea9f6facb9b272752e2ed88170bf6ef852e4be31200db21648d64a0cebd9a45","tools": ["tool_result_read","list_room_targets",@@ -383,8 +383,8 @@]},"skills+shared": {- "bytes": 67339,- "sha256": "51cf792084549e844dd06744a95010345af90835e5a64ceb987144636632705b",+ "bytes": 67315,+ "sha256": "d461ef0e18f90ead3cbc2ebef8f9b5baa5fb36dba87080db9de9797cb606d4f9","tools": ["tool_result_read","list_shared_computers",@@ -449,8 +449,8 @@]},"skills+shared+voice": {- "bytes": 68120,- "sha256": "10be6b1febc86237827a0ef8f8540fb236b7ae8ebba1bbd7a38d33405a82a8ab",+ "bytes": 68096,+ "sha256": "dd8cd734cab34d90db51471e422e007ec991e5e19205a7018ff87637e6b54d21","tools": ["tool_result_read","list_shared_computers",@@ -516,8 +516,8 @@]},"non-chief": {- "bytes": 54103,- "sha256": "0ed8d4c15b6c6add25ab3417ea2ab389ad24dcbb0cbb64c1d49aa6396c896e39",+ "bytes": 54079,+ "sha256": "cd31c7362f2bb417be0c94b41a46286bb8414955199be7c9c81df361d81c9d85","tools": ["tool_result_read","list_room_targets",@@ -571,8 +571,8 @@]},"voice+non-chief": {- "bytes": 54884,- "sha256": "c1d78a1c9e32629115737b1f33a6d44048f474f7664598daaa4d486b17d001ac",+ "bytes": 54860,+ "sha256": "d6fb26f217d2ebce612a138d10dad1b7ee77d5e24325905f4998f3d9c9e0d48e","tools": ["tool_result_read","list_room_targets",@@ -627,8 +627,8 @@]},"shared+non-chief": {- "bytes": 56368,- "sha256": "32500585206c0ae2ba15c77291dadf4d98bb99e330ed90a174d32327e29c8e43",+ "bytes": 56344,+ "sha256": "aa27aa1c920c097db01ce4a130a863b3dfbb23eda9ab79abd435600d8f906ce2","tools": ["tool_result_read","list_shared_computers",@@ -684,8 +684,8 @@]},"shared+voice+non-chief": {- "bytes": 57149,- "sha256": "d6782c327006a88fb2c248e243a5aee1b6139ae364f8afeb92e2a18555bd271f",+ "bytes": 57125,+ "sha256": "7b082a0a4ff85846e8378815d56c1889686a86340c2d185a2eae26367a241cf1","tools": ["tool_result_read","list_shared_computers",@@ -742,8 +742,8 @@]},"skills+non-chief": {- "bytes": 56526,- "sha256": "ab2653d9cadba76e774cfb86cc7f5ae5e735ed318573b431784f3e52d5e5fb05",+ "bytes": 56502,+ "sha256": "fca04bf2e81c56255a37b386422a2ba19d0cfbef177e36f8f9faa77031a994df","tools": ["tool_result_read","list_room_targets",@@ -799,8 +799,8 @@]},"skills+voice+non-chief": {- "bytes": 57307,- "sha256": "e0168ea0d4edd367fc59f420b1fdab9c31c0135e9eb196512c5c6576d5dab6eb",+ "bytes": 57283,+ "sha256": "d0e2e0b9b3d56c5f06c31d3c3e034049dedb5b20e221a24482e60e0950b612b5","tools": ["tool_result_read","list_room_targets",@@ -857,8 +857,8 @@]},"skills+shared+non-chief": {- "bytes": 58791,- "sha256": "0c116b2aa7f9d3ffb0d2a5f5412f78ed13d9563eeffcdbb49472b64855b0ce55",+ "bytes": 58767,+ "sha256": "79aee30fbe8af485dd45e20ec8f47e5cab658a48004a82252e8110f9bb692e8e","tools": ["tool_result_read","list_shared_computers",@@ -916,8 +916,8 @@]},"skills+shared+voice+non-chief": {- "bytes": 59572,- "sha256": "053bca11a6a464e9e9fdad21d18fbbecb5246b91ea5e2633a1fa0bb129cd6244",+ "bytes": 59548,+ "sha256": "61f72085ec95deb72838af276dc676db77ecf48d211f3ea78d1b80badffa4612","tools": ["tool_result_read","list_shared_computers",@@ -976,8 +976,8 @@]},"skills+shared+voice+cloud-home": {- "bytes": 67876,- "sha256": "ef1d1466191ae299bde944c5e4ac8dba1554399420e0a65386d298c3e9d57230",+ "bytes": 67852,+ "sha256": "4677074b46fb14b4c38bbdd320f0328d2b71adf032832ee3bec2ecd1dee45e0a","tools": ["tool_result_read","list_shared_computers",@@ -1043,8 +1043,8 @@]},"skills+shared+voice+non-chief+cloud-home": {- "bytes": 59328,- "sha256": "647dbc8b64bc00b900b7a2b2cc18fe390ee6f833a99f538316ecf75fbed203ba",+ "bytes": 59304,+ "sha256": "551e227fd901931768c8be3b8d5629359ae6017f2a76ad30940d9d8adb9ff21d","tools": ["tool_result_read","list_shared_computers",@@ -1103,8 +1103,8 @@]},"skills+shared+voice+x": {- "bytes": 71959,- "sha256": "8372e4e93c8cdf0558d4d660194e6e797c0a6ef0787b847e15c15432b06ee734",+ "bytes": 71935,+ "sha256": "188d0c94883239d135e6d3b256e60e0440eba72818203a262d9a857a5d942a32","tools": ["tool_result_read","list_shared_computers",@@ -1174,8 +1174,8 @@]},"skills+shared+voice+x+team": {- "bytes": 71959,- "sha256": "8372e4e93c8cdf0558d4d660194e6e797c0a6ef0787b847e15c15432b06ee734",+ "bytes": 71935,+ "sha256": "188d0c94883239d135e6d3b256e60e0440eba72818203a262d9a857a5d942a32","tools": ["tool_result_read","list_shared_computers",@@ -1245,8 +1245,8 @@]},"skills+shared+voice+x+team+images": {- "bytes": 73906,- "sha256": "b88de7b45bb16b52f239028edb46125dda5e9a6e3c52451e9d66e274df31e7b6",+ "bytes": 73882,+ "sha256": "b74fd64612eedddb67cb1532e88c652b2289e141c0d666474a9c084312fe4f96","tools": ["tool_result_read","list_shared_computers",@@ -1318,8 +1318,8 @@]},"default+legacy-switches": {- "bytes": 62651,- "sha256": "f971ff532c8ca9aa0e45102c2cf471a98bcf707fa14b1bef0046bf01d96786ab",+ "bytes": 62627,+ "sha256": "a87bc176ad0b181def31a64480449cf43fa2059be643c315953ac87c620d9b49","tools": ["tool_result_read","list_room_targets",@@ -1380,8 +1380,8 @@]},"default+mausbot": {- "bytes": 63302,- "sha256": "60b615dd716b9c2771976356b1dbd50d391daa4b38cb2ad6a0b6778aa427db3b",+ "bytes": 63278,+ "sha256": "ef04aaa5d29ae0e58dec55abe92c442b139238b088a357a869d8977b16bc4240","tools": ["tool_result_read","list_room_targets",@@ -1444,8 +1444,8 @@]},"skills+shared+voice+mausbot": {- "bytes": 68771,- "sha256": "a66ea038d92ac7d2561946c00db620cf1d95375a04f1edbd73359f7ead254725",+ "bytes": 68747,+ "sha256": "159802e7810ef0f869c073c95d415109a747cbb96cc892672d0e6daeae624fbb","tools": ["tool_result_read","list_shared_computers",@@ -1513,8 +1513,8 @@]},"default+no-computer-pick": {- "bytes": 61439,- "sha256": "ab0ff49c1e84c985c12814c904674ffb1522622ca1b1c3ca697051281fb8f133",+ "bytes": 61415,+ "sha256": "efb58a1eb5871b1ca0a4bf9a6b24c2183c81722ced1f15b583441a49833e77e7","tools": ["tool_result_read","list_room_targets",@@ -1574,8 +1574,8 @@]},"default+room": {- "bytes": 57447,- "sha256": "543f229ff9b5d322bbc458e65eebcae1d576d1a60c3baf46c13421c0a5b5a855",+ "bytes": 57423,+ "sha256": "3d8eb96e2a032e5a2b955f37d310e64daac9394895d5caa11aa0ed021f2c450b","tools": ["tool_result_read","list_room_targets",@@ -1628,8 +1628,8 @@]},"non-chief+room": {- "bytes": 48899,- "sha256": "21cfd9b34601859a8673c3463d94cb0d69cbd082a4484e4e3d5aaff2bf7d29ac",+ "bytes": 48875,+ "sha256": "c479a60408b75d3f1f8ee3c2c69bb25a119fb2da4159f0de382edb0b82cb02cc","tools": ["tool_result_read","list_room_targets",@@ -1675,8 +1675,8 @@]},"default+images": {- "bytes": 64598,- "sha256": "83f78d6ceff824e2fd0be03b0e38f11f67c9cde51d6aee24fe033e9018781fca",+ "bytes": 64574,+ "sha256": "456b7ce643be455dfda224876ec8f018add09f21bd31cd620ed42008900a219b","tools": ["tool_result_read","list_room_targets",@@ -1739,8 +1739,8 @@]},"skills+shared+voice+x+team+images+hosting": {- "bytes": 75830,- "sha256": "cdf18449a80b38b102349a3fb62d39aeb8e6366fd20e86604c35fab426369977",+ "bytes": 75806,+ "sha256": "cb1179a38ed948224d5c5b6393d51f091c32d3f9362a81a06da9ede620b2abe3","tools": ["tool_result_read","list_shared_computers",@@ -1814,8 +1814,8 @@]},"default+hosting": {- "bytes": 64575,- "sha256": "b0b0eba268fdd815ded8006553c9dee21b0ee0869d42d11b615615c8a71a1683",+ "bytes": 64551,+ "sha256": "b9a73680385e16c810d424f52446049fcf19681b41113a799c345a59ef42e5ac","tools": ["tool_result_read","list_room_targets",@@ -1878,8 +1878,8 @@]},"skills+shared+voice+x+team+board": {- "bytes": 74014,- "sha256": "a73df664fd385920e40d7963206b254b4c9199feedfe95bfdb21a6e67aa5c1ae",+ "bytes": 73990,+ "sha256": "b6e4fff5ff94e61f50a16692e52c5c272dc5969f7bcb261ca469b799535473fa","tools": ["tool_result_read","list_shared_computers",@@ -1952,8 +1952,8 @@]},"default+room+board": {- "bytes": 59502,- "sha256": "8fc54d373404b531552b6f32b96830db205c78b25d9ba90b76ac521d847a4138",+ "bytes": 59478,+ "sha256": "aa77140c54cdaef028008f3dbe2ec82d28716e323060467d69bc2363b6dc6e4a","tools": ["tool_result_read","list_room_targets",diff --git a/server/host/connector-gate-host.test.ts b/server/host/connector-gate-host.test.tsnew file mode 100644index 0000000000..2572678491--- /dev/null+++ b/server/host/connector-gate-host.test.ts@@ -0,0 +1,47 @@+// Which installation a call made outside a turn goes to, with a fake connected-apps module: nothing leaves this process.+import { describe, expect, it, vi } from "vitest";++import type { AppConfig } from "../config.ts";+import type { PersonAppsAccess } from "../team-connections.ts";+import { createConnectorGateApps, type ConnectorGateAppsDeps } from "./connector-gate-host.ts";++function fixture(personApps: string[] = []) {+ const relayed: Array<{ cfg: AppConfig; as: unknown }> = [];+ const composio = {+ configured: () => true,+ connectedServices: vi.fn(async () => ({})),+ sharedConnectedInventory: vi.fn(async () => ({ services: { gmail: { connected: true } }, complete: true })),+ connectedServiceSlugs: vi.fn(async () => ["gmail"]),+ listConnectorTools: vi.fn(async () => ({ gmail: [{ name: "GMAIL_FETCH_EMAILS", readOnly: true as const }, { name: "GMAIL_SEND_EMAIL" }] })),+ relayMcp: vi.fn(async (cfg: AppConfig, _payload: unknown, _session?: string, _before?: unknown, _signal?: AbortSignal, as?: unknown) => {+ relayed.push({ cfg, as });+ return { status: 200, bytes: new Uint8Array(), contentType: "application/json" };+ }),+ } as unknown as ConnectorGateAppsDeps["composio"];+ const ada = { installationId: "inst-ada", token: "t".repeat(64), brokerUrl: "https://broker.example" } as unknown as PersonAppsAccess;+ const apps = createConnectorGateApps({ cfg: () => ({}), composio, personApps: () => personApps, appsAccess: (person) => (person === "ada" ? ada : null), policyRefusal: () => undefined });+ return { apps, composio, relayed };+}++describe("the connector gate's installations", () => {+ it("sends an app every person shares to this computer's installation, and reads which tools only read from its listing", async () => {+ const { apps, relayed } = fixture();+ const shared = apps.installation("ada", "gmail")!;+ expect(shared.id).toBe("shared");+ expect([...await shared.readOnlyTools()]).toEqual(["GMAIL_FETCH_EMAILS"]);+ expect(await shared.connected()).toEqual({ gmail: { connected: true } });+ await shared.relay({ jsonrpc: "2.0" }, undefined, AbortSignal.timeout(1_000));+ expect(relayed).toEqual([{ cfg: {}, as: undefined }]);+ });++ it("sends an app each person connects to the calling person's own, and to nobody's without one", async () => {+ const { apps, relayed } = fixture(["gmail"]);+ expect(apps.installation(null, "gmail")).toBeNull();+ expect(apps.installation("bob", "gmail")).toBeNull();+ const own = apps.installation("ada", "gmail")!;+ expect(own.id).toBe("person:ada");+ await own.relay({ jsonrpc: "2.0" }, undefined, AbortSignal.timeout(1_000));+ expect(relayed[0]!.as).toBeDefined();+ expect(apps.installation("ada", "notion")!.id).toBe("shared");+ });+});diff --git a/server/host/connector-gate-host.ts b/server/host/connector-gate-host.tsnew file mode 100644index 0000000000..da2bc9d7d7--- /dev/null+++ b/server/host/connector-gate-host.ts@@ -0,0 +1,48 @@+// Where a call made outside a turn reaches the connected apps: this computer's or the team's installation, or, on a Team+// Cloud where each person connects an app for themselves, the calling person's own. Security: the person comes from the+// request's own session, never from the caller, and no key or token leaves the server.+import type * as Composio from "../composio.ts";+import type { AppConfig } from "../config.ts";+import type { AppInstallation, GateApps } from "../connector-gate.ts";+import { asPerson, type PersonAppsAccess } from "../team-connections.ts";++export interface ConnectorGateAppsDeps {+ cfg(): AppConfig;+ composio: Pick<typeof Composio, "configured" | "connectedServices" | "sharedConnectedInventory" | "connectedServiceSlugs" | "listConnectorTools" | "relayMcp">;+ /** The apps each person connects for themselves (only on a Team Cloud). */+ personApps(): readonly string[];+ appsAccess(person: string): PersonAppsAccess | null;+ policyRefusal(slugs: readonly string[], serviceSlugs: readonly string[]): string | undefined;+}++export function createConnectorGateApps(deps: ConnectorGateAppsDeps): GateApps {+ const { composio } = deps;+ // A tool's own listing is the same whoever connected its app, so the shared installation's listing is read for every call.+ const readOnlyTools = async () => new Set(Object.values(await composio.listConnectorTools(deps.cfg())).flat().filter((tool) => tool.readOnly).map((tool) => tool.name));+ return {+ configured: () => composio.configured(deps.cfg()),+ policyRefusal: deps.policyRefusal,+ installation(person, toolkit): AppInstallation | null {+ if (!deps.personApps().includes(toolkit)) {+ const cfg = deps.cfg();+ return {+ id: "shared",+ connected: async () => (await composio.sharedConnectedInventory(cfg)).services,+ serviceSlugs: () => composio.connectedServiceSlugs(cfg),+ readOnlyTools,+ relay: (frame, session, signal) => composio.relayMcp(cfg, frame as never, session, undefined, signal),+ };+ }+ const own = person ? deps.appsAccess(person) : null;+ if (!person || !own) return null;+ const [cfg, access] = asPerson(deps.cfg(), own);+ return {+ id: `person:${person}`,+ connected: () => composio.connectedServices(cfg, access),+ serviceSlugs: () => composio.connectedServiceSlugs(cfg, access),+ readOnlyTools,+ relay: (frame, session, signal) => composio.relayMcp(cfg, frame as never, session, undefined, signal, access),+ };+ },+ };+}diff --git a/server/index.ts b/server/index.tsindex cfec213724..8e12e899e1 100644--- a/server/index.ts+++ b/server/index.ts@@ -465,7 +465,7 @@ import { parseTriggerRequest, triggerTarget } from "./trigger-tools.ts"; importimport { appliesNow, directApply, UNDO_STALE, type DirectApply } from "./direct-apply.ts";import { createTeamMemoryRequests } from "./team-memory-requests.ts";import { createAgentCard } from "./chat-widgets.ts";-import { createChatAppRoutes, createChatApps, createChatAppsMcp } from "./routes/chat-apps.ts";+import { botApproval, createChatAppRoutes, createChatApps, createChatAppsMcp, createConnectorGate, createConnectorGateApps } from "./routes/chat-apps.ts";import { buildBotOverview, type BotOverview, connectedAppsFacts } from "./bot-overview.ts";import { ProfileRequestService } from "./profile-requests.ts"; import { browserProfileLabel } from "./bot-browser-profile.ts";import { ModelRequestService } from "./model-requests.ts";@@ -11938,7 +11938,7 @@ ROUTES.push(createBotMessageRoutes({}));const liveRoots = (threadId: string, botId: string | undefined) => { const bot = botId ? store.bot(botId) : store.botByThread(threadId); return bot ? messageFileRootsForThread(bot.id, threadId).filter((root) => root !== ATTACHMENTS_DIR) : null; }; const chatApps = createChatApps({ store, dataDir: DATA_DIR, liveRows: liveAppRows, liveRoots, paused: () => workspaceMaintenance.active || moveFreeze.frozen() });const chatAppsMcp = createChatAppsMcp({ store, apps: chatApps, dataDir: DATA_DIR, keys: mcpKeys, storedServers: () => cfg.mcpServers ?? {}, mountedServers: (bot) => teamConnections.engineMcp(bot), personMcp: teamConnections.personMcp, probeAs: (server) => mcpServersHost.probeAs(server), oauth: mcpOAuth });-ROUTES.push(createChatAppRoutes({ store, apps: chatApps, threadRefusal: cloudThreadRefusal, mcpRpc: chatAppsMcp.rpc, data: dataEngine, dataOff: (botId) => serverTurnedOff(store.bot(botId)?.toolsOff, "data"), threadVisible: (auth, threadId) => (auth.kind !== "session" || sessions.isLive(auth.session.id)) && visibleTo(viewerFor(auth)).thread(threadId) }));+const pageConnectors = { gate: createConnectorGate({ bot: (id) => store.bot(id) ?? undefined, apps: createConnectorGateApps({ cfg: () => cfg, composio, personApps: () => teamConnections.personApps(), appsAccess: (person) => teamConnections.people.appsAccess(person), policyRefusal: (slugs, serviceSlugs) => managedPolicy.appsCallRefusal(slugs.map((slug) => ({ slug })), serviceSlugs) }), servers: { open: chatAppsMcp.openServer }, decide: (row) => appendDecision(DATA_DIR, row) }), person: (auth: RequestAuth) => (CLOUD_TEAM && auth.kind === "session" ? personKey(auth.session) : null), mayAct: (auth: RequestAuth, botId: string) => ["chat", "edit"].includes(levelOf(auth, botId)), fullAccess: (botId: string, threadId: string) => botApproval(store, botId, threadId) === "full", confined: (threadId: string) => cloudGuestDriven(threadId) || proactive.fence.confines(threadId) }; ROUTES.push(createChatAppRoutes({ store, apps: chatApps, threadRefusal: cloudThreadRefusal, mcpRpc: chatAppsMcp.rpc, data: dataEngine, dataOff: (botId) => serverTurnedOff(store.bot(botId)?.toolsOff, "data"), threadVisible: (auth, threadId) => (auth.kind !== "session" || sessions.isLive(auth.session.id)) && visibleTo(viewerFor(auth)).thread(threadId), connectors: pageConnectors }));const roomReactionNotes = createRoomReactionNotes({ store }), { react } = createReactions({store, noted: roomReactionNotes.noted, inboxAnswer: (input) => teamMessages.reactedIn(input.auth, input.threadId, input.target.id, input.answer, { sendId: input.sendId, sender: messageSender(input.auth) }), reply: (input) => personReplies.deliver({ ...input, about: "message" }),answerCard: (input) => respondToCard({ ...input, via: "reaction" }), withdraw: personReplies.withdraw,diff --git a/server/outbound-hold.ts b/server/outbound-hold.tsindex 26ec888b3b..1fcf4f7ad3 100644--- a/server/outbound-hold.ts+++ b/server/outbound-hold.ts@@ -30,7 +30,7 @@ export type OutboundHoldAnswer = { ok: true; approved: boolean } | { ok: false;/** The rule a send goes out under without the card, or null when it waits on the card. At Full access a bot with no* sending rule of its own sends without asking; a stored rule is kept exactly as set. */-function sendsWithoutAsking(rule: OutboundPolicy | undefined, fullAccess: boolean, opaque: boolean): "full-access" | "allow" | null {+export function sendsWithoutAsking(rule: OutboundPolicy | undefined, fullAccess: boolean, opaque: boolean): "full-access" | "allow" | null {if (fullAccess && rule === undefined) return "full-access";// A call it cannot inspect (code run) goes out under "allow" only at Full access, as it would with no rule.return effectiveOutboundPolicy(rule, fullAccess).policy === "allow" && (!opaque || fullAccess) ? "allow" : null;diff --git a/server/routes/bot-page-connectors.test.ts b/server/routes/bot-page-connectors.test.tsnew file mode 100644index 0000000000..50a6370cfc--- /dev/null+++ b/server/routes/bot-page-connectors.test.ts@@ -0,0 +1,180 @@+// A bot's page calling the connector tools it declared, through its rpc route and the connector gate, against a fake+// connected-apps installation: nothing leaves this process.+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { rmSync } from "node:fs";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { createChatApps, type ChatApps } from "../chat-apps.ts";+import { DATA_DIR } from "../config.ts";+import { createConnectorGate, type AppInstallation } from "../connector-gate.ts";+import type { ModelSelection } from "../contracts.ts";+import type { DecisionRow } from "../decision-log.ts";+import { json, readBody } from "../harness/http.ts";+import type { RequestAuth } from "../request-auth.ts";+import { Store } from "../store.ts";+import { createChatAppRoutes, type ChatAppRouteDeps } from "./chat-apps.ts";+import { dispatchRoutes } from "./table.ts";++type Json = Record<string, unknown>;+const sonnet: ModelSelection = { instanceId: "claude", model: "claude-sonnet-5" };+const servers: Server[] = [];+const apps: ChatApps[] = [];++beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));+afterEach(async () => {+ for (const app of apps.splice(0)) app.close();+ await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));+});++/** One installation per person ("home" for the computer's own), each recording what it was sent. */+function installations() {+ const sent: Array<{ who: string; frame: Json }> = [];+ const make = (who: string): AppInstallation => ({+ id: who,+ connected: async () => ({ gmail: { connected: who !== "nobody", accounts: [{ id: `ca_${who}`, status: "ACTIVE" }] } }),+ serviceSlugs: async () => ["gmail"],+ readOnlyTools: async () => new Set(["GMAIL_FETCH_EMAILS"]),+ async relay(frame) {+ sent.push({ who, frame });+ if (frame.method !== "tools/call") return { status: 200, bytes: new TextEncoder().encode(JSON.stringify({ jsonrpc: "2.0", id: frame.id, result: {} })) };+ const slug = (frame.params as { arguments: { tools: Array<{ tool_slug: string }> } }).arguments.tools[0]!.tool_slug;+ const body = { successful: true, data: { results: [{ tool_slug: slug, response: { successful: true, data: { messages: [{ id: `${who}-1` }] } } }] } };+ return { status: 200, bytes: new TextEncoder().encode(JSON.stringify({ jsonrpc: "2.0", id: frame.id, result: { content: [{ type: "text", text: JSON.stringify(body) }] } })) };+ },+ });+ return { sent, make, calls: () => sent.filter((one) => one.frame.method === "tools/call") };+}++async function fixture(options: { threadVisible?: ChatAppRouteDeps["threadVisible"]; threadRefusal?: ChatAppRouteDeps["threadRefusal"]; mayAct?: (auth: RequestAuth) => boolean; full?: boolean; confined?: (threadId: string) => boolean } = {}) {+ const store = new Store(() => sonnet);+ const bot = store.createBot({ name: "Scout" });+ const other = store.createBot({ name: "Other" });+ const chatApps = createChatApps({ store, dataDir: DATA_DIR, sweeps: false });+ apps.push(chatApps);+ const fake = installations();+ const rows: Array<Omit<DecisionRow, "at">> = [];+ const gate = createConnectorGate({+ bot: (id) => store.bot(id) ?? undefined,+ // Each person connects Gmail for themselves here, so a call goes to the caller's own installation.+ apps: { configured: () => true, installation: (person) => fake.make(person ?? "home"), policyRefusal: () => undefined },+ decide: (row) => rows.push(row), log: () => {},+ });+ const routes = [createChatAppRoutes({+ store, apps: chatApps,+ ...(options.threadVisible ? { threadVisible: options.threadVisible } : {}),+ ...(options.threadRefusal ? { threadRefusal: options.threadRefusal } : {}),+ connectors: {+ gate,+ person: (auth) => (auth.kind === "session" ? auth.session.id : null),+ mayAct: (auth) => options.mayAct?.(auth) ?? true,+ fullAccess: () => options.full === true,+ ...(options.confined ? { confined: options.confined } : {}),+ },+ })];+ const server = createServer(async (req, res) => {+ const url = new URL(req.url ?? "/", "http://localhost");+ const person = req.headers["x-session"];+ const auth = (typeof person === "string"+ ? { kind: "session", session: { id: person, email: `${person}@example.com` }, via: "bearer", scopes: ["client"] }+ : { kind: "loopback", scopes: ["admin", "client"] }) as RequestAuth;+ try {+ if (!await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody })) json(res, 404, { from: "inline routes" });+ } catch (error) {+ json(res, 500, { error: error instanceof Error ? error.message : String(error) });+ }+ });+ servers.push(server);+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ const show = (input: Json, who = bot, threadId = who.threadId) => {+ const result = chatApps.createAppCard({ bot: who, threadId, input: { tool: "show_html", html: "<p>Mail</p>", title: "Mail", ...input } });+ if (result instanceof Promise || !result.ok) throw new Error(`not shown: ${JSON.stringify(result)}`);+ return result.messageId;+ };+ const rpc = async (id: string, method: string, params?: unknown, who = bot, threadId = bot.threadId, session?: string) => {+ const response = await fetch(`${base}/api/bots/${who.id}/apps/${id}/rpc`, {+ method: "POST", headers: { "content-type": "application/json", ...(session ? { "x-session": session } : {}) }, body: JSON.stringify({ threadId, method, ...(params === undefined ? {} : { params }) }),+ });+ return { status: response.status, body: await response.json() as Record<string, any> };+ };+ return { store, bot, other, chatApps, show, rpc, fake, rows };+}++const READ = { connector: "gmail", tool: "GMAIL_FETCH_EMAILS", arguments: { max_results: 2 }, engaged: false };++describe("mausbot.connectors on the rpc route", () => {+ it("answers a declared read with the viewer's own connection, and lists the declared tools", async () => {+ const { show, rpc, fake, rows } = await fixture();+ const id = show({ uses: ["gmail:GMAIL_FETCH_EMAILS", "gmail:GMAIL_TRASH_MESSAGE"] });+ expect(await rpc(id, "mausbot/connectors/call", READ, undefined, undefined, "ada")).toEqual({ status: 200, body: { result: { messages: [{ id: "ada-1" }] } } });+ expect(await rpc(id, "mausbot/connectors/call", READ)).toEqual({ status: 200, body: { result: { messages: [{ id: "home-1" }] } } });+ // The person and the account come from the request and the server, never from what the page sent.+ expect(await rpc(id, "mausbot/connectors/call", { ...READ, person: "bob", account: "ca_bob", arguments: { max_results: 2 } }, undefined, undefined, "ada")).toMatchObject({ status: 200 });+ expect(fake.calls().map((one) => [one.who, (one.frame.params as any).arguments.tools])).toEqual([+ ["ada", [{ tool_slug: "GMAIL_FETCH_EMAILS", arguments: { max_results: 2 } }]],+ ["home", [{ tool_slug: "GMAIL_FETCH_EMAILS", arguments: { max_results: 2 } }]],+ ["ada", [{ tool_slug: "GMAIL_FETCH_EMAILS", arguments: { max_results: 2 } }]],+ ]);+ expect(rows.map((row) => [row.summary, row.decision])).toEqual([[`page ${id}: ran (gmail)`, "auto-approved"], [`page ${id}: ran (gmail)`, "auto-approved"], [`page ${id}: ran (gmail)`, "auto-approved"]]);+ expect(await rpc(id, "mausbot/connectors/list", {}, undefined, undefined, "nobody")).toEqual({ status: 200, body: {+ connectors: [{ connector: "gmail", label: "Gmail", connected: false, tools: ["GMAIL_FETCH_EMAILS", "GMAIL_TRASH_MESSAGE"] }],+ } });+ });++ it("refuses a tool the page did not declare, a page that declared none, and a change without Full access or a click", async () => {+ const { show, rpc, fake } = await fixture();+ const plain = show({ uses: ["data"] });+ expect(await rpc(plain, "mausbot/connectors/call", READ)).toEqual({ status: 409, body: { error: { code: -32000, message: 'This page declared no connector tools: show it with uses naming each tool, e.g. ["gmail:GMAIL_FETCH_EMAILS"].' } } });+ const id = show({ uses: ["gmail:GMAIL_TRASH_MESSAGE"] });+ expect((await rpc(id, "mausbot/connectors/call", READ)).body.error.message).toBe('This page did not declare GMAIL_FETCH_EMAILS: list "gmail:GMAIL_FETCH_EMAILS" in show_html uses to call it.');+ const trash = { connector: "gmail", tool: "GMAIL_TRASH_MESSAGE", arguments: { id: "m1" }, engaged: true };+ expect(await rpc(id, "mausbot/connectors/call", trash)).toMatchObject({ status: 403, body: { error: { message: expect.stringContaining("Scout asks before it changes anything") } } });+ const full = await fixture({ full: true });+ const page = full.show({ uses: ["gmail:GMAIL_TRASH_MESSAGE"] });+ expect(await full.rpc(page, "mausbot/connectors/call", { ...trash, engaged: false })).toMatchObject({ status: 403, body: { error: { message: "This changes something in Gmail, so it runs only right after the person clicks in this page." } } });+ expect((await full.rpc(page, "mausbot/connectors/call", trash)).status).toBe(200);+ expect(fake.calls()).toEqual([]);+ });++ it("keeps a page's declared tools across a version that says nothing of uses, and drops them with one that does", async () => {+ const { bot, show, rpc, chatApps } = await fixture();+ const id = show({ uses: ["gmail:GMAIL_FETCH_EMAILS"] });+ show({ tool: "update_html", app_id: id, html: "<p>Mail 2</p>" });+ expect(chatApps.declaredConnectors(bot.threadId, id)).toEqual([{ connector: "gmail", tools: ["GMAIL_FETCH_EMAILS"] }]);+ expect((await rpc(id, "mausbot/connectors/call", READ)).status).toBe(200);+ show({ tool: "update_html", app_id: id, html: "<p>Mail 3</p>", uses: ["state"] });+ expect(chatApps.declaredConnectors(bot.threadId, id)).toEqual([]);+ expect((await rpc(id, "mausbot/connectors/call", READ)).status).toBe(409);+ const doc = chatApps.appDocument(bot.threadId, id);+ expect(doc?.can.connectors).toBeUndefined();+ show({ tool: "update_html", app_id: id, html: "<p>Mail 4</p>", uses: ["gmail:GMAIL_FETCH_EMAILS"] });+ expect(chatApps.appDocument(bot.threadId, id)?.can.connectors).toEqual([{ connector: "gmail", tools: ["GMAIL_FETCH_EMAILS"] }]);+ });++ it("is refused to another bot's page, another conversation, a room, a viewer who cannot see the conversation or may not chat with the bot, and a guest", async () => {+ const outsider = (auth: RequestAuth) => auth.kind !== "session" || auth.session.id !== "outsider";+ const { store, bot, other, show, rpc, fake } = await fixture({+ threadVisible: outsider, mayAct: (auth) => auth.kind !== "session" || auth.session.id !== "reader",+ threadRefusal: (auth) => (auth.kind === "session" && auth.session.id === "guest" ? "A guest changes only conversations it started." : null),+ });+ const id = show({ uses: ["gmail:GMAIL_FETCH_EMAILS"] });+ const home = bot.threadId;+ expect((await rpc(id, "mausbot/connectors/call", READ, other, other.threadId)).status).toBe(404);+ expect((await rpc(id, "mausbot/connectors/call", READ, other, home)).status).toBe(404);+ const second = store.createTask(bot.id)!;+ expect((await rpc(id, "mausbot/connectors/call", READ, bot, second.threadId)).status).toBe(404);+ const room = store.createGroup("Launch", [bot.id, other.id]);+ const inRoom = show({ uses: ["gmail:GMAIL_FETCH_EMAILS"] }, bot, room.threadId);+ expect(await rpc(inRoom, "mausbot/connectors/call", READ, bot, room.threadId)).toEqual({ status: 409, body: { error: { code: -32000, message: "In a room, a page cannot call connected apps." } } });+ expect(await rpc(id, "mausbot/connectors/call", READ, bot, home, "outsider")).toEqual({ status: 404, body: { error: "no such conversation" } });+ expect(await rpc(id, "mausbot/connectors/list", {}, bot, home, "outsider")).toEqual({ status: 404, body: { error: "no such conversation" } });+ expect(await rpc(id, "mausbot/connectors/list", {}, bot, home, "reader")).toEqual({ status: 403, body: { error: { code: -32000, message: "Only someone who can chat with Scout can use this page's connected apps." } } });+ expect((await rpc(id, "mausbot/connectors/call", READ, bot, home, "guest")).status).toBe(403);+ expect(fake.sent).toEqual([]);+ const confined = await fixture({ confined: () => true });+ expect(await confined.rpc(confined.show({ uses: ["gmail:GMAIL_FETCH_EMAILS"] }), "mausbot/connectors/call", READ))+ .toEqual({ status: 403, body: { error: { code: -32000, message: "In this conversation, pages cannot use connected apps." } } });+ expect(confined.fake.sent).toEqual([]);+ });+});diff --git a/server/routes/bot-page-rpc.ts b/server/routes/bot-page-rpc.tsindex 9e9ffe2aa0..cd1a7d7823 100644--- a/server/routes/bot-page-rpc.ts+++ b/server/routes/bot-page-rpc.ts@@ -1,13 +1,15 @@-// mausbot.data and mausbot.state for a bot's own page, on its rpc route once the route has checked the bot, the-// conversation and the row. Each answers only for what the page's current version declared (show_html `uses`).-import { APP_LIMITS, type AppUse } from "../../shared/app.ts";-import { pageUseRefusal, RPC_HOST_REFUSED, RPC_INVALID_PARAMS, type PageRpcMethod } from "../../shared/app-frame/bridge.ts";+// mausbot.data, mausbot.state and mausbot.connectors for a bot's own page, on its rpc route once the route has checked the+// bot, the conversation and the row. Each answers only for what the page's current version declared (show_html `uses`).+import { APP_LIMITS } from "../../shared/app.ts";+import { pageConnectorTarget, pageMethodUse, pageUseRefusal, RPC_HOST_REFUSED, RPC_INVALID_PARAMS, type PageRpcMethod } from "../../shared/app-frame/bridge.ts";import type { ChatApps } from "../chat-apps.ts";+import type { ConnectorGate } from "../connector-gate.ts";import { boundRows } from "../data/tools.ts";import { DataFailure, type DataEngine, type RunResult } from "../data/types.ts";export interface PageRpcDeps {- apps: Pick<ChatApps, "declaredUses" | "states" | "paused">;+ apps: Pick<ChatApps, "declaredUses" | "declaredConnectors" | "states" | "paused">;+ connectors?: ConnectorGate;data?: Pick<DataEngine, "unavailable" | "forBot">;/** True when the person switched this bot's Data tools off. */dataOff?(botId: string): boolean;@@ -89,8 +91,34 @@ async function query(deps: PageRpcDeps, botId: string, params: Record<string, un}}-export async function pageRpc(deps: PageRpcDeps, call: { botId: string; threadId: string; messageId: string; method: PageRpcMethod; params: Record<string, unknown> }): Promise<PageRpcAnswer> {- const use: AppUse = call.method === "mausbot/data/query" ? "data" : "state";+/** Who is looking at the page: the person whose own connections its connector calls use, and whether the bot runs changes+ * without asking in this conversation. */+export interface PageViewer {+ person: string | null;+ fullAccess(): boolean;+}++async function connectors(deps: PageRpcDeps, call: PageCall): Promise<PageRpcAnswer> {+ const declared = deps.apps.declaredConnectors(call.threadId, call.messageId);+ if (!declared.length) return refuse(409, pageUseRefusal("connectors", false));+ if (!deps.connectors || !call.viewer) return refuse(503, "This page cannot reach connected apps on this computer.");+ const caller = {+ botId: call.botId, person: call.viewer.person, declared, fullAccess: call.viewer.fullAccess, engaged: call.params.engaged === true,+ audit: { label: `page ${call.messageId}`, key: `${call.threadId}:${call.messageId}`, threadId: call.threadId },+ };+ if (call.method === "mausbot/connectors/list") return answer({ connectors: await deps.connectors.list(caller) });+ const target = pageConnectorTarget(call.params, declared);+ if (!target) return refuse(400, "mausbot.connectors.call needs (connector or server, tool name, arguments object).", RPC_INVALID_PARAMS);+ const result = await deps.connectors.call(caller, target, call.params.arguments);+ if (!result.ok) return refuse(result.status, result.message, result.status === 400 ? RPC_INVALID_PARAMS : RPC_HOST_REFUSED);+ return answer({ result: result.result, ...(result.truncated ? { truncated: true } : {}) });+}++type PageCall = { botId: string; threadId: string; messageId: string; method: PageRpcMethod; params: Record<string, unknown>; viewer?: PageViewer };++export async function pageRpc(deps: PageRpcDeps, call: PageCall): Promise<PageRpcAnswer> {+ const use = pageMethodUse(call.method);+ if (use === "connectors") return connectors(deps, call);if (!deps.apps.declaredUses(call.threadId, call.messageId).includes(use)) return refuse(409, pageUseRefusal(use, false));if (call.method === "mausbot/data/query") return query(deps, call.botId, call.params);const { states } = deps.apps;diff --git a/server/routes/chat-apps.ts b/server/routes/chat-apps.tsindex 55ac2e1c0c..b3602c0076 100644--- a/server/routes/chat-apps.ts+++ b/server/routes/chat-apps.ts@@ -1,7 +1,8 @@import { APP_LIMITS, ROOM_VIEW_ONLY, type AppPayload } from "../../shared/app.ts";-import { APP_RPC_METHODS, PAGE_RPC_METHODS, pageUseRefusal, RPC_HOST_REFUSED, type AppRpcMethod, type PageRpcMethod } from "../../shared/app-frame/bridge.ts";+import { APP_RPC_METHODS, PAGE_RPC_METHODS, pageMethodUse, pageUseRefusal, RPC_HOST_REFUSED, type AppRpcMethod, type PageRpcMethod } from "../../shared/app-frame/bridge.ts";import { webOrigin } from "../../shared/app-frame/csp.ts";import { appRow, createChatApps, rowRate, type ChatApps } from "../chat-apps.ts";+import type { ConnectorGate } from "../connector-gate.ts";import type { DataEngine } from "../data/types.ts";import { messageFileDisposition } from "../message-file.ts";import type { RequestAuth } from "../request-auth.ts";@@ -11,7 +12,9 @@ import { pageRpc } from "./bot-page-rpc.ts";import { PASS, type RouteHandler } from "./table.ts";export { createChatApps };-export { createChatAppsMcp } from "../chat-apps-mcp.ts";+export { botApproval, createChatAppsMcp } from "../chat-apps-mcp.ts";+export { createConnectorGate } from "../connector-gate.ts";+export { createConnectorGateApps } from "../host/connector-gate-host.ts";export interface McpRpcRequest {auth: RequestAuth;@@ -41,6 +44,18 @@ export interface ChatAppRouteDeps {data?: Pick<DataEngine, "unavailable" | "forBot">;/** True when the person switched this bot's Data tools off. */dataOff?(botId: string): boolean;+ /** The connector tools a bot's page declared, called with the viewer's own connections. */+ connectors?: {+ gate: ConnectorGate;+ /** Whose own connections the viewer's calls use, where each person connects their own; null elsewhere. */+ person(auth: RequestAuth): string | null;+ /** May this viewer have the bot act: a viewer who may only read its conversations may not. */+ mayAct(auth: RequestAuth, botId: string): boolean;+ /** Would a turn of this bot in this conversation run a change without asking. */+ fullAccess(botId: string, threadId: string): boolean;+ /** A conversation whose turns are confined (a guest's, a read-and-draft run's): its pages call no connected apps. */+ confined?(threadId: string): boolean;+ };}const DOCUMENT = /^\/api\/threads\/([\w-]+)\/messages\/([\w-]+)\/app(\/download)?$/;@@ -108,7 +123,7 @@ export function createChatAppRoutes(deps: ChatAppRouteDeps): RouteHandler {(PAGE_RPC_METHODS as readonly string[]).includes(body.method);if (store.groupByThread(threadId)) {return json(res, 409, pageCall(appRow(store, threadId, messageId))- ? { error: { code: RPC_HOST_REFUSED, message: pageUseRefusal("data", true) } } : { error: ROOM_VIEW_ONLY });+ ? { error: { code: RPC_HOST_REFUSED, message: pageUseRefusal(pageMethodUse(body.method as PageRpcMethod), true) } } : { error: ROOM_VIEW_ONLY });}if (!store.taskByThread(bot.id, threadId)) return json(res, 404, { error: "no such conversation" });const refused = deps.threadRefusal?.(auth, threadId);@@ -127,9 +142,20 @@ export function createChatAppRoutes(deps: ChatAppRouteDeps): RouteHandler {if (pageMethod) {if (body.params !== undefined && !isRecord(body.params)) return json(res, 400, { error: "params must be an object" });+ const connectorCall = pageMethodUse(body.method as PageRpcMethod) === "connectors";+ const linked = deps.connectors;+ if (connectorCall && linked && !linked.mayAct(auth, bot.id)) {+ return json(res, 403, { error: { code: RPC_HOST_REFUSED, message: `Only someone who can chat with ${bot.name} can use this page's connected apps.` } });+ }+ if (connectorCall && linked?.confined?.(threadId)) {+ return json(res, 403, { error: { code: RPC_HOST_REFUSED, message: "In this conversation, pages cannot use connected apps." } });+ }if (!pageRate.take(`${threadId}:${row.id}`)) return json(res, 429, { error: { code: -32000, message: "Too many calls from this page. Wait a moment." } });- const answer = await pageRpc({ apps, ...(deps.data ? { data: deps.data } : {}), ...(deps.dataOff ? { dataOff: deps.dataOff } : {}) }, {+ const answer = await pageRpc({+ apps, ...(deps.data ? { data: deps.data } : {}), ...(deps.dataOff ? { dataOff: deps.dataOff } : {}), ...(linked ? { connectors: linked.gate } : {}),+ }, {botId: bot.id, threadId, messageId: row.id, method: body.method as PageRpcMethod, params: isRecord(body.params) ? body.params : {},+ ...(connectorCall && linked ? { viewer: { person: linked.person(auth), fullAccess: () => linked.fullAccess(bot.id, threadId) } } : {}),});return json(res, answer.status, answer.body);}diff --git a/server/skill-library.test.ts b/server/skill-library.test.tsindex 19582274b2..bd64946faa 100644--- a/server/skill-library.test.ts+++ b/server/skill-library.test.ts@@ -151,6 +151,30 @@ describe("bundled data-dashboards skill", () => {});});+describe("bundled connected-app-pages skill", () => {+ const skills = loadBundledSkills(join(process.cwd(), "skills"));+ const guide = skills.find((skill) => skill.manifest.id === "connected-app-pages")?.instructions ?? "";+ const ids = (text: string) => selectBundledSkills(text, [], skills).map((skill) => skill.manifest.id);++ it("mounts for a page or mini app over the person's own apps, and stays out of other turns", () => {+ for (const text of ["Make me a mini app for my inbox", "build a page that lists my open GitHub issues", "an app that shows my calendar this week"]) {+ expect(ids(text), text).toContain("connected-app-pages");+ }+ for (const text of ["summarize this email", "book a call for Friday", "Build me a sales dashboard", "fix the typo in my biography"]) {+ expect(ids(text), text).not.toContain("connected-app-pages");+ }+ });++ it("teaches the declaration and the page calls, with one worked example that reads and one button that changes", () => {+ expect(guide).toContain('"gmail:GMAIL_FETCH_EMAILS"');+ expect(guide).toContain('"mcp:notes:search"');+ expect(guide).toContain("mausbot.connectors.list()");+ expect(guide).toContain("mausbot.connectors.call(");+ expect(guide).toContain("a page someone shares never\ncarries an account");+ expect(guide.match(/```html/g)).toHaveLength(1);+ });+});+describe("bundled phone-connection skill", () => {const skills = loadBundledSkills(join(process.cwd(), "skills"));const guide = skills.find((skill) => skill.manifest.id === "phone-connection")?.instructions ?? "";diff --git a/shared/app-frame/app-host.html b/shared/app-frame/app-host.htmlindex 3a5880a3e2..4863df20c9 100644--- a/shared/app-frame/app-host.html+++ b/shared/app-frame/app-host.html@@ -1,10 +1,10 @@-<!-- mausbot app-host v1 sha256:b2cb1ac587a54f7761c87052234c219d47e0249dd38b6e015eb7b212d392c22e -->+<!-- mausbot app-host v1 sha256:5a7eda35e9359dca4a7a4556663a65439a861c8c7e976cbfef77ec34274f25ac --><!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"><meta name="color-scheme" content="light dark"><title>App</title><style>html,body{margin:0;padding:0;background:transparent;overflow:hidden}iframe{display:block;width:100%;border:0;background:transparent}</style></head><body>-<script id="mausbot-app-host">(()=>{var B="2026-01-26";var H={htmlBytes:262144,title:80,fallback:1500,fallbackExcerpt:600,heightMin:80,heightMax:720,messageText:4e3,contextText:4e3,doneText:300,mcpHtmlBytes:2097152,rpcArgumentsBytes:65536,rpcResourceBytes:8388608,messagesPerHour:20,rpcPerMinute:60,pageQueryRows:5e3,pageQueryBytes:1e6,pageQuerySqlChars:2e4,pageQueryMs:1e4,pageStateKeyChars:200,pageStateValueBytes:65536,pageStateBytes:262144,pageStateKeys:200};var I="In a room, pages, apps and widgets are view-only: they cannot send messages or tell a bot what anyone sees.";function $(e){let n=0;for(let i=0;i<e.length;i+=1){let p=e.charCodeAt(i);if(p<128)n+=1;else if(p<2048)n+=2;else if(p>=55296&&p<=56319&&i+1<e.length){let l=e.charCodeAt(i+1);l>=56320&&l<=57343?(n+=4,i+=1):n+=3}else n+=3}return n}var J=["tools/call","tools/list","resources/read","resources/list"],U=["mausbot/data/query","mausbot/state/get","mausbot/state/set","mausbot/state/keys"];var f={messageBytes:1e6,minHeight:48,defaultHeight:160,maxHeight:720,linkChars:2048,teardownMs:1e3,engagedTouchMs:1e4,contextCoalesceMs:1e3,logsPerMinute:50,rates:{message:[[3e3,1],[6e5,10]],openLink:[[2e3,1]],rpc:[[1e4,10],[6e5,120]]}};function ee(e){let n=F(e);return{...e.can.openLinks?{openLinks:{}}:{},logging:{},...e.can.modelContext?{updateModelContext:{text:{},structuredContent:{}}}:{},...e.can.message?{message:{text:{}}}:{},...n&&e.can.serverTools?{serverTools:{}}:{},...n&&e.can.serverResources?{serverResources:{}}:{},sandbox:{permissions:{},csp:{connectDomains:[...e.network.connect],resourceDomains:[...e.network.resources]}}}}function F(e){return!!e.tool}function M(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function q(e){return typeof e=="string"&&e.length<=200||typeof e=="number"&&Number.isFinite(e)}function te(e){let n;try{n=JSON.stringify(e)}catch{return null}return n===void 0?null:n.length*3<=f.messageBytes?n.length:$(n)}function ne(e){if(!M(e)||e.jsonrpc!=="2.0")return null;let n=te(e);return n===null||n>f.messageBytes||e.params!==void 0&&!M(e.params)?null:typeof e.method=="string"?!e.method||e.method.length>200||"id"in e&&!q(e.id)?null:e:e.method!==void 0||!q(e.id)?null:"result"in e||M(e.error)&&typeof e.error.code=="number"&&typeof e.error.message=="string"?e:null}function S(e,n){let i=[],p=Math.max(...e.map(([l])=>l));return{take(){let l=n();for(;i.length&&l-i[0]>=p;)i.shift();for(let[g,d]of e)if(i.filter(w=>l-w<g).length>=d)return!1;return i.push(l),!0}}}function E(e){return M(e)&&typeof e.code=="number"&&Number.isInteger(e.code)?{code:e.code,message:typeof e.message=="string"&&e.message?e.message:"The host refused this."}:{code:-32e3,message:e instanceof Error&&e.message?e.message:"The host could not do that."}}function re(e){if(typeof e!="string"||!e||e.length>f.linkChars)return null;let n;try{n=new URL(e)}catch{return null}return n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password?null:n.href.length<=f.linkChars?n.href:null}function oe(e,n){return n?"In a room, a page cannot read its bot's data or keep state.":`This page did not declare "${e}": show it with uses: ["${e}"] to ${e==="data"?"read its bot's data":"keep state"}.`}function se(e,n){let i=p=>typeof p=="string"&&p.length>0&&p.length<=H.pageStateKeyChars;switch(e){case"mausbot/data/query":return typeof n.sql!="string"||!n.sql.trim()||n.sql.length>H.pageQuerySqlChars?`mausbot.data.query needs one SELECT of at most ${H.pageQuerySqlChars} characters.`:n.params===void 0||Array.isArray(n.params)||M(n.params)?null:"mausbot.data.query params: a list for ? or $1, or an object for $name.";case"mausbot/state/get":case"mausbot/state/set":return i(n.key)?null:`A state key is text of 1 to ${H.pageStateKeyChars} characters.`;case"mausbot/state/keys":return null}}function ie(e){if(!e||e.role!=="user"||!Array.isArray(e.content)||e.content.length===0)return null;let n=[];for(let p of e.content){if(!M(p)||p.type!=="text"||typeof p.text!="string")return null;n.push(p.text)}let i=n.join(`-`).trim();return i&&i.length<=H.messageText?i:null}function z(e){let{doc:n,adapter:i}=e,p=F(n),l=e.timers??{set:(t,a)=>setTimeout(t,a),clear:t=>clearTimeout(t)},g=()=>i.now(),d={...e.hostContext,...p&&n.tool?{toolInfo:{tool:n.tool}}:{}},w=null,P=!1,y=!1,k=!1,C=!1,O=0,v=new Map,h={message:S(f.rates.message,g),openLink:S(f.rates.openLink,g),rpc:S(f.rates.rpc,g),log:S([[6e4,f.logsPerMinute]],g)},b=null,r=null,u=-1/0,m=t=>{if(!k)try{i.post(t)}catch{}},R=(t,a)=>m({jsonrpc:"2.0",id:t,result:a}),s=(t,a,o)=>m({jsonrpc:"2.0",id:t,error:{code:a,message:o}}),j=()=>{let t=e.limits?.maxHeight,a=d.containerDimensions?.maxHeight,o=typeof t=="number"&&t>0?t:typeof a=="number"&&a>0?a:f.maxHeight;return Math.max(f.minHeight,o)},N=()=>{if(r=null,k||!b)return;let t=b;b=null,u=g(),Promise.resolve().then(()=>i.setContext(t)).catch(()=>{})},Q=async()=>{if(r===null||!b)return;l.clear(r),r=null;let t=b;b=null,u=g();try{await i.setContext(t)}catch{}},K=()=>{if(p&&!C&&(C=!0,m({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:n.toolInput??{}}}),m({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:n.toolResult??{content:[]}})),w){let t=w;w=null,m({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:t})}},G=async(t,a,o)=>{if(!p)return s(t,-32601,"Method not found");if(!(a.startsWith("tools/")?n.can.serverTools:n.can.serverResources))return s(t,-32e3,n.room?I:n.blocked?.text??"This app cannot reach its server right now.");if(a==="tools/call"&&(typeof o.name!="string"||!o.name||o.arguments!==void 0&&!M(o.arguments)))return s(t,-32602,"tools/call needs {name, arguments?}.");if(a==="resources/read"&&typeof o.uri!="string")return s(t,-32602,"resources/read needs {uri}.");if(!h.rpc.take())return s(t,-32e3,"Too many calls from this app. Wait a moment.");try{let A=await i.callRpc(a,o);R(t,A??{})}catch(A){let T=E(A);s(t,T.code,T.message)}},Y=async(t,a,o)=>{if(p)return s(t,-32601,"Method not found");let c=a==="mausbot/data/query"?"data":"state";if(!n.can[c])return s(t,-32e3,oe(c,!!n.room));let A=se(a,o);if(A)return s(t,-32602,A);if(!h.rpc.take())return s(t,-32e3,"Too many calls from this page. Wait a moment.");try{R(t,await i.callRpc(a,o)??{})}catch(T){let D=E(T);s(t,D.code,D.message)}},X=async(t,a,o)=>{if(a==="ui/initialize")return P=!0,R(t,{protocolVersion:B,hostInfo:{name:"mausbot",version:e.hostVersion},hostCapabilities:ee(n),hostContext:d});if(y)switch(a){case"ping":return R(t,{});case"ui/request-display-mode":return R(t,{mode:"inline"});case"ui/open-link":{if(!n.can.openLinks)return s(t,-32e3,"This app cannot open links here.");if(!i.engaged())return s(t,-32e3,"Links open only after the person clicks in the app.");let c=re(o?.url);if(!c)return s(t,-32602,"Only http and https links of at most 2,048 characters, without a user name or password, can be opened.");if(!h.openLink.take())return s(t,-32e3,"Too many links from this app. Wait a moment.");try{return await i.openLink(c),R(t,{})}catch(A){return s(t,-32e3,E(A).message)}}case"ui/message":{if(!n.can.message)return s(t,-32e3,n.room?I:"This app cannot send messages here.");if(!i.engaged())return s(t,-32e3,"Messages are sent only after the person clicks in the app.");let c=ie(o);if(c===null)return s(t,-32602,`Only text messages of 1 to ${H.messageText} characters can be sent.`);if(!h.message.take())return s(t,-32e3,"Too many messages from this app. Wait a moment.");try{return await Q(),await i.sendMessage(c),R(t,{})}catch(A){return s(t,-32e3,E(A).message)}}case"ui/update-model-context":{if(!n.can.modelContext)return s(t,-32e3,n.room?I:"This app cannot update the model's context here.");if(o?.content!==void 0&&!Array.isArray(o.content)||o?.structuredContent!==void 0&&!M(o.structuredContent))return s(t,-32602,"ui/update-model-context takes {content?, structuredContent?}.");if(b={...Array.isArray(o?.content)?{content:o.content}:{},...M(o?.structuredContent)?{structuredContent:o.structuredContent}:{}},r===null){let c=u+f.contextCoalesceMs-g();c<=0?N():r=l.set(N,c)}return R(t,{})}default:return J.includes(a)?G(t,a,o??{}):U.includes(a)?Y(t,a,o??{}):s(t,-32601,"Method not found")}},Z=(t,a)=>{if(t==="ui/notifications/initialized"){if(!P||y)return;y=!0,K();return}if(y)switch(t){case"ui/notifications/size-changed":{let o=a?.height;if(typeof o!="number"||!Number.isFinite(o))return;i.resize(Math.round(Math.min(j(),Math.max(f.minHeight,o))));return}case"notifications/message":e.log&&h.log.take()&&e.log(a);return;case"ui/notifications/request-teardown":i.teardownRequested();return;default:}};return{get initialized(){return y},handleMessage(t){if(k)return;let a=e.source();if(a==null||t.source!==a)return;let o=ne(t.data);if(!o)return;if("method"in o){"id"in o?X(o.id,o.method,o.params):Z(o.method,o.params);return}let c=v.get(o.id);c&&(v.delete(o.id),c(o))},contextChanged(t){k||(d={...d,...t},y?m({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:t}):P&&(w={...w,...t}))},teardown(){return k||!y?Promise.resolve():new Promise(t=>{let a=`host:${++O}`,o=!1,c=()=>{o||(o=!0,v.delete(a),l.clear(A),t())},A=l.set(c,f.teardownMs);v.set(a,c),m({jsonrpc:"2.0",id:a,method:"ui/resource-teardown",params:{}})})},dispose(){k=!0,r!==null&&l.clear(r),r=null;for(let t of v.values())t({jsonrpc:"2.0",id:"",result:{}});v.clear()}}}var V=1;function ae(e){let i=e.webkit?.messageHandlers?.appHost;if(i&&typeof i.postMessage=="function")return{send:l=>i.postMessage(l)};let p=e.appHost;return p&&typeof p.postMessage=="function"?{send:l=>p.postMessage(JSON.stringify(l)),listen:l=>{p.onmessage=g=>{if(typeof g.data!="string")return;let d;try{d=JSON.parse(g.data)}catch{return}d&&typeof d=="object"&&d.v===V&&l(d)}}}:null}function le(e,n){let i=n??ae(e);if(!i)return null;let p=e.document,l=null,g=null,d=0,w=!1,P=0,y=new Map,k=r=>{try{i.send(r)}catch{}},C=(r,u)=>new Promise((m,R)=>{let s=`c${++P}`;y.set(s,{resolve:m,reject:R}),k({v:1,type:"call",callId:s,op:r,params:u})}),O=()=>{for(let r of y.values())r.reject({code:-32e3,message:"This app was closed."});y.clear()};e.addEventListener("message",r=>{l&&(l.handleMessage({source:r.source,data:r.data}),!w&&l.initialized&&(w=!0,k({v:1,type:"initialized"})))});let v=()=>{l?.dispose(),l=null,g?.remove(),g=null,w=!1,O()},h={load(r){if(!r||r.v!==V||!r.doc||typeof r.doc.srcdoc!="string")return;v(),typeof r.engagedAt=="number"&&(d=r.engagedAt);let u=p.createElement("iframe");u.setAttribute("sandbox","allow-scripts allow-forms"),u.setAttribute("referrerpolicy","no-referrer"),u.setAttribute("title","App");let m=Math.max(f.minHeight,Math.round(r.limits?.height??f.defaultHeight));u.style.height=`${m}px`,l=z({doc:r.doc,hostContext:r.hostContext??{},hostVersion:r.hostVersion??"phone",...r.limits?.maxHeight?{limits:{maxHeight:r.limits.maxHeight}}:{},source:()=>u.contentWindow,adapter:{post:s=>u.contentWindow?.postMessage(s,"*"),callRpc:(s,j)=>C("rpc",{method:s,params:j}),sendMessage:async s=>{await C("message",{text:s})},openLink:async s=>{await C("open-link",{url:s})},setContext:async s=>{await C("context",{...s})},resize:s=>{u.style.height=`${s}px`,k({v:1,type:"size",height:s})},engaged:()=>Date.now()-d<=f.engagedTouchMs,teardownRequested:()=>k({v:1,type:"teardown-request"}),now:()=>Date.now()}}),g=u,u.srcdoc=r.doc.srcdoc,p.body.appendChild(u)},contextChanged(r){l?.contextChanged(r??{})},engaged(r){typeof r=="number"&&Number.isFinite(r)&&(d=Math.max(d,r))},async teardown(){l&&await l.teardown(),v(),k({v:1,type:"torn-down"})},reply(r,u){let m=y.get(r);m&&(y.delete(r),u&&"error"in u&&u.error?m.reject(u.error):m.resolve(u&&"result"in u?u.result:void 0))}};i.listen?.(r=>{switch(r.call){case"load":return h.load(r.args[0]);case"contextChanged":return h.contextChanged(r.args[0]);case"engaged":return h.engaged(r.args[0]);case"teardown":return void h.teardown();case"reply":return h.reply(r.args[0],r.args[1])}});let b=e;return b.appHost&&typeof b.appHost.postMessage=="function"||(b.appHost=h),b.mausbotAppHost=h,k({v:1,type:"ready"}),h}function W(){typeof window<"u"&&le(window)}W();})();</script>+<script id="mausbot-app-host">(()=>{var U="2026-01-26";var T={htmlBytes:256*1024,title:80,fallback:1500,fallbackExcerpt:600,heightMin:80,heightMax:720,messageText:4e3,contextText:4e3,doneText:300,mcpHtmlBytes:2*1024*1024,rpcArgumentsBytes:64*1024,rpcResourceBytes:8*1024*1024,messagesPerHour:20,rpcPerMinute:60,pageQueryRows:5e3,pageQueryBytes:1e6,pageQuerySqlChars:2e4,pageQueryMs:1e4,pageStateKeyChars:200,pageStateValueBytes:64*1024,pageStateBytes:256*1024,pageStateKeys:200,pageConnectors:8,pageConnectorTools:24,pageConnectorArgsBytes:64*1024,pageConnectorResultBytes:512*1024,pageConnectorMs:6e4,pageConnectorErrorChars:1e3,pageConnectorCallsPerMinute:30,connectorCallsPerMinute:60};var E="In a room, pages, apps and widgets are view-only: they cannot send messages or tell a bot what anyone sees.";function N(e){let t=0;for(let r=0;r<e.length;r+=1){let a=e.charCodeAt(r);if(a<128)t+=1;else if(a<2048)t+=2;else if(a>=55296&&a<=56319&&r+1<e.length){let l=e.charCodeAt(r+1);l>=56320&&l<=57343?(t+=4,r+=1):t+=3}else t+=3}return t}var $=["tools/call","tools/list","resources/read","resources/list"],W=["mausbot/data/query","mausbot/state/get","mausbot/state/set","mausbot/state/keys","mausbot/connectors/call","mausbot/connectors/list"];function j(e){return e==="mausbot/data/query"?"data":e.startsWith("mausbot/connectors/")?"connectors":"state"}var L=-32601,M=-32602,f=-32e3;var m={messageBytes:1e6,minHeight:48,defaultHeight:160,maxHeight:720,linkChars:2048,teardownMs:1e3,engagedTouchMs:1e4,contextCoalesceMs:1e3,logsPerMinute:50,rates:{message:[[3e3,1],[6e5,10]],openLink:[[2e3,1]],rpc:[[1e4,10],[6e5,120]]}};function se(e){let t=J(e);return{...e.can.openLinks?{openLinks:{}}:{},logging:{},...e.can.modelContext?{updateModelContext:{text:{},structuredContent:{}}}:{},...e.can.message?{message:{text:{}}}:{},...t&&e.can.serverTools?{serverTools:{}}:{},...t&&e.can.serverResources?{serverResources:{}}:{},sandbox:{permissions:{},csp:{connectDomains:[...e.network.connect],resourceDomains:[...e.network.resources]}}}}function J(e){return!!e.tool}function v(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function z(e){return typeof e=="string"&&e.length<=200||typeof e=="number"&&Number.isFinite(e)}function G(e){let t;try{t=JSON.stringify(e)}catch{return null}return t===void 0?null:t.length*3<=m.messageBytes?t.length:N(t)}function ie(e){if(!v(e)||e.jsonrpc!=="2.0")return null;let t=G(e);return t===null||t>m.messageBytes||e.params!==void 0&&!v(e.params)?null:typeof e.method=="string"?!e.method||e.method.length>200||"id"in e&&!z(e.id)?null:e:e.method!==void 0||!z(e.id)?null:"result"in e||v(e.error)&&typeof e.error.code=="number"&&typeof e.error.message=="string"?e:null}function H(e,t){let r=[],a=Math.max(...e.map(([l])=>l));return{take(){let l=t();for(;r.length&&l-r[0]>=a;)r.shift();for(let[g,d]of e)if(r.filter(R=>l-R<g).length>=d)return!1;return r.push(l),!0}}}function B(e){return v(e)&&typeof e.code=="number"&&Number.isInteger(e.code)?{code:e.code,message:typeof e.message=="string"&&e.message?e.message:"The host refused this."}:{code:f,message:e instanceof Error&&e.message?e.message:"The host could not do that."}}function ae(e){if(typeof e!="string"||!e||e.length>m.linkChars)return null;let t;try{t=new URL(e)}catch{return null}return t.protocol!=="http:"&&t.protocol!=="https:"||t.username||t.password?null:t.href.length<=m.linkChars?t.href:null}function le(e,t){return e==="connectors"?t?"In a room, a page cannot call connected apps.":'This page declared no connector tools: show it with uses naming each tool, e.g. ["gmail:GMAIL_FETCH_EMAILS"].':t?"In a room, a page cannot read its bot's data or keep state.":`This page did not declare "${e}": show it with uses: ["${e}"] to ${e==="data"?"read its bot's data":"keep state"}.`}function V(e,t){let r=e.tool,a=e.name??e.connector??e.server;if(typeof r!="string"||!r||r.length>128||typeof a!="string"||!a||a.length>68)return null;let l=a.trim().toLowerCase();return typeof e.server=="string"||l.startsWith("mcp:")?{server:l.replace(/^mcp:/,""),tool:r}:typeof e.connector=="string"?{connector:l,tool:r}:!t.some(d=>"connector"in d&&d.connector===l)&&t.some(d=>"server"in d&&d.server===l)?{server:l,tool:r}:{connector:l,tool:r}}function pe(e,t){return e.find(r=>("server"in t?"server"in r&&r.server===t.server:"connector"in r&&r.connector===t.connector)&&r.tools.includes(t.tool))??null}function ue(e){let t="server"in e?`mcp:${e.server}:${e.tool}`:`${e.connector}:${e.tool}`;return`This page did not declare ${e.tool}: list "${t}" in show_html uses to call it.`}function de(e,t){let r=a=>typeof a=="string"&&a.length>0&&a.length<=T.pageStateKeyChars;switch(e){case"mausbot/data/query":return typeof t.sql!="string"||!t.sql.trim()||t.sql.length>T.pageQuerySqlChars?`mausbot.data.query needs one SELECT of at most ${T.pageQuerySqlChars} characters.`:t.params===void 0||Array.isArray(t.params)||v(t.params)?null:"mausbot.data.query params: a list for ? or $1, or an object for $name.";case"mausbot/state/get":case"mausbot/state/set":return r(t.key)?null:`A state key is text of 1 to ${T.pageStateKeyChars} characters.`;case"mausbot/state/keys":case"mausbot/connectors/list":return null;case"mausbot/connectors/call":{if(!V(t,[]))return"mausbot.connectors.call needs (connector or server, tool name, arguments object).";if(t.arguments!==void 0&&!v(t.arguments))return"mausbot.connectors.call arguments: one object.";let a=G(t.arguments??{});return a===null||a>T.pageConnectorArgsBytes?`mausbot.connectors.call arguments: at most ${T.pageConnectorArgsBytes} bytes of JSON.`:null}}}function ce(e,t,r,a){return e==="mausbot/connectors/list"?{}:r?{...r,arguments:v(t.arguments)?t.arguments:{},engaged:a()}:t}function ge(e){if(!e||e.role!=="user"||!Array.isArray(e.content)||e.content.length===0)return null;let t=[];for(let a of e.content){if(!v(a)||a.type!=="text"||typeof a.text!="string")return null;t.push(a.text)}let r=t.join(`+`).trim();return r&&r.length<=T.messageText?r:null}function K(e){let{doc:t,adapter:r}=e,a=J(t),l=e.timers??{set:(n,p)=>setTimeout(n,p),clear:n=>clearTimeout(n)},g=()=>r.now(),d={...e.hostContext,...a&&t.tool?{toolInfo:{tool:t.tool}}:{}},R=null,S=!1,y=!1,k=!1,I=!1,O=0,w=new Map,b={message:H(m.rates.message,g),openLink:H(m.rates.openLink,g),rpc:H(m.rates.rpc,g),log:H([[6e4,m.logsPerMinute]],g)},A=null,o=null,u=-1/0,h=n=>{if(!k)try{r.post(n)}catch{}},C=(n,p)=>h({jsonrpc:"2.0",id:n,result:p}),i=(n,p,s)=>h({jsonrpc:"2.0",id:n,error:{code:p,message:s}}),q=()=>{let n=e.limits?.maxHeight,p=d.containerDimensions?.maxHeight,s=typeof n=="number"&&n>0?n:typeof p=="number"&&p>0?p:m.maxHeight;return Math.max(m.minHeight,s)},F=()=>{if(o=null,k||!A)return;let n=A;A=null,u=g(),Promise.resolve().then(()=>r.setContext(n)).catch(()=>{})},Y=async()=>{if(o===null||!A)return;l.clear(o),o=null;let n=A;A=null,u=g();try{await r.setContext(n)}catch{}},X=()=>{if(a&&!I&&(I=!0,h({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:t.toolInput??{}}}),h({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:t.toolResult??{content:[]}})),R){let n=R;R=null,h({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:n})}},ee=async(n,p,s)=>{if(!a)return i(n,L,"Method not found");if(!(p.startsWith("tools/")?t.can.serverTools:t.can.serverResources))return i(n,f,t.room?E:t.blocked?.text??"This app cannot reach its server right now.");if(p==="tools/call"&&(typeof s.name!="string"||!s.name||s.arguments!==void 0&&!v(s.arguments)))return i(n,M,"tools/call needs {name, arguments?}.");if(p==="resources/read"&&typeof s.uri!="string")return i(n,M,"resources/read needs {uri}.");if(!b.rpc.take())return i(n,f,"Too many calls from this app. Wait a moment.");try{let x=await r.callRpc(p,s);C(n,x??{})}catch(x){let P=B(x);i(n,P.code,P.message)}},te=async(n,p,s)=>{if(a)return i(n,L,"Method not found");let c=j(p),x=c==="connectors"?t.can.connectors??[]:[];if(c==="connectors"?!x.length:!t.can[c])return i(n,f,le(c,!!t.room));let P=de(p,s);if(P)return i(n,M,P);let _=p==="mausbot/connectors/call"?V(s,x):null;if(_&&!pe(x,_))return i(n,f,ue(_));if(!b.rpc.take())return i(n,f,"Too many calls from this page. Wait a moment.");try{C(n,await r.callRpc(p,ce(p,s,_,()=>r.engaged()))??{})}catch(oe){let D=B(oe);i(n,D.code,D.message)}},ne=async(n,p,s)=>{if(p==="ui/initialize")return S=!0,C(n,{protocolVersion:U,hostInfo:{name:"mausbot",version:e.hostVersion},hostCapabilities:se(t),hostContext:d});if(y)switch(p){case"ping":return C(n,{});case"ui/request-display-mode":return C(n,{mode:"inline"});case"ui/open-link":{if(!t.can.openLinks)return i(n,f,"This app cannot open links here.");if(!r.engaged())return i(n,f,"Links open only after the person clicks in the app.");let c=ae(s?.url);if(!c)return i(n,M,"Only http and https links of at most 2,048 characters, without a user name or password, can be opened.");if(!b.openLink.take())return i(n,f,"Too many links from this app. Wait a moment.");try{return await r.openLink(c),C(n,{})}catch(x){return i(n,f,B(x).message)}}case"ui/message":{if(!t.can.message)return i(n,f,t.room?E:"This app cannot send messages here.");if(!r.engaged())return i(n,f,"Messages are sent only after the person clicks in the app.");let c=ge(s);if(c===null)return i(n,M,`Only text messages of 1 to ${T.messageText} characters can be sent.`);if(!b.message.take())return i(n,f,"Too many messages from this app. Wait a moment.");try{return await Y(),await r.sendMessage(c),C(n,{})}catch(x){return i(n,f,B(x).message)}}case"ui/update-model-context":{if(!t.can.modelContext)return i(n,f,t.room?E:"This app cannot update the model's context here.");if(s?.content!==void 0&&!Array.isArray(s.content)||s?.structuredContent!==void 0&&!v(s.structuredContent))return i(n,M,"ui/update-model-context takes {content?, structuredContent?}.");if(A={...Array.isArray(s?.content)?{content:s.content}:{},...v(s?.structuredContent)?{structuredContent:s.structuredContent}:{}},o===null){let c=u+m.contextCoalesceMs-g();c<=0?F():o=l.set(F,c)}return C(n,{})}default:return $.includes(p)?ee(n,p,s??{}):W.includes(p)?te(n,p,s??{}):i(n,L,"Method not found")}},re=(n,p)=>{if(n==="ui/notifications/initialized"){if(!S||y)return;y=!0,X();return}if(y)switch(n){case"ui/notifications/size-changed":{let s=p?.height;if(typeof s!="number"||!Number.isFinite(s))return;r.resize(Math.round(Math.min(q(),Math.max(m.minHeight,s))));return}case"notifications/message":e.log&&b.log.take()&&e.log(p);return;case"ui/notifications/request-teardown":r.teardownRequested();return;default:}};return{get initialized(){return y},handleMessage(n){if(k)return;let p=e.source();if(p==null||n.source!==p)return;let s=ie(n.data);if(!s)return;if("method"in s){"id"in s?ne(s.id,s.method,s.params):re(s.method,s.params);return}let c=w.get(s.id);c&&(w.delete(s.id),c(s))},contextChanged(n){k||(d={...d,...n},y?h({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:n}):S&&(R={...R,...n}))},teardown(){return k||!y?Promise.resolve():new Promise(n=>{let p=`host:${++O}`,s=!1,c=()=>{s||(s=!0,w.delete(p),l.clear(x),n())},x=l.set(c,m.teardownMs);w.set(p,c),h({jsonrpc:"2.0",id:p,method:"ui/resource-teardown",params:{}})})},dispose(){k=!0,o!==null&&l.clear(o),o=null;for(let n of w.values())n({jsonrpc:"2.0",id:"",result:{}});w.clear()}}}var Q=1;function me(e){let r=e.webkit?.messageHandlers?.appHost;if(r&&typeof r.postMessage=="function")return{send:l=>r.postMessage(l)};let a=e.appHost;return a&&typeof a.postMessage=="function"?{send:l=>a.postMessage(JSON.stringify(l)),listen:l=>{a.onmessage=g=>{if(typeof g.data!="string")return;let d;try{d=JSON.parse(g.data)}catch{return}d&&typeof d=="object"&&d.v===Q&&l(d)}}}:null}function fe(e,t){let r=t??me(e);if(!r)return null;let a=e.document,l=null,g=null,d=0,R=!1,S=0,y=new Map,k=o=>{try{r.send(o)}catch{}},I=(o,u)=>new Promise((h,C)=>{let i=`c${++S}`;y.set(i,{resolve:h,reject:C}),k({v:1,type:"call",callId:i,op:o,params:u})}),O=()=>{for(let o of y.values())o.reject({code:-32e3,message:"This app was closed."});y.clear()};e.addEventListener("message",o=>{l&&(l.handleMessage({source:o.source,data:o.data}),!R&&l.initialized&&(R=!0,k({v:1,type:"initialized"})))});let w=()=>{l?.dispose(),l=null,g?.remove(),g=null,R=!1,O()},b={load(o){if(!o||o.v!==Q||!o.doc||typeof o.doc.srcdoc!="string")return;w(),typeof o.engagedAt=="number"&&(d=o.engagedAt);let u=a.createElement("iframe");u.setAttribute("sandbox","allow-scripts allow-forms"),u.setAttribute("referrerpolicy","no-referrer"),u.setAttribute("title","App");let h=Math.max(m.minHeight,Math.round(o.limits?.height??m.defaultHeight));u.style.height=`${h}px`,l=K({doc:o.doc,hostContext:o.hostContext??{},hostVersion:o.hostVersion??"phone",...o.limits?.maxHeight?{limits:{maxHeight:o.limits.maxHeight}}:{},source:()=>u.contentWindow,adapter:{post:i=>u.contentWindow?.postMessage(i,"*"),callRpc:(i,q)=>I("rpc",{method:i,params:q}),sendMessage:async i=>{await I("message",{text:i})},openLink:async i=>{await I("open-link",{url:i})},setContext:async i=>{await I("context",{...i})},resize:i=>{u.style.height=`${i}px`,k({v:1,type:"size",height:i})},engaged:()=>Date.now()-d<=m.engagedTouchMs,teardownRequested:()=>k({v:1,type:"teardown-request"}),now:()=>Date.now()}}),g=u,u.srcdoc=o.doc.srcdoc,a.body.appendChild(u)},contextChanged(o){l?.contextChanged(o??{})},engaged(o){typeof o=="number"&&Number.isFinite(o)&&(d=Math.max(d,o))},async teardown(){l&&await l.teardown(),w(),k({v:1,type:"torn-down"})},reply(o,u){let h=y.get(o);h&&(y.delete(o),u&&"error"in u&&u.error?h.reject(u.error):h.resolve(u&&"result"in u?u.result:void 0))}};r.listen?.(o=>{switch(o.call){case"load":return b.load(o.args[0]);case"contextChanged":return b.contextChanged(o.args[0]);case"engaged":return b.engaged(o.args[0]);case"teardown":return void b.teardown();case"reply":return b.reply(o.args[0],o.args[1])}});let A=e;return A.appHost&&typeof A.appHost.postMessage=="function"||(A.appHost=b),A.mausbotAppHost=b,k({v:1,type:"ready"}),b}function Z(){typeof window<"u"&&fe(window)}Z();})();</script></body></html>diff --git a/shared/app-frame/bridge.test.ts b/shared/app-frame/bridge.test.tsindex 287cd8e5f7..62d7476c84 100644--- a/shared/app-frame/bridge.test.ts+++ b/shared/app-frame/bridge.test.ts@@ -514,3 +514,67 @@ describe("a bot page's data and state", () => {expect((await h.request("mausbot/data/query", { sql: "SELECT 1" }))?.error).toBeUndefined();});});++describe("a bot page's connector tools", () => {+ const gmail = { connector: "gmail", tools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"] };+ const notes = { server: "notes", tools: ["search"] };+ const declared = (over: Partial<AppDocument> = {}): AppDocument => ({ ...botDoc(), can: { ...botDoc().can, connectors: [gmail, notes] }, ...over });++ it("refuses a page that declared no connector tools, and a tool it did not declare, before the host is asked", async () => {+ const none = harness(botDoc());+ await none.connect();+ expect((await none.request("mausbot/connectors/call", { name: "gmail", tool: "GMAIL_FETCH_EMAILS" }))?.error).toEqual({+ code: RPC_HOST_REFUSED, message: 'This page declared no connector tools: show it with uses naming each tool, e.g. ["gmail:GMAIL_FETCH_EMAILS"].',+ });+ expect((await none.request("mausbot/connectors/list"))?.error?.code).toBe(RPC_HOST_REFUSED);+ const h = harness(declared());+ await h.connect();+ expect((await h.request("mausbot/connectors/call", { name: "gmail", tool: "GMAIL_DELETE_MESSAGE" }))?.error).toEqual({+ code: RPC_HOST_REFUSED, message: 'This page did not declare GMAIL_DELETE_MESSAGE: list "gmail:GMAIL_DELETE_MESSAGE" in show_html uses to call it.',+ });+ expect((await h.request("mausbot/connectors/call", { name: "outlook", tool: "OUTLOOK_LIST_MESSAGES" }))?.error?.code).toBe(RPC_HOST_REFUSED);+ expect((await h.request("mausbot/connectors/call", { name: "notes", tool: "write" }))?.error?.message).toContain('"mcp:notes:write"');+ expect(none.calls.rpc).toEqual([]);+ expect(h.calls.rpc).toEqual([]);+ });++ it("forwards a declared call with exactly its own fields and the host's word on a click, which the page cannot set", async () => {+ const h = harness(declared());+ h.answerRpc(async () => ({ result: { messages: [] } }));+ await h.connect();+ h.setEngaged(false);+ expect((await h.request("mausbot/connectors/call", { name: "gmail", tool: "GMAIL_FETCH_EMAILS", arguments: { max_results: 5 }, engaged: true, account: "acct_1" }))?.result)+ .toEqual({ result: { messages: [] } });+ h.setEngaged(true);+ await h.request("mausbot/connectors/call", { name: "gmail", tool: "GMAIL_SEND_EMAIL", arguments: { to: "[email protected]" } });+ await h.request("mausbot/connectors/call", { name: "notes", tool: "search" });+ expect(h.calls.rpc).toEqual([+ { method: "mausbot/connectors/call", params: { connector: "gmail", tool: "GMAIL_FETCH_EMAILS", arguments: { max_results: 5 }, engaged: false } },+ { method: "mausbot/connectors/call", params: { connector: "gmail", tool: "GMAIL_SEND_EMAIL", arguments: { to: "[email protected]" }, engaged: true } },+ { method: "mausbot/connectors/call", params: { server: "notes", tool: "search", arguments: {}, engaged: true } },+ ]);+ });++ it("asks the host for the list with no params, and checks a call's params first", async () => {+ const h = harness(declared());+ h.answerRpc(async () => ({ connectors: [] }));+ await h.connect();+ expect((await h.request("mausbot/connectors/list", { anything: 1 }))?.result).toEqual({ connectors: [] });+ expect((await h.request("mausbot/connectors/call", { name: "gmail" }))?.error?.code).toBe(RPC_INVALID_PARAMS);+ expect((await h.request("mausbot/connectors/call", { name: "gmail", tool: "GMAIL_FETCH_EMAILS", arguments: [1] }))?.error?.code).toBe(RPC_INVALID_PARAMS);+ expect((await h.request("mausbot/connectors/call", { name: "gmail", tool: "GMAIL_FETCH_EMAILS", arguments: { q: "x".repeat(70_000) } }))?.error?.code).toBe(RPC_INVALID_PARAMS);+ expect(h.calls.rpc).toEqual([{ method: "mausbot/connectors/list", params: {} }]);+ });++ it("gives a room's page and an MCP app none of it", async () => {+ const room = harness({ ...botDoc(), room: true });+ await room.connect();+ expect((await room.request("mausbot/connectors/call", { name: "gmail", tool: "GMAIL_FETCH_EMAILS" }))?.error?.message).toBe("In a room, a page cannot call connected apps.");+ const mcp = harness(mcpDoc({ can: { ...mcpDoc().can, connectors: [gmail] } }));+ await mcp.connect();+ expect((await mcp.request("mausbot/connectors/list"))?.error?.code).toBe(RPC_METHOD_NOT_FOUND);+ expect(room.calls.rpc).toEqual([]);+ expect(mcp.calls.rpc).toEqual([]);+ });+});+diff --git a/shared/app-frame/bridge.ts b/shared/app-frame/bridge.tsindex 7df7bca7a1..e0f8361a47 100644--- a/shared/app-frame/bridge.ts+++ b/shared/app-frame/bridge.ts@@ -1,15 +1,17 @@// The host side of the MCP Apps bridge (io.modelcontextprotocol/ui, stable 2026-01-26) for one app frame. It// runs in the desktop renderer and, bundled, in the phones' web views, so it never touches a window: a platform// hands it each `message` event and an adapter for the rest.-import { APP_LIMITS, APP_PROTOCOL_VERSION, ROOM_VIEW_ONLY, utf8Bytes, type AppDocument } from "../app.ts";+import { APP_LIMITS, APP_PROTOCOL_VERSION, ROOM_VIEW_ONLY, utf8Bytes, type AppConnectorUse, type AppDocument } from "../app.ts";import {APP_RPC_METHODS,PAGE_RPC_METHODS,+ pageMethodUse,RPC_HOST_REFUSED,RPC_INVALID_PARAMS,RPC_METHOD_NOT_FOUND,type AppRpcMethod,type PageRpcMethod,+ type PageUse,type JsonRpcError,type JsonRpcId,type JsonRpcMessage,@@ -180,11 +182,40 @@ export function openableLink(value: unknown): string | null {}/** Why a bot's page may not make a call it did not declare, or makes in a room. */-export function pageUseRefusal(use: "data" | "state", room: boolean): string {+export function pageUseRefusal(use: PageUse, room: boolean): string {+ if (use === "connectors") {+ return room ? "In a room, a page cannot call connected apps." : 'This page declared no connector tools: show it with uses naming each tool, e.g. ["gmail:GMAIL_FETCH_EMAILS"].';+ }if (room) return "In a room, a page cannot read its bot's data or keep state.";return `This page did not declare "${use}": show it with uses: ["${use}"] to ${use === "data" ? "read its bot's data" : "keep state"}.`;}+/** The target of a connector call as the page named it: a connected app's toolkit or an MCP server, and the tool. */+export type PageConnectorTarget = { connector: string; tool: string } | { server: string; tool: string };++/** `name` is a connected app's toolkit or, failing that, an MCP server the page declared; "mcp:<server>" always a server. */+export function pageConnectorTarget(params: Record<string, unknown>, declared: readonly AppConnectorUse[]): PageConnectorTarget | null {+ const tool = params.tool, given = params.name ?? params.connector ?? params.server;+ if (typeof tool !== "string" || !tool || tool.length > 128 || typeof given !== "string" || !given || given.length > 68) return null;+ const name = given.trim().toLowerCase();+ if (typeof params.server === "string" || name.startsWith("mcp:")) return { server: name.replace(/^mcp:/, ""), tool };+ if (typeof params.connector === "string") return { connector: name, tool };+ const app = declared.some((group) => "connector" in group && group.connector === name);+ return !app && declared.some((group) => "server" in group && group.server === name) ? { server: name, tool } : { connector: name, tool };+}++/** The declared group a target belongs to, when the page declared that exact tool. */+export function declaredConnectorTool(declared: readonly AppConnectorUse[], target: PageConnectorTarget): AppConnectorUse | null {+ return declared.find((group) => ("server" in target+ ? "server" in group && group.server === target.server+ : "connector" in group && group.connector === target.connector) && group.tools.includes(target.tool)) ?? null;+}++export function pageConnectorUndeclared(target: PageConnectorTarget): string {+ const named = "server" in target ? `mcp:${target.server}:${target.tool}` : `${target.connector}:${target.tool}`;+ return `This page did not declare ${target.tool}: list "${named}" in show_html uses to call it.`;+}+/** The params a page's own call needs, or what is wrong with them. */function pageParamsProblem(method: PageRpcMethod, params: Record<string, unknown>): string | null {const key = (value: unknown) => typeof value === "string" && value.length > 0 && value.length <= APP_LIMITS.pageStateKeyChars;@@ -198,10 +229,24 @@ function pageParamsProblem(method: PageRpcMethod, params: Record<string, unknowncase "mausbot/state/set":return key(params.key) ? null : `A state key is text of 1 to ${APP_LIMITS.pageStateKeyChars} characters.`;case "mausbot/state/keys":+ case "mausbot/connectors/list":return null;+ case "mausbot/connectors/call": {+ if (!pageConnectorTarget(params, [])) return "mausbot.connectors.call needs (connector or server, tool name, arguments object).";+ if (params.arguments !== undefined && !isRecord(params.arguments)) return "mausbot.connectors.call arguments: one object.";+ const bytes = jsonBytes(params.arguments ?? {});+ return bytes === null || bytes > APP_LIMITS.pageConnectorArgsBytes ? `mausbot.connectors.call arguments: at most ${APP_LIMITS.pageConnectorArgsBytes} bytes of JSON.` : null;+ }}}+/** Only what the host should send on: a connector call's own fields, with the host's word on engagement. */+function pageParamsSent(method: PageRpcMethod, params: Record<string, unknown>, target: PageConnectorTarget | null, engaged: () => boolean): Record<string, unknown> {+ if (method === "mausbot/connectors/list") return {};+ if (!target) return params;+ return { ...target, arguments: isRecord(params.arguments) ? params.arguments : {}, engaged: engaged() };+}+function messageText(params: Record<string, unknown> | undefined): string | null {if (!params || params.role !== "user" || !Array.isArray(params.content) || params.content.length === 0) return null;const texts: string[] = [];@@ -312,15 +357,20 @@ export function createAppBridge(options: AppBridgeOptions): AppBridge {};// A page's reads and saves need no click: a dashboard loads its data, and remembers its filters, on its own.+ // A connector call to a tool that changes something needs a click as well, which only the host can vouch for: the server+ // knows which tools change something and refuses such a call made without one.const onPageRpc = async (id: JsonRpcId, method: PageRpcMethod, params: Record<string, unknown>) => {if (mcp) return fail(id, RPC_METHOD_NOT_FOUND, "Method not found");- const use = method === "mausbot/data/query" ? "data" : "state";- if (!doc.can[use]) return fail(id, RPC_HOST_REFUSED, pageUseRefusal(use, Boolean(doc.room)));+ const use = pageMethodUse(method);+ const declared = use === "connectors" ? doc.can.connectors ?? [] : [];+ if (use === "connectors" ? !declared.length : !doc.can[use]) return fail(id, RPC_HOST_REFUSED, pageUseRefusal(use, Boolean(doc.room)));const problem = pageParamsProblem(method, params);if (problem) return fail(id, RPC_INVALID_PARAMS, problem);+ const target = method === "mausbot/connectors/call" ? pageConnectorTarget(params, declared)! : null;+ if (target && !declaredConnectorTool(declared, target)) return fail(id, RPC_HOST_REFUSED, pageConnectorUndeclared(target));if (!rates.rpc.take()) return fail(id, RPC_HOST_REFUSED, "Too many calls from this page. Wait a moment.");try {- respond(id, (await adapter.callRpc(method, params)) ?? {});+ respond(id, (await adapter.callRpc(method, pageParamsSent(method, params, target, () => adapter.engaged()))) ?? {});} catch (error) {const failure = rpcErrorFrom(error);fail(id, failure.code, failure.message);diff --git a/shared/app-frame/document.test.ts b/shared/app-frame/document.test.tsindex df7ef72819..d6b7432433 100644--- a/shared/app-frame/document.test.ts+++ b/shared/app-frame/document.test.ts@@ -99,9 +99,12 @@ describe("a bot page's declared uses", () => {expect(botHtmlDocument({ messageId: "m", rev: 0, html: "<p>x</p>", uses: ["data"] }).can).toMatchObject({ data: true });expect(botHtmlDocument({ messageId: "m", rev: 0, html: "<p>x</p>", uses: ["data"] }).can.state).toBeUndefined();expect(botHtmlDocument({ messageId: "m", rev: 0, html: "<p>x</p>", uses: ["data", "state"] }).can).toMatchObject({ data: true, state: true });- const room = botHtmlDocument({ messageId: "m", rev: 0, html: "<p>x</p>", uses: ["data", "state"], room: true }).can;+ const connectors = [{ connector: "gmail", tools: ["GMAIL_FETCH_EMAILS"] }, { server: "notes", tools: ["search"] }];+ expect(botHtmlDocument({ messageId: "m", rev: 0, html: "<p>x</p>", connectors }).can.connectors).toEqual(connectors);+ const room = botHtmlDocument({ messageId: "m", rev: 0, html: "<p>x</p>", uses: ["data", "state"], connectors, room: true }).can;expect(room.data).toBeUndefined();expect(room.state).toBeUndefined();+ expect(room.connectors).toBeUndefined();});it("are refused with a plain reason on a published page", async () => {@@ -109,7 +112,9 @@ describe("a bot page's declared uses", () => {const script = /<script>(.*?)<\/script>/.exec(html)![1]!;const window: Record<string, unknown> = { matchMedia: () => ({ matches: false }), open: () => null };new Function("window", "matchMedia", script)(window, window.matchMedia);- const mausbot = window.mausbot as { data: { query(): Promise<unknown> }; state: { set(): Promise<unknown> } };+ const mausbot = window.mausbot as { data: { query(): Promise<unknown> }; state: { set(): Promise<unknown> }; connectors: { call(): Promise<unknown>; list(): Promise<unknown> } };+ await expect(mausbot.connectors.call()).rejects.toThrow(PUBLISHED_PAGE_NO_BOT);+ await expect(mausbot.connectors.list()).rejects.toThrow(PUBLISHED_PAGE_NO_BOT);await expect(mausbot.data.query()).rejects.toThrow(PUBLISHED_PAGE_NO_BOT);await expect(mausbot.state.set()).rejects.toThrow(PUBLISHED_PAGE_NO_BOT);});diff --git a/shared/app-frame/document.ts b/shared/app-frame/document.tsindex febb3978b0..c0bdfd8d32 100644--- a/shared/app-frame/document.ts+++ b/shared/app-frame/document.ts@@ -1,7 +1,7 @@// No byte of app content precedes the CSP meta. A leading BOM, whitespace, comments, bogus comments// (`<?xml …?>`, `<![CDATA[…]>`) and the app's own doctype are stripped first; the rest follows the meta,// which already sits in the head the parser opened for it.-import type { AppCan, AppDocument, AppToolDefinition, AppToolResult, AppUse } from "../app.ts";+import type { AppCan, AppConnectorUse, AppDocument, AppToolDefinition, AppToolResult, AppUse } from "../app.ts";import { BOT_HTML_CSP, BOT_HTML_NETWORK, folderPageCsp, folderPageNetwork, mcpAppCsp } from "./csp.ts";import { APP_HELPER_SOURCE, APP_ROOM_HELPER_SOURCE, APP_THEME_STYLE, PUBLISHED_PAGE_NO_BOT } from "./helper.ts";import { jsxPageHtml } from "./jsx-page.ts";@@ -45,7 +45,7 @@ const PUBLISHED_MAUSBOT = "(function(){var no=function(){return Promise.reject(n"window.mausbot={theme:matchMedia(\"(prefers-color-scheme: dark)\").matches?\"dark\":\"light\"," +"send:function(){return Promise.resolve()},setContext:function(){return Promise.resolve()}," +"open:function(u){window.open(String(u),\"_blank\",\"noopener\");return Promise.resolve()}," +- "data:{query:no},state:{get:no,set:no,keys:no}};})();";+ "data:{query:no},state:{get:no,set:no,keys:no},connectors:{call:no,list:no}};})();";/** A bot's HTML page as a published page serves it: the theme colours the chat would give it, and a quiet mausbot. */export function publishedBotHtml(html: string): string {@@ -61,6 +61,7 @@ export const ROOM_CAN: AppCan = { serverTools: false, serverResources: false, me* page gets none of it. */export function botHtmlDocument(input: {messageId: string; rev: number; html: string; format?: "jsx"; title?: string; files?: string; room?: boolean; uses?: readonly AppUse[];+ connectors?: readonly AppConnectorUse[];}): AppDocument {const html = input.format === "jsx" ? jsxPageHtml({ title: input.title ?? "Page", source: input.html }) : input.html;const csp = input.files ? folderPageCsp(input.files) : BOT_HTML_CSP;@@ -72,13 +73,16 @@ export function botHtmlDocument(input: {srcdoc: buildSrcdoc({ html, csp, botHelper: true, room: input.room === true, ...(input.files ? { base: input.files } : {}) }),csp,network: { connect: [...network.connect], resources: [...network.resources] },- can: input.room ? { ...ROOM_CAN } : declaredCan(input.uses ?? []),+ can: input.room ? { ...ROOM_CAN } : declaredCan(input.uses ?? [], input.connectors ?? []),...(input.room ? { room: true as const } : {}),};}-function declaredCan(uses: readonly AppUse[]): AppCan {- return { ...BOT_HTML_CAN, ...(uses.includes("data") ? { data: true } : {}), ...(uses.includes("state") ? { state: true } : {}) };+function declaredCan(uses: readonly AppUse[], connectors: readonly AppConnectorUse[]): AppCan {+ return {+ ...BOT_HTML_CAN, ...(uses.includes("data") ? { data: true } : {}), ...(uses.includes("state") ? { state: true } : {}),+ ...(connectors.length ? { connectors: connectors.map((group) => ({ ...group, tools: [...group.tools] })) } : {}),+ };}export function mcpAppDocument(input: {diff --git a/shared/app-frame/helper.test.ts b/shared/app-frame/helper.test.tsindex ba9d2b97cd..2c234a7874 100644--- a/shared/app-frame/helper.test.ts+++ b/shared/app-frame/helper.test.ts@@ -129,6 +129,7 @@ function boot(engaged = true, options: {send(text: string): Promise<void>; open(url: string): Promise<void>; setContext(text: string): Promise<void>; theme: string; room: boolean;data: { query(sql: string, params?: unknown): Promise<unknown> };state: { get(key: string): Promise<unknown>; set(key: string, value?: unknown): Promise<void>; keys(): Promise<string[]> };+ connectors: { call(name: string, tool: string, args?: unknown): Promise<unknown>; list(): Promise<unknown[]> };},};}@@ -193,6 +194,26 @@ describe("the bot-page helper", () => {expect(asked[4]).toEqual(["mausbot/state/set", { key: "filter" }]);});+ it("calls declared connector tools and lists them through the bridge, answering with the tool's result alone", async () => {+ const asked: Array<[string, Record<string, unknown>]> = [];+ const page = boot(false, {+ can: { connectors: [{ connector: "gmail", tools: ["GMAIL_FETCH_EMAILS"] }] },+ rpc: async (method, params) => {+ asked.push([method, params]);+ return method === "mausbot/connectors/list"+ ? { connectors: [{ connector: "gmail", label: "Gmail", connected: true, tools: ["GMAIL_FETCH_EMAILS"] }] }+ : { result: { messages: [{ id: "1" }] }, truncated: true };+ },+ });+ expect(await page.mausbot().connectors.call("gmail", "GMAIL_FETCH_EMAILS", { max_results: 3 })).toEqual({ messages: [{ id: "1" }] });+ expect(await page.mausbot().connectors.list()).toEqual([{ connector: "gmail", label: "Gmail", connected: true, tools: ["GMAIL_FETCH_EMAILS"] }]);+ expect(asked).toEqual([+ ["mausbot/connectors/call", { connector: "gmail", tool: "GMAIL_FETCH_EMAILS", arguments: { max_results: 3 }, engaged: false }],+ ["mausbot/connectors/list", {}],+ ]);+ await expect(page.mausbot().connectors.call("gmail", "GMAIL_SEND_EMAIL")).rejects.toThrow("This page did not declare GMAIL_SEND_EMAIL");+ });+it("rejects data and state with the reason when the page did not declare them", async () => {const page = boot();await expect(page.mausbot().data.query("SELECT 1")).rejects.toThrow('This page did not declare "data"');diff --git a/shared/app-frame/helper.ts b/shared/app-frame/helper.tsindex 630149d76c..17e9a65ac1 100644--- a/shared/app-frame/helper.ts+++ b/shared/app-frame/helper.ts@@ -9,9 +9,14 @@// room: boolean, // shown in a room: send and setContext resolve and do nothing// data: { query(sql, params?): Promise<{ columns, rows, truncated }> }, // mausbot/data/query// state: { get(key): Promise<value | undefined>, set(key, value?): Promise<void>, keys(): Promise<string[]> },+// connectors: {+// call(connectorOrServer, tool, args?): Promise<result>, // mausbot/connectors/call: the tool's answer+// list(): Promise<Array<{ connector | server, label, connected, tools }>>, // mausbot/connectors/list+// },// }//-// data and state answer only for a page shown with show_html `uses` naming them; otherwise they reject with the reason.+// data, state and connectors answer only for a page shown with show_html `uses` naming them; otherwise they reject with the+// reason. A connector call that changes something runs only after the person clicked in the page.//// Outside a room it also reports the person's text selection (mausbot/notifications/selection), so the host can// offer to cite it in the chat's composer. Everywhere it reports whether the page, as rendered, opens with a heading@@ -34,7 +39,7 @@ export const APP_THEME_STYLE = [].join("");/** What a published page's data and state calls reject with: no bot answers there. */-export const PUBLISHED_PAGE_NO_BOT = "This page is published: it cannot read the bot's data or keep state. Embed the data in the page instead.";+export const PUBLISHED_PAGE_NO_BOT = "This page is published: it cannot read the bot's data, keep state or call connected apps. Embed the data in the page instead.";/** The page's text selection, read by the desktop host beside the bridge: { text, left, bottom }, or { text: "" } once gone. */export const APP_SELECTION_METHOD = "mausbot/notifications/selection";@@ -331,6 +336,15 @@ const helperSource = (room: boolean) => `(function () {return call("mausbot/state/keys", {}).then(function (result) { return result && Array.isArray(result.keys) ? result.keys : []; });}};+ api.connectors = {+ call: function (name, tool, args) {+ return call("mausbot/connectors/call", { name: String(name), tool: String(tool), arguments: args === undefined ? {} : args })+ .then(function (answer) { return answer ? answer.result : undefined; });+ },+ list: function () {+ return call("mausbot/connectors/list", {}).then(function (answer) { return answer && Array.isArray(answer.connectors) ? answer.connectors : []; });+ }+ };Object.defineProperty(window, "mausbot", { value: api, enumerable: true });})();`;diff --git a/shared/app-frame/jsx-page.ts b/shared/app-frame/jsx-page.tsindex 206bd90fe6..a78d21c373 100644--- a/shared/app-frame/jsx-page.ts+++ b/shared/app-frame/jsx-page.ts@@ -17,7 +17,7 @@ export const JSX_PAGE_LIBRARIES = {const NPM = "https://cdn.jsdelivr.net/npm";const REACT = `${NPM}/react@${JSX_PAGE_LIBRARIES.react}/+esm`;-/** What a page's file may import. `mausbot` is the shell's own: Chart, useTheme, send, open, setContext, data and state. */+/** What a page's file may import. `mausbot` is the shell's own: Chart, useTheme, send, open, setContext, data, state and connectors. */export const JSX_PAGE_IMPORTS: Readonly<Record<string, string>> = {react: REACT,"react/jsx-runtime": `${NPM}/react@${JSX_PAGE_LIBRARIES.react}/jsx-runtime/+esm`,@@ -169,6 +169,10 @@ export const JSX_RUNTIME_SOURCE = `(function (env) {get: function (key) { return bridge() ? bridge().state.get(key) : unpublished(); },set: function (key, value) { return bridge() ? bridge().state.set(key, value) : unpublished(); },keys: function () { return bridge() ? bridge().state.keys() : unpublished(); }+ },+ connectors: {+ call: function (name, tool, args) { return bridge() ? bridge().connectors.call(name, tool, args) : unpublished(); },+ list: function () { return bridge() ? bridge().connectors.list() : unpublished(); }}};};diff --git a/shared/app.test.ts b/shared/app.test.tsindex 4431f763fc..76894807e1 100644--- a/shared/app.test.ts+++ b/shared/app.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { APP_LIMITS, appBlockedText, appDoneOf, htmlFallbackText, htmlVisibleText, mcpAppFallbackText, parseShowHtmlInput, parseUpdateHtmlInput, utf8Bytes, wrapHtmlFragment } from "./app.ts";+import { APP_LIMITS, appBlockedText, appUsesList, appDoneOf, htmlFallbackText, htmlVisibleText, mcpAppFallbackText, parseShowHtmlInput, parseUpdateHtmlInput, utf8Bytes, wrapHtmlFragment } from "./app.ts";describe("parseShowHtmlInput", () => {it("keeps a whole document as written, trimmed", () => {@@ -121,13 +121,16 @@ describe("htmlVisibleText numeric character references", () => {});});+const USES_HELP = 'uses: a list of "data", "state" and connector tools by exact name: "gmail:GMAIL_FETCH_EMAILS" for a connected app, '+ + '"mcp:<server>:<tool>" for an MCP server; no wildcards. E.g. ["data", "gmail:GMAIL_FETCH_EMAILS"].';+describe("show_html uses", () => {it("reads a list of data and state, and the shapes models send for one", () => {expect(parseShowHtmlInput({ html: "<p>x</p>", title: "t", uses: ["data", "state", "data"] })).toMatchObject({ ok: true, value: { uses: ["data", "state"] } });expect(parseShowHtmlInput({ html: "<p>x</p>", title: "t", uses: "data" })).toMatchObject({ ok: true, value: { uses: ["data"] } });expect(parseShowHtmlInput({ html: "<p>x</p>", title: "t", uses: '["State"]' })).toMatchObject({ ok: true, value: { uses: ["state"] } });expect(parseShowHtmlInput({ html: "<p>x</p>", title: "t", uses: [] }).ok && "uses" in (parseShowHtmlInput({ html: "<p>x</p>", title: "t", uses: [] }) as { value: object }).value).toBe(false);- expect(parseShowHtmlInput({ html: "<p>x</p>", title: "t", uses: ["network"] })).toEqual({ ok: false, error: 'uses: a list of "data" and "state", e.g. ["data", "state"].' });+ expect(parseShowHtmlInput({ html: "<p>x</p>", title: "t", uses: ["network"] })).toEqual({ ok: false, error: USES_HELP });expect(parseShowHtmlInput({ html: "<p>x</p>", title: "t", uses: [{ name: "data" }] }).ok).toBe(false);});@@ -136,3 +139,52 @@ describe("show_html uses", () => {expect(parseUpdateHtmlInput({ app_id: "m1", html: "<p>x</p>" }).ok && "uses" in (parseUpdateHtmlInput({ app_id: "m1", html: "<p>x</p>" }) as { value: object }).value).toBe(false);});});++describe("show_html uses: connector tools", () => {+ const parse = (uses: unknown) => parseShowHtmlInput({ html: "<p>x</p>", title: "t", uses });+ it.each([+ ["one app tool", ["gmail:GMAIL_FETCH_EMAILS"], [{ connector: "gmail", tools: ["GMAIL_FETCH_EMAILS"] }]],+ ["case as models vary it", ["Gmail:gmail_fetch_emails"], [{ connector: "gmail", tools: ["GMAIL_FETCH_EMAILS"] }]],+ ["one app, several tools, a repeat", ["gmail:GMAIL_FETCH_EMAILS", "gmail:GMAIL_SEND_EMAIL", "gmail:GMAIL_FETCH_EMAILS"], [{ connector: "gmail", tools: ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"] }]],+ ["an underscored app", ["bland_ai:BLAND_AI_LIST_CALLS"], [{ connector: "bland_ai", tools: ["BLAND_AI_LIST_CALLS"] }]],+ ["an MCP server's tool, its case kept", ["mcp:Notes:searchNotes"], [{ server: "notes", tools: ["searchNotes"] }]],+ ["the object shapes", [{ connector: "gmail", tools: ["GMAIL_FETCH_EMAILS"] }, { server: "notes", tools: "search,open" }], [{ connector: "gmail", tools: ["GMAIL_FETCH_EMAILS"] }, { server: "notes", tools: ["search", "open"] }]],+ ["one string of several", "data, gmail:GMAIL_FETCH_EMAILS", [{ connector: "gmail", tools: ["GMAIL_FETCH_EMAILS"] }]],+ ["a JSON list", '["gmail:GMAIL_FETCH_EMAILS"]', [{ connector: "gmail", tools: ["GMAIL_FETCH_EMAILS"] }]],+ ])("reads %s", (_name, uses, connectors) => {+ expect(parse(uses)).toMatchObject({ ok: true, value: { connectors } });+ });++ it("keeps data and state beside connector tools, and both are given together", () => {+ expect(parse(["state", "gmail:GMAIL_FETCH_EMAILS"])).toMatchObject({ ok: true, value: { uses: ["state"], connectors: [{ connector: "gmail" }] } });+ expect(parse(["data"])).toMatchObject({ ok: true, value: { uses: ["data"], connectors: [] } });+ expect(parseUpdateHtmlInput({ app_id: "m1", html: "<p>x</p>", uses: ["data"] })).toMatchObject({ ok: true, value: { uses: ["data"], connectors: [] } });+ expect(appUsesList(["data"], [{ connector: "gmail", tools: ["GMAIL_FETCH_EMAILS"] }, { server: "notes", tools: ["search"] }]))+ .toEqual(["data", "gmail:GMAIL_FETCH_EMAILS", "mcp:notes:search"]);+ });++ it.each([+ ["a wildcard", ["gmail:*"], "wildcards"],+ ["a wildcard on a server", ["mcp:notes:*"], "wildcards"],+ ["a tool of another app", ["gmail:SLACK_SEND_MESSAGE"], "is not one of gmail's tools"],+ ["an app with no tool", ["gmail"], USES_HELP],+ ["Composio's own tools", ["composio:COMPOSIO_MULTI_EXECUTE_TOOL"], "is not a connected app's name"],+ ["a connection tool", ["gmail:GMAIL_MANAGE_CONNECTIONS"], "a page cannot call GMAIL_MANAGE_CONNECTIONS"],+ ["a bad server name", ["mcp:no such:search"], "does not name an MCP server"],+ ["an object with both", [{ connector: "gmail", server: "notes", tools: ["x"] }], USES_HELP],+ ["an object with no tools", [{ connector: "gmail", tools: [] }], USES_HELP],+ ])("refuses %s", (_name, uses, error) => {+ const parsed = parse(uses);+ expect(parsed.ok).toBe(false);+ expect(parsed.ok ? "" : parsed.error).toContain(error);+ });++ it("caps the apps and the tools a page names", () => {+ const apps = Array.from({ length: APP_LIMITS.pageConnectors + 1 }, (_, i) => `app${i}:APP${i}_LIST`);+ expect(parse(apps).ok).toBe(false);+ const tools = Array.from({ length: APP_LIMITS.pageConnectorTools + 1 }, (_, i) => `gmail:GMAIL_T${i}`);+ expect(parse(tools)).toEqual({ ok: false, error: `uses: at most ${APP_LIMITS.pageConnectors} connected apps or servers and ${APP_LIMITS.pageConnectorTools} tools in all.` });+ expect(parse(tools.slice(1)).ok).toBe(true);+ });+});+diff --git a/skills/connected-app-pages/SKILL.md b/skills/connected-app-pages/SKILL.mdnew file mode 100644index 0000000000..04da373f0f--- /dev/null+++ b/skills/connected-app-pages/SKILL.md@@ -0,0 +1,68 @@+---+name: connected-app-pages+description: "Build a page shown with show_html that reads from, or acts on, the person's connected apps (Gmail, Calendar, Notion, GitHub and others) or their own MCP tools, through tools the page declares. Use when the person asks for a mini app, a tool or a page over their own mail, calendar, tasks or other connected data."+---++# Pages that use connected apps++A page shown with `show_html` can call connected-app tools itself, after it loads and when the person clicks, with no+turn of yours in between. It runs with the person's own connection and your own access to that app: nothing is put in+the page. So the same page works for anyone who opens it with their own accounts, and a page someone shares never+carries an account.++## Declare each tool++Name every tool the page calls in `uses`, exactly, one entry each. No wildcards, at most 8 apps and 24 tools:++- a connected app's tool: `"gmail:GMAIL_FETCH_EMAILS"` (the app's name, a colon, the tool's exact name);+- an MCP tool the person added: `"mcp:notes:search"` (the word mcp, its name in Settings, the tool).++Use the exact tool names you would call yourself; check one you have not used. `uses` can also hold `"data"` and+`"state"`. A replacement without `uses` keeps what the page declared; one with `uses` replaces all of it.++## Call them from the page++- `await mausbot.connectors.list()`: each declared app with `connected` true or false, its `label` and its `tools`.+ Show "Connect Gmail in Apps" (with the label) for one that is not connected, instead of calling it.+- `await mausbot.connectors.call("gmail", "GMAIL_FETCH_EMAILS", { max_results: 10 })`: the tool's answer, the same+ data you would get. A very large answer comes back cut to its first items. Pass values as arguments only.++A tool whose own listing marks it read-only runs on load. Any other tool (sends, labels, moves, deletes, creates) runs+only from a click handler, and only when you are at Full access: below it, or when you ask before sending, the call is+refused with a sentence that says to ask you in the chat. When an app's listing does not mark its reads, even a read+needs a click and Full access: load on a button then. Each call is checked against your access to that app as it is+now, recorded, and limited: about 30 calls a minute per page, a minute each, 64 KB of arguments. A call that is+refused rejects with a plain sentence: show it in the page.++## Example: recent mail, with one button that changes something++```html+<button id="load">Show my inbox</button><ul id="list"></ul><p id="note"></p>+<script>+const note = (text) => { document.getElementById("note").textContent = text; };+async function load() {+ const [gmail] = await mausbot.connectors.list();+ if (!gmail.connected) return note(`Connect ${gmail.label} in Apps to see your mail here.`);+ const data = await mausbot.connectors.call("gmail", "GMAIL_FETCH_EMAILS", { user_id: "me", query: "in:inbox", max_results: 10 });+ const list = document.getElementById("list");+ list.innerHTML = "";+ for (const mail of data.messages ?? []) {+ const row = document.createElement("li");+ row.textContent = `${mail.sender ?? ""}: ${mail.subject ?? "(no subject)"} `;+ const reply = document.createElement("button");+ reply.textContent = "Draft a thank-you";+ reply.onclick = () => mausbot.connectors.call("gmail", "GMAIL_CREATE_EMAIL_DRAFT", {+ user_id: "me", recipient_email: mail.sender, subject: `Re: ${mail.subject}`, body: "Thank you!", thread_id: mail.threadId,+ }).then(() => { reply.textContent = "Drafted"; }, (error) => note(error.message));+ row.append(reply);+ list.append(row);+ }+}+load().catch((error) => note(error.message));+document.getElementById("load").onclick = () => load().catch((error) => note(error.message));+</script>+```++Show it with `uses: ["gmail:GMAIL_FETCH_EMAILS", "gmail:GMAIL_CREATE_EMAIL_DRAFT"]`. The draft button works only at+Full access; say so in one line when you are not. The arguments are the tool's own, as you would send them. A published page cannot call connected apps: keep these pages in the chat.+In a room, pages cannot call them either.diff --git a/skills/connected-app-pages/manifest.json b/skills/connected-app-pages/manifest.jsonnew file mode 100644index 0000000000..3878c60289--- /dev/null+++ b/skills/connected-app-pages/manifest.json@@ -0,0 +1,24 @@+{+ "id": "connected-app-pages",+ "name": "Pages That Use Connected Apps",+ "version": "1.0.0",+ "description": "Build a page in the chat that reads from, and acts on, the person's connected apps through tools it declares.",+ "defaultEnabled": true,+ "triggerTerms": [+ "mini app",+ "little app",+ "small app",+ "an app that",+ "app for my",+ "page that shows my",+ "page that lists",+ "page for my",+ "page with my",+ "page of my",+ "inbox page",+ "inbox app",+ "triage app",+ "connectors.call"+ ],+ "requiredCapabilities": []+}