Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
My Cloud reaches MCP servers on the person's lent Mac or PC
milind-soni87e622ecf675
diff --git a/electron/computer-sharing.d.mts b/electron/computer-sharing.d.mtsindex 3b5fe42961..2f715e9e2f 100644--- a/electron/computer-sharing.d.mts+++ b/electron/computer-sharing.d.mts@@ -88,6 +88,8 @@ export function createComputerSharing(options: {file: string;fetch: (url: string, init: RequestInit) => Promise<Response>;environments: () => Workspace[];+ /** This computer's own OpenMausBot installs, by environment id: what an MCP server kept for it on a Cloud names. */+ localEnvironments?: () => string[];enabled?: () => Promise<boolean>;protectedPaths?: string[];/** The desktop's cua connection, or why it did not start (`reason` stays on this computer). */@@ -160,6 +162,8 @@ export function createComputerSharing(options: {/** Every Cloud stops using this computer, across restarts too, until resume(). */pause(): void;resume(): Promise<void> | undefined;+ /** Whether every Cloud of the signed-in account's own may run commands here as this user, across restarts too. */+ lendTerminal(on: boolean): Promise<void> | undefined;screenChanged(): Promise<void>;cloudChanged(): void;start(options?: { maintainer?: boolean }): void;diff --git a/electron/computer-sharing.mjs b/electron/computer-sharing.mjsindex a9e4b11e49..8394aab5a2 100644--- a/electron/computer-sharing.mjs+++ b/electron/computer-sharing.mjs@@ -5,6 +5,7 @@ import os from "node:os";import { randomBytes, randomUUID } from "node:crypto";import { setTimeout as delay } from "node:timers/promises";import { createSharedCua, executeSharedOperation, personalSecretPaths, sharedComputerError, validCommandSeconds } from "./shared-computer-access.mjs";+import { createLentMcp, LENT_MCP_ACTIONS, validLentMcpServer } from "./lent-mcp.mjs";import { sharedCuaConnection } from "./shared-cua-connection.mjs";export { sharedCuaConnection };import { createLendingActivity, describeSharedOperation } from "./lending-activity.mjs";@@ -107,8 +108,8 @@ export async function validateSharedFolders(folders, { homeEdits = false } = {})return result;}-const JOB_KEYS = new Set(["computer_id", "action", "folder_id", "path", "content", "encoding", "expected_sha256", "old_text", "new_text", "command", "timeout_seconds", "tool_name", "arguments"]);-const JOB_ACTIONS = new Set(["list_files", "read_file", "write_file", "edit_file", "append_file", "delete_file", "run_command", "computer_tools", "computer_call"]);+const JOB_KEYS = new Set(["computer_id", "action", "folder_id", "path", "content", "encoding", "expected_sha256", "old_text", "new_text", "command", "timeout_seconds", "tool_name", "arguments", "server"]);+const JOB_ACTIONS = new Set(["list_files", "read_file", "write_file", "edit_file", "append_file", "delete_file", "run_command", "computer_tools", "computer_call", ...LENT_MCP_ACTIONS]);const optionalText = (value, max) => value === undefined || (typeof value === "string" && value.length <= max);/** Refuses malformed input only; the grant still decides whether the operation is allowed. */export function validSharedOperation(operation, computerId) {@@ -120,8 +121,9 @@ export function validSharedOperation(operation, computerId) {optionalText(operation.old_text, 350_000) && optionalText(operation.new_text, 350_000) &&(operation.encoding === undefined || operation.encoding === "utf8" || operation.encoding === "base64") &&(operation.expected_sha256 === undefined || (typeof operation.expected_sha256 === "string" && /^[a-f0-9]{64}$/.test(operation.expected_sha256))) &&- optionalText(operation.command, 8000) && validCommandSeconds(operation.timeout_seconds) && optionalText(operation.tool_name, 100) &&- (operation.arguments === undefined || (Boolean(operation.arguments) && typeof operation.arguments === "object" && !Array.isArray(operation.arguments)));+ optionalText(operation.command, 8000) && validCommandSeconds(operation.timeout_seconds) && optionalText(operation.tool_name, 256) &&+ (operation.arguments === undefined || (Boolean(operation.arguments) && typeof operation.arguments === "object" && !Array.isArray(operation.arguments))) &&+ (LENT_MCP_ACTIONS.has(operation.action) ? validLentMcpServer(operation.server) : operation.server === undefined);}export function cloudLendingVerdict(binding, current, env) {@@ -135,6 +137,12 @@ export function cloudLendingVerdict(binding, current, env) {return { allow: true };}+/** What a Cloud that keeps MCP servers for this computer hears: it runs them, and which installs here it is. */+const lendsMcp = environments => {+ const ids = Array.isArray(environments) ? environments.filter(uuid).slice(0, 8) : [];+ return { mcpServers: true, ...(ids.length ? { environments: ids } : {}) };+};+/** A Cloud grant lends the internet connection unless it was unticked: one kept without `internet` lends it too. */const lendsInternet = grant => Boolean(grant?.cloud) && grant.internet !== false;@@ -204,7 +212,7 @@ const BROWSE_NOTE_MS = 10 * 60_000;* this computer is and asks for it when a bot there needs it: `prompt(env, ask, signal)` shows the ask in this app's* own prompt, `startScreen()` starts computer control again (its state after), and `confirmTerminal()` turns on* running commands once the person confirms it here. */-export function createComputerSharing({ file, fetch: fetchImpl, environments, cuaConnection, hostControl, screenLocked = () => false, idleSeconds = () => null, protectedPaths = [], enabled = async () => false, home = os.homedir(), activityFile, cloud = () => null, onChange = () => {}, reconnect = null, now = Date.now, power = createCloudPowerGate(),+export function createComputerSharing({ file, fetch: fetchImpl, environments, localEnvironments = () => [], cuaConnection, hostControl, screenLocked = () => false, idleSeconds = () => null, protectedPaths = [], enabled = async () => false, home = os.homedir(), activityFile, cloud = () => null, onChange = () => {}, reconnect = null, now = Date.now, power = createCloudPowerGate(),linkHeaders = () => ({}), WebSocket: linkSocket = globalThis.WebSocket, egress = {}, chrome = {}, myCloud = () => null, ownClouds = () => [], screen = () => false, askForScreen = () => {}, cloudPower = () => null,prompt = async () => null, startScreen = async () => null, confirmTerminal = async () => false, log = () => {}, t = nativeText.englishText.t }) {const protectedRoots = [path.dirname(file), ...protectedPaths.filter(entry => typeof entry === "string" && entry), ...personalSecretPaths(home)];@@ -351,7 +359,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu.catch(error => { throw error.status === 401 || error.status === 403 ? Object.assign(error, { problem: "connect-first" }) : error; });if (auth.kind !== "session" || !uuid(auth.id) || !uuid(descriptor.environmentId)) throw Object.assign(new Error("Complete server pairing or sign-in first"), { problem: "connect-first" });if (descriptor.capabilities?.sharedComputers !== true) throw new Error("Update this server to enable computer sharing");- return { auth, info: { sessionId: auth.id, environmentId: descriptor.environmentId }, details: descriptor.capabilities?.lendingDetails === true, link: descriptor.capabilities?.deviceLink === true, chrome: descriptor.capabilities?.myChromeLink === true, timeouts: descriptor.capabilities?.commandTimeouts === true, long: descriptor.capabilities?.longCommands === true, edits: descriptor.capabilities?.fileEdits === true, asks: descriptor.capabilities?.computerAsks === true };+ return { auth, info: { sessionId: auth.id, environmentId: descriptor.environmentId }, details: descriptor.capabilities?.lendingDetails === true, link: descriptor.capabilities?.deviceLink === true, chrome: descriptor.capabilities?.myChromeLink === true, timeouts: descriptor.capabilities?.commandTimeouts === true, long: descriptor.capabilities?.longCommands === true, edits: descriptor.capabilities?.fileEdits === true, asks: descriptor.capabilities?.computerAsks === true, mcp: descriptor.capabilities?.lentMcp === true };};const identity = async env => {await requireEnabled();@@ -364,7 +372,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu* server the move chose (lending-target.mjs `own:<environment id>`). */const ownHomeId = env => { const current = cloud(env); return current?.origin === env.origin && current.accountId?.startsWith("own:") ? current.accountId.slice(4) : null; };const cloudIdentity = async env => {- const { auth, info, details, link, chrome: takesChrome, timeouts, long, edits } = await describe(env);+ const { auth, info, details, link, chrome: takesChrome, timeouts, long, edits, mcp } = await describe(env);const own = ownHomeId(env);if (own !== null && (auth.own !== true || info.environmentId !== own)) throw Object.assign(new Error(t("native.lend.homeChanged")), { problem: "not-cloud" });if ((own === null && auth.cloudHome !== true) || !Array.isArray(auth.scopes) || !auth.scopes.includes("admin")) throw Object.assign(new Error("This server is not My Cloud"), { problem: "not-cloud" });@@ -374,8 +382,11 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cuif (timeouts) supportsTimeouts.add(env.id); else supportsTimeouts.delete(env.id);if (long) supportsLong.add(env.id); else supportsLong.delete(env.id);if (edits) supportsEdits.add(env.id); else supportsEdits.delete(env.id);+ if (mcp) supportsMcp.add(env.id); else supportsMcp.delete(env.id);return info;};+ /** The Clouds that keep MCP servers for this computer to run. */+ const supportsMcp = new Set();const supportsDetails = new Set();const supportsLink = new Set();/** The Clouds that take the person's Chrome over the device link. */@@ -409,13 +420,13 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cuconst matches = (grant, info) => grant?.sessionId === info.sessionId && grant?.environmentId === info.environmentId;const stop = id => {const live = running.get(id);- if (live) { live.abort.abort(); live.cua?.close(); running.delete(id); }+ if (live) { live.abort.abort(); live.cua?.close(); live.mcp?.close(); running.delete(id); }status.set(id, { connected: false });};const run = (env, grant) => {stop(env.id);if (closed || !grant.enabled || (grant.cloud ? paused : maintainerOff)) return;- const live = { abort: new AbortController(), cua: null };+ const live = { abort: new AbortController(), cua: null, mcp: null };running.set(env.id, live);const signal = live.abort.signal;const call = (action, body = {}, held = signal) => request(env, `/api/shared-computers/${grant.id}/${action}`, body, held, grant.secret);@@ -453,6 +464,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu...(supportsTimeouts.has(env.id) ? { commandTimeouts: true } : {}),...(supportsLong.has(env.id) ? { longCommands: true } : {}),...(supportsEdits.has(env.id) ? { fileEdits: true } : {}),+ ...(grant.cloud && supportsMcp.has(env.id) ? lendsMcp(localEnvironments()) : {}),}, signal, grant.secret);if (signal.aborted) break;status.set(env.id, { connected: true });@@ -509,7 +521,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, culive.cua = createSharedCua(mcp, { t });}return live.cua;- });+ }, () => (live.mcp ??= createLentMcp()));} catch (error) { result = sharedComputerError(error); live.cua?.close(); live.cua = null; }finally {clearInterval(heartbeat); ended = true;diff --git a/electron/lending-activity.mjs b/electron/lending-activity.mjsindex 342a32973d..7d63d62c2e 100644--- a/electron/lending-activity.mjs+++ b/electron/lending-activity.mjs@@ -22,6 +22,8 @@ export function describeSharedOperation(grant, operation) {}case "run_command": return clean(operation.command, 300);case "computer_call": return clean(operation.tool_name, 100);+ case "mcp_tools": return clean(operation.server?.name, 100);+ case "mcp_call": return clean(`${operation.server?.name ?? ""} ${operation.tool_name ?? ""}`, 300);default: return "";}}diff --git a/electron/lent-mcp.d.mts b/electron/lent-mcp.d.mtsnew file mode 100644index 0000000000..e0b8c1e2b5--- /dev/null+++ b/electron/lent-mcp.d.mts@@ -0,0 +1,17 @@+export type LentMcpServer =+ | { name: string; command: string; args: string[]; env: Record<string, string> }+ | { name: string; url: string; type: "http" | "sse"; headers: Record<string, string> };+export const LENT_MCP_ACTIONS: ReadonlySet<"mcp_tools" | "mcp_call">;+export function validLentMcpServer(server: unknown): server is LentMcpServer;+export function isLoopbackAddress(url: string): boolean;+export function lentMcpRefusal(grant: { cloud?: unknown; terminal?: boolean }, server: LentMcpServer): string | null;+export function ownEnvironmentIds(dataDirs: ReadonlyArray<string | null | undefined>): string[];+export function inheritedEnvironment(env?: NodeJS.ProcessEnv): Record<string, string>;+export function createLentMcp(options?: {+ environment?: () => Record<string, string> | Promise<Record<string, string>>;+ home?: string;+ fetch?: typeof fetch;+}): {+ call(operation: { action: "mcp_tools" | "mcp_call"; server: LentMcpServer; tool_name?: string; arguments?: Record<string, unknown> }, signal: AbortSignal): Promise<unknown>;+ close(): void;+};diff --git a/electron/lent-mcp.mjs b/electron/lent-mcp.mjsnew file mode 100644index 0000000000..79d11098d9--- /dev/null+++ b/electron/lent-mcp.mjs@@ -0,0 +1,267 @@+// The MCP servers a Cloud of the person's own keeps for this computer: each started, or reached, exactly as that Cloud's+// job gives it, only as this computer's lending allows, and kept running between calls. Security: no other address is+// fetched and no other program started, a URL server is sent MCP messages only, and its keys are never written down+// here or put into an error.+import { createHash } from "node:crypto";+import { spawn } from "node:child_process";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import readline from "node:readline";+import { commandPath } from "./shell-path.mjs";++export const LENT_MCP_ACTIONS = new Set(["mcp_tools", "mcp_call"]);+const NAME = /^[a-z][a-z0-9_-]{0,31}$/;+const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,255}$/;+const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,256}$/;+const LOOPBACK = /^(?:localhost|127(?:\.\d{1,3}){3}|::1)$/i;+const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;+/** A package runner fetches its program the first time it starts. */+const START_MS = 130_000;+const CALL_MS = 300_000;+const IDLE_MS = 10 * 60_000;+/** The server reads a result body of at most 4,000,000 bytes. */+const RESULT_LIMIT = 3_900_000;+const MAX_PAGES = 10;+const PROTOCOL = "2025-03-26";++/** What a lent server inherits from this app: where things live, never a key. */+const INHERITED = ["HOME", "USERPROFILE", "USER", "LOGNAME", "SHELL", "LANG", "TMPDIR", "TEMP", "TMP", "PATHEXT", "SystemRoot", "SystemDrive", "windir", "APPDATA", "LOCALAPPDATA", "ProgramData"];+export const inheritedEnvironment = (env = process.env) => Object.fromEntries(INHERITED.filter(key => env[key]).map(key => [key, env[key]]));++const record = value => Boolean(value) && typeof value === "object" && !Array.isArray(value);+const secrets = (value, name) => record(value) && Object.keys(value).length <= 64 && Object.entries(value).every(([key, item]) => name.test(key) && typeof item === "string" && item.length <= 16_384);++/** The server a job names, in the shape the Cloud sends it; anything else is refused before it is looked at again. */+export function validLentMcpServer(server) {+ if (!record(server) || typeof server.name !== "string" || !NAME.test(server.name)) return false;+ const keys = Object.keys(server).sort().join();+ if (keys === "args,command,env,name") {+ return typeof server.command === "string" && server.command.trim().length > 0 && server.command.length <= 1024 &&+ Array.isArray(server.args) && server.args.length <= 64 && server.args.every(arg => typeof arg === "string" && arg.length <= 4096) && secrets(server.env, ENV_NAME);+ }+ return keys === "headers,name,type,url" && typeof server.url === "string" && server.url.length <= 2048 && (server.type === "http" || server.type === "sse") && secrets(server.headers, HEADER_NAME);+}++export function isLoopbackAddress(url) {+ try {+ const parsed = new URL(url);+ return (parsed.protocol === "http:" || parsed.protocol === "https:") && !parsed.username && !parsed.password && LOOPBACK.test(parsed.hostname.replace(/^\[|\]$/g, ""));+ } catch { return false; }+}++/** Why this computer won't run `server` for this grant, or null. A command server starts a program here, which only a+ * lent terminal allows; a URL server must be at this computer's own loopback address. */+export function lentMcpRefusal(grant, server) {+ if (!grant?.cloud) return "MCP servers run here only for the person's own Clouds";+ if ("command" in server) return grant.terminal === true ? null : "Running commands is not enabled for this server";+ if (!isLoopbackAddress(server.url)) return "Only an MCP server at this computer's own address (127.0.0.1, localhost or ::1) can be reached";+ if (server.type === "sse") return "This MCP server uses the older SSE transport, which lending doesn't carry yet";+ return null;+}++/** This computer's own OpenMausBot installs, by the environment id each keeps in its data folder. */+export function ownEnvironmentIds(dataDirs) {+ const ids = new Set();+ for (const dir of dataDirs) {+ if (typeof dir !== "string" || !dir) continue;+ try {+ const id = fs.readFileSync(path.join(dir, "environment-id"), "utf8").trim();+ if (UUID.test(id)) ids.add(id.toLowerCase());+ } catch {}+ }+ return [...ids].slice(0, 8);+}++const hash = server => createHash("sha256").update(JSON.stringify(server)).digest("hex");+const failure = message => new Error(message);+/** The server answered the request with an error: it is still running. */+const refusal = message => Object.assign(new Error(message), { answered: true });++/** Windows starts a .cmd shim (npx.cmd, uvx.cmd) only through cmd.exe, so there each word is quoted for it. */+const windowsWord = word => (/[\s"]/.test(word) ? `"${word.replace(/"/g, '\\"')}"` : word);++function killTree(child) {+ if (!child.pid) return;+ if (process.platform === "win32") {+ const killer = spawn("taskkill", ["/PID", String(child.pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" });+ killer.on("error", () => child.kill());+ } else {+ try { process.kill(-child.pid, "SIGKILL"); } catch { child.kill("SIGKILL"); }+ }+}++function stdioClient(server, { environment, home }) {+ const windows = process.platform === "win32";+ const child = spawn(windows ? windowsWord(server.command) : server.command, windows ? server.args.map(windowsWord) : server.args, {+ cwd: home, detached: !windows, windowsHide: true, shell: windows, stdio: ["pipe", "pipe", "ignore"], env: { ...environment, ...server.env },+ });+ let sequence = 0; let closed = null; let bytes = 0;+ const pending = new Map();+ const end = error => {+ if (closed) return;+ closed = error;+ for (const item of pending.values()) item.reject(error);+ pending.clear(); killTree(child);+ };+ child.on("error", error => end(failure(error.code === "ENOENT" ? `${server.name} could not start: ${path.basename(server.command)} is not on this computer` : `${server.name} could not start`)));+ child.stdin.on("error", () => end(failure(`${server.name} stopped`)));+ child.on("exit", () => end(failure(`${server.name} stopped`)));+ child.stdout.on("data", chunk => { bytes += chunk.length; if (bytes > RESULT_LIMIT) end(failure(`${server.name} answered with more than ${RESULT_LIMIT} bytes`)); });+ const lines = readline.createInterface({ input: child.stdout });+ const write = message => child.stdin.write(`${JSON.stringify(message)}\n`);+ lines.on("line", line => {+ let message; try { message = JSON.parse(line); } catch { return; }+ if (!record(message)) return;+ // A server's own request (roots, sampling) is one this client does not offer.+ if (typeof message.method === "string" && Object.hasOwn(message, "id")) return void write({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "Not offered by OpenMausBot" } });+ const waiting = pending.get(message.id);+ if (!waiting) return;+ pending.delete(message.id); bytes = 0;+ if (message.error) waiting.reject(refusal(String(message.error.message ?? `${server.name} refused the request`))); else waiting.resolve(message.result);+ });+ return {+ request(method, params, signal, ms) {+ return new Promise((resolve, reject) => {+ if (closed) return reject(closed);+ const id = ++sequence;+ const stop = () => { cleanup(); pending.delete(id); reject(failure(`${server.name} did not answer in time`)); end(failure(`${server.name} stopped`)); };+ const timer = setTimeout(stop, ms);+ const cleanup = () => { clearTimeout(timer); signal.removeEventListener("abort", stop); };+ signal.addEventListener("abort", stop, { once: true });+ pending.set(id, { resolve: value => { cleanup(); resolve(value); }, reject: error => { cleanup(); reject(error); } });+ write({ jsonrpc: "2.0", id, method, params });+ });+ },+ notify(method) { if (!closed) write({ jsonrpc: "2.0", method }); },+ close() { lines.close(); end(failure(`${server.name} stopped`)); },+ };+}++/** One JSON-RPC answer out of a Streamable HTTP reply: a JSON body, or the event in an event stream that carries it. */+async function answerOf(response, id, name) {+ const reader = response.body?.getReader();+ if (!reader) throw failure(`${name} sent an empty answer`);+ const stream = (response.headers.get("content-type") ?? "").includes("text/event-stream");+ const decoder = new TextDecoder();+ let text = ""; let size = 0;+ const matching = value => [value].flat().find(message => record(message) && message.id === id);+ try {+ for (;;) {+ const { value, done } = await reader.read();+ if (value) { size += value.byteLength; if (size > RESULT_LIMIT) throw failure(`${name} answered with more than ${RESULT_LIMIT} bytes`); text += decoder.decode(value, { stream: true }); }+ if (stream) {+ const events = text.split(/\r?\n\r?\n/);+ text = done ? "" : events.pop() ?? "";+ for (const event of events) {+ const data = event.split(/\r?\n/).filter(line => line.startsWith("data:")).map(line => line.slice(5).trimStart()).join("\n");+ let message; try { message = JSON.parse(data); } catch { continue; }+ const found = matching(message);+ if (found) return found;+ }+ }+ if (done) break;+ }+ } finally { await reader.cancel().catch(() => {}); }+ if (stream) throw failure(`${name} ended its answer without a reply`);+ let parsed; try { parsed = JSON.parse(text); } catch { throw failure(`${name} sent an answer that is not JSON`); }+ const found = matching(parsed);+ if (!found) throw failure(`${name} sent no reply to the request`);+ return found;+}++function httpClient(server, { fetch: fetchImpl }) {+ let session = null; let protocol = null; let sequence = 0;+ const target = new URL(server.url);+ const send = async (message, signal, ms) => {+ let response;+ try {+ response = await fetchImpl(server.url, {+ method: "POST", redirect: "error", cache: "no-store", signal: AbortSignal.any([signal, AbortSignal.timeout(ms)]),+ headers: { ...server.headers, "content-type": "application/json", accept: "application/json, text/event-stream", ...(session ? { "mcp-session-id": session } : {}), ...(protocol ? { "mcp-protocol-version": protocol } : {}) },+ body: JSON.stringify(message),+ });+ } catch (error) {+ if (error?.name === "TimeoutError") throw failure(`${server.name} did not answer in time`);+ if (signal.aborted) throw failure("The requesting turn ended");+ throw failure(`${server.name} is not answering at ${target.host} on this computer`);+ }+ const id = response.headers.get("mcp-session-id");+ if (id) session = id;+ if (!Object.hasOwn(message, "id")) { await response.body?.cancel().catch(() => {}); return null; }+ if (!response.ok) {+ await response.body?.cancel().catch(() => {});+ if (response.status === 404 && session) { session = null; protocol = null; throw Object.assign(failure(`${server.name} forgot its session`), { expired: true }); }+ throw failure(response.status === 401 || response.status === 403 ? `${server.name} refused its saved keys (HTTP ${response.status})` : `${server.name} answered HTTP ${response.status}`);+ }+ const answer = await answerOf(response, message.id, server.name);+ if (answer.error) throw refusal(String(answer.error.message ?? `${server.name} refused the request`));+ return answer.result;+ };+ return {+ request: (method, params, signal, ms) => send({ jsonrpc: "2.0", id: ++sequence, method, params }, signal, ms),+ notify(method) { void send({ jsonrpc: "2.0", method }, new AbortController().signal, 10_000).catch(() => {}); },+ started(version) { protocol = typeof version === "string" ? version : PROTOCOL; },+ close() { session = null; },+ };+}++/** The servers one lent Cloud keeps here, each started once and kept between calls; a change to one starts it anew, and+ * one unused for ten minutes is stopped. */+export function createLentMcp({ environment = async () => ({ ...inheritedEnvironment(), PATH: await commandPath() }), home = os.homedir(), fetch: fetchImpl = globalThis.fetch } = {}) {+ const running = new Map();+ const stop = name => { const live = running.get(name); if (!live) return; clearTimeout(live.idle); live.client.close(); running.delete(name); };+ const ready = async (server, signal) => {+ const key = hash(server);+ const known = running.get(server.name);+ if (known?.key === key && !known.failed) return known;+ stop(server.name);+ const client = "command" in server ? stdioClient(server, { environment: await environment(), home }) : httpClient(server, { fetch: fetchImpl });+ const live = { key, client, idle: null, failed: false, started: null };+ running.set(server.name, live);+ live.started = client.request("initialize", { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "openmausbot-lent", version: "1" } }, signal, START_MS).then(result => {+ client.started?.(result?.protocolVersion);+ client.notify("notifications/initialized");+ });+ live.started.catch(() => {});+ return live;+ };+ const use = async (server, signal, work) => {+ for (let attempt = 0; ; attempt++) {+ const live = await ready(server, signal);+ clearTimeout(live.idle);+ try {+ await live.started;+ const result = await work(live.client);+ live.idle = setTimeout(() => stop(server.name), IDLE_MS);+ live.idle.unref?.();+ return result;+ } catch (error) {+ if (error?.answered) { live.idle = setTimeout(() => stop(server.name), IDLE_MS); live.idle.unref?.(); throw error; }+ live.failed = true; stop(server.name);+ if (!error?.expired || attempt > 0) throw error;+ }+ }+ };+ return {+ async call(operation, signal) {+ const { server } = operation;+ if (operation.action === "mcp_tools") {+ return use(server, signal, async client => {+ const tools = [];+ let cursor;+ for (let page = 0; page < MAX_PAGES; page++) {+ const listed = await client.request("tools/list", cursor ? { cursor } : {}, signal, START_MS);+ if (Array.isArray(listed?.tools)) tools.push(...listed.tools);+ cursor = typeof listed?.nextCursor === "string" && listed.nextCursor ? listed.nextCursor : undefined;+ if (!cursor) break;+ }+ return { tools };+ });+ }+ if (typeof operation.tool_name !== "string" || !operation.tool_name) throw failure("Name the tool to call");+ return use(server, signal, client => client.request("tools/call", { name: operation.tool_name, arguments: operation.arguments ?? {} }, signal, CALL_MS));+ },+ close() { for (const name of running.keys()) stop(name); },+ };+}diff --git a/electron/lent-mcp.node-test.mjs b/electron/lent-mcp.node-test.mjsnew file mode 100644index 0000000000..c696f38ee2--- /dev/null+++ b/electron/lent-mcp.node-test.mjs@@ -0,0 +1,161 @@+import assert from "node:assert/strict";+import { test } from "node:test";+import { createServer } from "node:http";+import { mkdtemp, mkdir, realpath, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { randomUUID } from "node:crypto";+import { createLentMcp, isLoopbackAddress, lentMcpRefusal, ownEnvironmentIds, validLentMcpServer } from "./lent-mcp.mjs";+import { executeSharedOperation } from "./shared-computer-access.mjs";+import { validSharedOperation } from "./computer-sharing.mjs";++const signal = () => new AbortController().signal;+const http = (url, headers = {}) => ({ name: "local", url, type: "http", headers });++/** A stdio MCP server: `whoami` answers with its process id and the key it was started with, `fail` with an error. */+const SERVER_SCRIPT = `+import readline from "node:readline";+const send = message => process.stdout.write(JSON.stringify(message) + "\\n");+readline.createInterface({ input: process.stdin }).on("line", line => {+ const message = JSON.parse(line);+ if (!("id" in message)) return;+ if (message.method === "initialize") return send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: "fixture", version: "1" } } });+ if (message.method === "tools/list") return send({ jsonrpc: "2.0", id: message.id, result: message.params.cursor ? { tools: [{ name: "fail", inputSchema: { type: "object" } }] } : { tools: [{ name: "whoami", inputSchema: { type: "object" } }], nextCursor: "2" } });+ if (message.params.name === "fail") return send({ jsonrpc: "2.0", id: message.id, error: { code: -32602, message: "no such thing" } });+ send({ jsonrpc: "2.0", id: message.id, result: { content: [{ type: "text", text: JSON.stringify({ pid: process.pid, key: process.env.NOTES_TOKEN, cwd: process.cwd() }) }] } });+});+`;++async function stdioFixture(t) {+ const dir = await realpath(await mkdtemp(path.join(tmpdir(), "omb-lent-mcp-")));+ t.after(() => rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }));+ const script = path.join(dir, "server.mjs");+ await writeFile(script, SERVER_SCRIPT);+ const home = path.join(dir, "home");+ await mkdir(home);+ const lent = createLentMcp({ environment: () => ({ PATH: process.env.PATH ?? "" }), home });+ t.after(() => lent.close());+ return { dir, home, script, lent, server: { name: "notes", command: process.execPath, args: [script], env: { NOTES_TOKEN: "saved-env-key" } } };+}++test("takes a server only in the shape the Cloud sends, and an MCP job only with its server", () => {+ const command = { name: "notes", command: "npx", args: ["-y", "notes-mcp"], env: { NOTES_TOKEN: "x" } };+ assert.equal(validLentMcpServer(command), true);+ assert.equal(validLentMcpServer(http("http://127.0.0.1:1/mcp")), true);+ for (const bad of [{ ...command, extra: 1 }, { ...command, name: "Bad" }, { ...command, env: { "BAD NAME": "x" } }, { ...command, args: "x" }, { name: "local", url: "http://127.0.0.1/", type: "ws", headers: {} }, null]) {+ assert.equal(validLentMcpServer(bad), false, JSON.stringify(bad));+ }+ const id = randomUUID();+ assert.equal(validSharedOperation({ computer_id: id, action: "mcp_tools", server: command }, id), true);+ assert.equal(validSharedOperation({ computer_id: id, action: "mcp_call", server: command, tool_name: "x".repeat(200), arguments: {} }, id), true);+ assert.equal(validSharedOperation({ computer_id: id, action: "mcp_tools" }, id), false);+ assert.equal(validSharedOperation({ computer_id: id, action: "read_file", server: command }, id), false);+});++test("security: only the person's own Cloud, a command only with the terminal lent, an address only on this computer, MCP only", () => {+ const command = { name: "notes", command: "npx", args: [], env: {} };+ const cloud = { cloud: { accountId: "a", origin: "https://x" }, terminal: false };+ assert.match(lentMcpRefusal({ terminal: true }, command), /only for the person's own Clouds/);+ assert.match(lentMcpRefusal(cloud, command), /Running commands is not enabled/);+ assert.equal(lentMcpRefusal({ ...cloud, terminal: true }, command), null);+ assert.equal(lentMcpRefusal(cloud, http("http://127.0.0.1:19501/mcp")), null);+ assert.equal(lentMcpRefusal(cloud, http("http://[::1]:19501/mcp")), null);+ for (const url of ["http://192.168.1.10:8080/mcp", "https://example.com/mcp", "http://127.0.0.1.nip.io/mcp", "http://user:[email protected]/mcp", "file:///etc/passwd"]) {+ assert.equal(isLoopbackAddress(url), false, url);+ assert.match(lentMcpRefusal(cloud, http(url)), /this computer's own address/);+ }+ assert.match(lentMcpRefusal(cloud, { ...http("http://127.0.0.1:1/sse"), type: "sse" }), /older SSE transport/);+});++test("the executor refuses before anything starts when the grant doesn't allow it", async () => {+ let started = 0;+ const grant = { enabled: true, folders: [], terminal: false, computer: false, cloud: { accountId: "a", origin: "https://x" } };+ const operation = { action: "mcp_tools", server: { name: "notes", command: "touch", args: ["/tmp/never"], env: {} } };+ await assert.rejects(executeSharedOperation(grant, operation, signal(), null, () => { started++; return null; }), /Running commands is not enabled/);+ await assert.rejects(executeSharedOperation({ ...grant, cloud: undefined, terminal: true }, operation, signal(), null, () => { started++; return null; }), /own Clouds/);+ await assert.rejects(executeSharedOperation({ ...grant, enabled: false }, operation, signal(), null, () => { started++; return null; }), /sharing is off/);+ assert.equal(started, 0);+});++test("a command server starts once, from the home folder, with its saved key, and keeps running between calls", async t => {+ const { lent, server, home } = await stdioFixture(t);+ const listed = await lent.call({ action: "mcp_tools", server }, signal());+ assert.deepEqual(listed.tools.map(tool => tool.name), ["whoami", "fail"], "every page");+ const first = JSON.parse((await lent.call({ action: "mcp_call", server, tool_name: "whoami", arguments: {} }, signal())).content[0].text);+ assert.equal(first.key, "saved-env-key");+ assert.equal(await realpath(first.cwd), await realpath(home));+ await assert.rejects(lent.call({ action: "mcp_call", server, tool_name: "fail" }, signal()), /no such thing/);+ const again = JSON.parse((await lent.call({ action: "mcp_call", server, tool_name: "whoami" }, signal())).content[0].text);+ assert.equal(again.pid, first.pid, "an error from the server leaves it running");+ const changed = { ...server, env: { NOTES_TOKEN: "new-key" } };+ const fresh = JSON.parse((await lent.call({ action: "mcp_call", server: changed, tool_name: "whoami" }, signal())).content[0].text);+ assert.notEqual(fresh.pid, first.pid, "a changed server starts anew");+ assert.equal(fresh.key, "new-key");+});++test("a command server that can't start says so by its program's name, never with its keys", async t => {+ const { lent } = await stdioFixture(t);+ const missing = { name: "notes", command: path.join(tmpdir(), "omb-no-such-program"), args: [], env: { NOTES_TOKEN: "never-echoed" } };+ await assert.rejects(lent.call({ action: "mcp_tools", server: missing }, signal()), error => {+ assert.match(error.message, /notes could not start: omb-no-such-program is not on this computer/);+ assert.doesNotMatch(error.message, /never-echoed/);+ return true;+ });+});++async function httpFixture(t, answer) {+ const seen = [];+ const server = createServer(async (req, res) => {+ let body = ""; for await (const chunk of req) body += chunk;+ const message = body ? JSON.parse(body) : null;+ seen.push({ method: req.method, url: req.url, headers: req.headers, message });+ answer(req, res, message);+ });+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));+ t.after(() => new Promise(resolve => server.close(resolve)));+ return { seen, url: `http://127.0.0.1:${server.address().port}/mcp` };+}++test("an address on this computer gets MCP messages with its saved headers, as JSON or an event stream, in one session", async t => {+ const { seen, url } = await httpFixture(t, (req, res, message) => {+ if (!("id" in message)) { res.writeHead(202).end(); return; }+ if (message.method === "initialize") { res.writeHead(200, { "content-type": "application/json", "mcp-session-id": "s-1" }).end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: "2025-03-26" } })); return; }+ if (message.method === "tools/list") { res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result: { tools: [{ name: "search" }] } })); return; }+ res.writeHead(200, { "content-type": "text/event-stream" });+ res.write(`event: message\ndata: ${JSON.stringify({ jsonrpc: "2.0", method: "notifications/progress", params: {} })}\n\n`);+ res.end(`event: message\ndata: ${JSON.stringify({ jsonrpc: "2.0", id: message.id, result: { content: [{ type: "text", text: `found ${message.params.arguments.q}` }] } })}\n\n`);+ });+ const lent = createLentMcp();+ t.after(() => lent.close());+ const server = http(url, { Authorization: "Bearer saved-header" });+ assert.deepEqual(await lent.call({ action: "mcp_tools", server }, signal()), { tools: [{ name: "search" }] });+ assert.deepEqual(await lent.call({ action: "mcp_call", server, tool_name: "search", arguments: { q: "plan" } }, signal()), { content: [{ type: "text", text: "found plan" }] });+ assert.deepEqual(seen.map(request => request.message.method), ["initialize", "notifications/initialized", "tools/list", "tools/call"]);+ assert.ok(seen.every(request => request.method === "POST" && request.url === "/mcp" && request.headers.authorization === "Bearer saved-header"));+ assert.deepEqual(seen.slice(1).map(request => request.headers["mcp-session-id"]), ["s-1", "s-1", "s-1"]);+});++test("an address that refuses its keys, redirects or isn't there says so plainly, with no key in the words", async t => {+ const { url } = await httpFixture(t, (req, res, message) => {+ if (req.headers.authorization === "Bearer wrong") { res.writeHead(401).end(); return; }+ res.writeHead(302, { location: "https://example.com/" }).end();+ void message;+ });+ const lent = createLentMcp();+ t.after(() => lent.close());+ await assert.rejects(lent.call({ action: "mcp_tools", server: http(url, { Authorization: "Bearer wrong" }) }, signal()), error => {+ assert.equal(error.message, "local refused its saved keys (HTTP 401)");+ return true;+ });+ await assert.rejects(lent.call({ action: "mcp_tools", server: http(url) }, signal()), /local is not answering at 127\.0\.0\.1:\d+ on this computer/);+ await assert.rejects(lent.call({ action: "mcp_tools", server: http("http://127.0.0.1:9/mcp") }, signal()), /local is not answering at 127\.0\.0\.1:9 on this computer/);+});++test("this computer's own installs, by the environment id each keeps", async t => {+ const dir = await realpath(await mkdtemp(path.join(tmpdir(), "omb-lent-mcp-ids-")));+ t.after(() => rm(dir, { recursive: true, force: true }));+ const id = randomUUID();+ await mkdir(path.join(dir, "a")); await writeFile(path.join(dir, "a", "environment-id"), `${id}\n`);+ await mkdir(path.join(dir, "b")); await writeFile(path.join(dir, "b", "environment-id"), "not-an-id");+ assert.deepEqual(ownEnvironmentIds([path.join(dir, "a"), path.join(dir, "b"), path.join(dir, "missing"), null, path.join(dir, "a")]), [id]);+});diff --git a/electron/main.mjs b/electron/main.mjsindex 8bcc0a8b47..362410927c 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -89,7 +89,7 @@ import capabilitiesModule from "./capabilities.cjs";import environmentsModule from "./environments.cjs";import localOriginModule from "./local-origin.cjs";import { buildApplicationMenu } from "./menu.mjs";-import { createComputerSharing, isHomeFolder, validateSharedFolders } from "./computer-sharing.mjs";+import { createComputerSharing, isHomeFolder, validateSharedFolders } from "./computer-sharing.mjs"; import { ownEnvironmentIds } from "./lent-mcp.mjs";import { createHostScreenLease } from "./host-screen-lease.mjs";import { acquireDataDirLease } from "./data-dir-lease.mjs";import { switchLocalEnvironment } from "./environment-switch.mjs";@@ -1443,7 +1443,7 @@ function sharingController() {// Holds provider API keys and sessions.json: a broad share must never reach it.protectedPaths: [desktopDataDir()],fetch: (...args) => session.defaultSession.fetch(...args),- environments: () => environmentsState.environments,+ environments: () => environmentsState.environments, localEnvironments: () => ownEnvironmentIds([desktopDataDir(), runningDataDir]),enabled: refreshSharedComputersAllowed, t: nativeT,cloud: lendingTarget.cloud, myCloud: lendingTarget.environment, ownClouds: lendingTarget.places, screen: screenControl.now, askForScreen, power: cloudPower, cloudPower: origin => cloudAccount?.powerOf?.(origin) ?? null, reconnect: reconnectCloud,prompt: createAskPrompt({ t: nativeT, dialog, window: () => mainWindow, idleSeconds: () => powerMonitor.getSystemIdleState(1) === "unknown" ? null : powerMonitor.getSystemIdleTime() }), startScreen: screenControl.start, confirmTerminal: () => lendingDialogs.lendTerminal(true, () => sharingController().lendTerminal(true)), log: slog,diff --git a/electron/shared-computer-access.mjs b/electron/shared-computer-access.mjsindex 13d9a9a7ad..ddd6382421 100644--- a/electron/shared-computer-access.mjs+++ b/electron/shared-computer-access.mjs@@ -9,6 +9,7 @@ import { lentScreenArguments, lentScreenToolListing } from "./lent-screen-tools.import { typeOneCharacterAtATime, typesInOneBurst } from "./paced-typing.mjs";import { helperMissing } from "./lent-screen-failures.mjs";import { commandPath } from "./shell-path.mjs";+import { LENT_MCP_ACTIONS, lentMcpRefusal } from "./lent-mcp.mjs";/** Reads stay under the 4 MB body that carries a result to the server (base64 of 2 MiB is 2.8 MB); writes stay small. */const READ_LIMIT = 2 * 1024 * 1024;@@ -290,9 +291,14 @@ export function createSharedCua(connection, { platform = process.platform, t } =};}-export async function executeSharedOperation(grant, operation, signal, cua) {+export async function executeSharedOperation(grant, operation, signal, cua, lentMcp) {signal.throwIfAborted();if (grant.enabled !== true) throw new Error("Computer sharing is off");+ if (LENT_MCP_ACTIONS.has(operation.action)) {+ const refused = lentMcpRefusal(grant, operation.server);+ if (refused) throw new Error(refused);+ return (await lentMcp()).call(operation, signal);+ }if (operation.action === "run_command") {if (grant.terminal !== true) throw new Error("Terminal access is not enabled for this server");return sharedCommand(operation.command, grant.folders[0]?.path ?? process.env.HOME ?? process.env.USERPROFILE, signal, operation.timeout_seconds);diff --git a/server/chat-apps-mcp.ts b/server/chat-apps-mcp.tsindex 9012a23d70..4b9a4d92a3 100644--- a/server/chat-apps-mcp.ts+++ b/server/chat-apps-mcp.ts@@ -392,7 +392,7 @@ export function createChatAppsMcp(deps: ChatAppsMcpDeps): ChatAppsMcp {queued.delete(name);if (closed || deps.personMcp?.().includes(name)) return;const stored = storedServer(name, deps.storedServers()[name]);- if (!stored?.enabled || stored.apps === false) return;+ if (!stored?.enabled || stored.apps === false || stored.runsOn) return;if (isRemoteMcpServer(stored) && deps.oauth.authState(name, stored.url) === "needs-sign-in") return;const target = isRemoteMcpServer(stored) ? await signedIn(name, stored) : stored;if (!target) return;@@ -420,7 +420,7 @@ export function createChatAppsMcp(deps: ChatAppsMcpDeps): ChatAppsMcp {const startup = deps.startupProbes === false ? undefined : setTimeout(() => {for (const [name, raw] of Object.entries(deps.storedServers())) {const stored = storedServer(name, raw);- if (stored?.enabled && stored.apps !== false && isRemoteMcpServer(stored) && catalog.stale(name, stored)) probeStale(name);+ if (stored?.enabled && stored.apps !== false && !stored.runsOn && isRemoteMcpServer(stored) && catalog.stale(name, stored)) probeStale(name);}}, STARTUP_PROBE_DELAY_MS);startup?.unref?.();diff --git a/server/cloud-connections-host.ts b/server/cloud-connections-host.tsindex 9288e3f765..560935709b 100644--- a/server/cloud-connections-host.ts+++ b/server/cloud-connections-host.ts@@ -40,7 +40,7 @@ export interface CloudConnectionsHostDeps {/** The person's mailboxes: what a move carries, and what takes them on the Cloud they move to. */email?: { accounts(): readonly EmailAccount[]; adopt(accounts: unknown[]): { adopted: number; kept: number } };/** How the person hears what stayed on their computer; a Cloud home only. */- stayedNotices?: Pick<StayedNoticesDeps, "bots" | "say" | "notify" | "language">;+ stayedNotices?: Pick<StayedNoticesDeps, "bots" | "say" | "notify" | "language" | "lent">;}const managedService = (): boolean => { try { return brokerAccess() !== null; } catch { return false; } };@@ -102,7 +102,7 @@ export function createCloudConnectionsHost(deps: CloudConnectionsHostDeps) {return answerConnection(what.id, sources());},- prompt: (bot: ConnectionPromptBot): string => prompt?.(bot) ?? "",+ prompt: (bot: ConnectionPromptBot, lent?: ReadonlyMap<string, string>): string => prompt?.(bot, lent) ?? "",/** What stayed on the person's computer: said when the move ends, and in the first conversation with each bot. */moved: (language?: string): void => stayed?.moved(language),personTurn: (bot: Parameters<NonNullable<typeof stayed>["personTurn"]>[0], threadId: string): void => stayed?.personTurn(bot, threadId),diff --git a/server/cloud-connections-prompt.test.ts b/server/cloud-connections-prompt.test.tsindex 6dc1b5b401..272a5276d8 100644--- a/server/cloud-connections-prompt.test.ts+++ b/server/cloud-connections-prompt.test.ts@@ -34,6 +34,14 @@ describe("what a bot on My Cloud is told about connections that need the person"expect(prompt({ mcpServers: ["dodo", "off"] })).toBe("");});+ it("in a turn, a server on the person's computer is named only when it can't be reached now, with the reason lending gives", () => {+ const prompt = createConnectionPrompt(sources(), ORIGIN);+ expect(prompt({ mcpServers: ["notes"] }, new Map()), "reached through the lent computer: nothing to say").toBe("");+ const offline = "notes runs on your Mac (Milind's MacBook), which is offline right now: OpenMausBot on it is closed, or the Mac is asleep or off.";+ expect(prompt({ mcpServers: ["notes"] }, new Map([["notes", offline]]))).toBe(+ ` Runs on the person's own computer and can't be reached now: ${offline} If a task needs one, tell the person that in plain words, and do not write your own replacement.`);+ });+it("says nothing of a server signed in here, or one that needs no sign-in", () => {const prompt = createConnectionPrompt(sources({ linear: "signed-in", jira: "signed-in" }), ORIGIN);expect(prompt({ mcpServers: ["dodo", "linear", "jira"] })).toBe("");diff --git a/server/cloud-connections-prompt.ts b/server/cloud-connections-prompt.tsindex 08fb1667b0..202ce5c942 100644--- a/server/cloud-connections-prompt.ts+++ b/server/cloud-connections-prompt.ts@@ -26,8 +26,10 @@ export interface ConnectionPromptSources {export type ConnectionPromptBot = { mcpServers?: string[]; composio?: boolean; connectorTools?: Record<string, ConnectorToolGrant> };-/** `origin`: My Cloud's public address, where `/?connect=<id>` opens the page that connects it. */-export function createConnectionPrompt(sources: ConnectionPromptSources, origin: string): (bot: ConnectionPromptBot) => string {+/** `origin`: My Cloud's public address, where `/?connect=<id>` opens the page that connects it. `lent`, in a turn: by+ * name, why each of the bot's servers that runs on the person's computer can't be reached now; one left out reaches the+ * turn through that computer. */+export function createConnectionPrompt(sources: ConnectionPromptSources, origin: string): (bot: ConnectionPromptBot, lent?: ReadonlyMap<string, string>) => string {const known = new Map<string, { at: number; connected: boolean }>();let reading: Promise<void> | null = null;let failedAt = 0;@@ -47,7 +49,7 @@ export function createConnectionPrompt(sources: ConnectionPromptSources, origin:const link = (id: string) => `${origin}/?connect=${encodeURIComponent(id)}`;- return (bot) => {+ return (bot, lent) => {const toConnect: string[] = [];const elsewhere = new Map<string, string[]>();for (const stayed of stayedConnectors(sources.mcpServers(), sources.programs?.() ?? [])) {@@ -72,7 +74,9 @@ export function createConnectionPrompt(sources: ConnectionPromptSources, origin:from ? ` You moved to My Cloud from the person's computer ${from}, with everything in OpenMausBot. What lives outside OpenMausBot stayed on ${from}: its other folders and files, passkeys, the person's own browser sessions and apps, Local VM disks and model servers on its home network. When a task needs one, use ${from} if it is lent to My Cloud and online; otherwise say in plain words that it stayed there.` : "",toConnect.length ? ` Not connected on My Cloud yet: ${toConnect.join("; ")}. When a task needs one, say in plain words that it needs the person once on My Cloud and give its link; do not try another way.` : "",apps.length ? ` Assigned to this bot but not connected on My Cloud yet: ${apps.join(", ")}. When a task needs one, call COMPOSIO_MANAGE_CONNECTIONS for it, which shows the person a card to connect it, and end the turn.` : "",- ...[...elsewhere].map(([computer, names]) => ` Runs only on the person's computer ${computer}, not on My Cloud: ${names.join("; ")}. It worked there before the bots moved here. If a task needs one, tell the person in plain words that it stayed on ${computer} and why, not that it was never set up, and do not write your own replacement.`),+ ...(lent+ ? (lent.size ? [` Runs on the person's own computer and can't be reached now: ${[...lent.values()].join(" ")} If a task needs one, tell the person that in plain words, and do not write your own replacement.`] : [])+ : [...elsewhere].map(([computer, names]) => ` Runs only on the person's computer ${computer}, not on My Cloud: ${names.join("; ")}. It worked there before the bots moved here. If a task needs one, tell the person in plain words that it stayed on ${computer} and why, not that it was never set up, and do not write your own replacement.`)),].join("");};}diff --git a/server/cloud-connections-stayed.test.ts b/server/cloud-connections-stayed.test.tsindex 7c76d0cd03..209d38a342 100644--- a/server/cloud-connections-stayed.test.ts+++ b/server/cloud-connections-stayed.test.ts@@ -19,13 +19,14 @@ const SERVERS = {const dirs: string[] = [];afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });-function fixture(bots: Array<{ id: string; name: string; threadId: string; chiefOfStaff?: boolean; mcpServers?: string[]; toolScope?: unknown }>, servers: Record<string, unknown> = SERVERS, file?: string, mailConnected?: () => boolean) {+function fixture(bots: Array<{ id: string; name: string; threadId: string; chiefOfStaff?: boolean; mcpServers?: string[]; toolScope?: unknown }>, servers: Record<string, unknown> = SERVERS, file?: string, mailConnected?: () => boolean, lent?: (runsOn: { environmentId: string; label: string }) => boolean) {const dir = mkdtempSync(join(tmpdir(), "omb-stayed-")); dirs.push(dir);const said: Array<{ threadId: string; text: string; kind: string }> = [];const notified: Array<{ text: string; bot: string; threadId: string }> = [];const notices = createStayedNotices({file: file ?? join(dir, "told.json"), origin: "https://omb-u-1.fly.dev", servers: () => servers, programs: () => ["npx", "node", "python3"], bots: () => bots, language: () => undefined,...(mailConnected ? { mailConnected } : {}),+ ...(lent ? { lent } : {}),say: (threadId, text, kind) => { said.push({ threadId, text, kind }); },notify: (text, bot, threadId) => { notified.push({ text, bot: bot.id, threadId }); },});@@ -33,11 +34,23 @@ function fixture(bots: Array<{ id: string; name: string; threadId: string; chief}describe("what stayed on the person's computer", () => {+ it("says nothing stayed when the computer a connector runs on is lent here, since bots reach it through that computer", () => {+ const bots = [{ id: "a", name: "Ada", threadId: "t-a", chiefOfStaff: true }];+ const lentHere = fixture(bots, SERVERS, undefined, undefined, (runsOn) => runsOn.environmentId === MAC.environmentId);+ lentHere.notices.moved();+ lentHere.notices.personTurn(bots[0]!, "t-a");+ expect(lentHere.said).toEqual([]);+ expect(lentHere.notified).toEqual([]);+ const notLent = fixture(bots, SERVERS, undefined, undefined, () => false);+ notLent.notices.moved();+ expect(notLent.said).toHaveLength(1);+ });+it("names each connector that runs elsewhere with why, and leaves out one that was off anyway", () => {expect(stayedConnectors(SERVERS, ["npx", "node", "python3"])).toEqual([- { name: "easy", computer: "Mac mini", why: { kind: "mail" } },- { name: "fetch", computer: "Mac mini", why: { kind: "program", program: "uvx" } },- { name: "notes", computer: "Mac mini", why: { kind: "here" } },+ { name: "easy", computer: "Mac mini", runsOn: MAC, why: { kind: "mail" } },+ { name: "fetch", computer: "Mac mini", runsOn: MAC, why: { kind: "program", program: "uvx" } },+ { name: "notes", computer: "Mac mini", runsOn: MAC, why: { kind: "here" } },]);});diff --git a/server/cloud-connections-stayed.ts b/server/cloud-connections-stayed.tsindex 282ad35295..359a4dc0d5 100644--- a/server/cloud-connections-stayed.ts+++ b/server/cloud-connections-stayed.ts@@ -6,7 +6,7 @@ import { readFileSync } from "node:fs";import { canUseMcpServer } from "../shared/tool-scope.ts";import { writeFileAtomic } from "./atomic.ts";import { isMailConnector, launcherOf } from "./cloud-connections.ts";-import { isRemoteMcpServer, parseStoredMcpServer } from "./mcp-registry.ts";+import { isRemoteMcpServer, parseStoredMcpServer, type McpRunsOn } from "./mcp-registry.ts";import { serverLine } from "./server-lines.ts";export type StayedWhy = { kind: "mail" } | { kind: "program"; program: string } | { kind: "here" };@@ -15,6 +15,7 @@ export interface StayedConnector {name: string;/** The computer it runs on, by the name the person knows it by. */computer: string;+ runsOn: McpRunsOn;why: StayedWhy;/** The one bot it serves, when it is that bot's own. */bot?: string;@@ -29,7 +30,7 @@ export function stayedConnectors(servers: Record<string, unknown> | undefined, pconst remote = isRemoteMcpServer(server);const program = remote ? "" : launcherOf(server.command);const why: StayedWhy = isMailConnector(server) ? { kind: "mail" } : !remote && !/[\\/]/u.test(server.command) && !programs.includes(program) ? { kind: "program", program } : { kind: "here" };- return [{ name, computer: server.runsOn!.label, why, ...(!remote && server.bot ? { bot: server.bot } : {}) }];+ return [{ name, computer: server.runsOn!.label, runsOn: server.runsOn!, why, ...(!remote && server.bot ? { bot: server.bot } : {}) }];});}@@ -59,6 +60,8 @@ export interface StayedNoticesDeps {programs(): readonly string[];/** A mailbox is connected here, so a mail connector left behind is no longer missed. */mailConnected?(): boolean;+ /** The computer it runs on is lent here, so bots reach it through that computer and nothing stayed behind. */+ lent?(runsOn: McpRunsOn): boolean;bots(): readonly Bot[];/** A line in a bot's own chat, in the conversation the person is looking at. */say(threadId: string, text: string, kind: "line" | "row"): void;@@ -81,7 +84,7 @@ export function createStayedNotices(deps: StayedNoticesDeps) {(all[key(stayed)] ??= []).push(bot.id);try { writeFileAtomic(deps.file, JSON.stringify(all), { mode: 0o600 }); } catch (error) { console.warn("[connections] could not save what was said about what stayed:", error); }};- const stayed = () => stayedConnectors(deps.servers(), deps.programs()).filter((connector) => connector.why.kind !== "mail" || !deps.mailConnected?.());+ const stayed = () => stayedConnectors(deps.servers(), deps.programs()).filter((connector) => (connector.why.kind !== "mail" || !deps.mailConnected?.()) && !deps.lent?.(connector.runsOn));const serves = (bot: Bot, connector: StayedConnector) => (connector.bot ? connector.bot === bot.id : !bot.mcpServers || bot.mcpServers.includes(connector.name)) && canUseMcpServer(bot.toolScope, connector.name);return {diff --git a/server/cloud-connections.e2e.test.ts b/server/cloud-connections.e2e.test.tsindex 4cefb061da..bf4605fcda 100644--- a/server/cloud-connections.e2e.test.ts+++ b/server/cloud-connections.e2e.test.ts@@ -144,7 +144,7 @@ it("moves the MCP servers with their secrets and sign-ins, the keys and the connexpect(servers.find((server) => server.name === "notes")).toMatchObject({ enabled: true, runsOn: collected.computer });expect(servers.find((server) => server.name === "easy"), "a mail connector stays with its accounts, whatever programs My Cloud has").toMatchObject({ enabled: true, runsOn: collected.computer });const notesTest = await onCloud("POST", "/api/mcp/servers/notes/test");- expect(notesTest).toMatchObject({ status: 409, body: { error: `This server runs on ${collected.computer.label}, so it isn't started here.` } });+ expect(notesTest).toMatchObject({ status: 409, body: { error: `notes runs on ${collected.computer.label}, which isn't lent to My Cloud: it works once OpenMausBot is open on that computer and signed in to My Cloud.` } });// The sign-in moved: My Cloud refreshes it with the refresh token and the app's secret that came over...await onCloud("POST", "/api/mcp/servers/linear/test");diff --git a/server/cloud-lent-mcp.e2e.test.ts b/server/cloud-lent-mcp.e2e.test.tsnew file mode 100644index 0000000000..abd49360a3--- /dev/null+++ b/server/cloud-lent-mcp.e2e.test.ts@@ -0,0 +1,262 @@+// A real server booted as a Cloud home, the real outbound connector on the Mac side, and two MCP servers on the Mac: one+// a program, one at a loopback address. Each runs only where the Mac lends it, and a bot's turn on My Cloud reaches it as+// any other MCP server.+import { randomBytes, randomUUID } from "node:crypto";+import { spawn, type ChildProcess } from "node:child_process";+import { createServer, type Server } from "node:http";+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";+import { hostname, tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { createInterface } from "node:readline";+import { fileURLToPath, pathToFileURL } from "node:url";+import { afterAll, beforeAll, expect, it } from "vitest";+import { createComputerSharing } from "../electron/computer-sharing.mjs";+import { cloudPairingSignature } from "./cloud-home.ts";+import { removeTempDir, waitForExit } from "./testing/cleanup.ts";+import { hostTimeout } from "./testing/host-timeout.ts";+import { freePortBlock } from "./testing/ports.ts";++const SERVER_DIR = dirname(fileURLToPath(import.meta.url));+const HOST = "omb-t-0123456789ab.fly.dev";+const MAC_INSTALL = randomUUID();+const secret = randomBytes(32).toString("base64url");+let home = "";+let base = "";+let port = 0;+let child: ChildProcess;+let log = "";+let owner = "";+let connector: ReturnType<typeof createComputerSharing> | undefined;+let macServer: Server | undefined;+const macRequests: Array<{ authorization?: string; method?: string; client?: string }> = [];+const engines: ChildProcess[] = [];++async function api(method: string, path: string, options: { body?: unknown; token?: string } = {}) {+ const response = await fetch(`${base}${path}`, {+ method,+ headers: {+ host: HOST, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https", origin: `https://${HOST}`,+ ...(options.token ? { authorization: `Bearer ${options.token}` } : {}),+ ...(options.body === undefined ? {} : { "content-type": "application/json" }),+ },+ body: options.body === undefined ? undefined : JSON.stringify(options.body),+ });+ return { status: response.status, body: await response.json().catch(() => null) as any };+}++async function adminPairing(): Promise<string> {+ const body = JSON.stringify({ label: "OpenMausBot app (Cloud)", ttlSeconds: 300 });+ const timestamp = String(Math.floor(Date.now() / 1000)), nonce = randomBytes(16).toString("base64url");+ const response = await fetch(`${base}/api/cloud/pairing`, { method: "POST", headers: {+ host: HOST, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https", "content-type": "application/json",+ "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce, "x-omb-cloud-signature": `v1=${cloudPairingSignature(secret, timestamp, nonce, body)}`,+ }, body });+ const granted = await response.json() as { code: string };+ const paired = await api("POST", "/api/auth/pair", { body: { code: granted.code } });+ expect(paired.status, JSON.stringify(paired.body)).toBe(200);+ return paired.body.token;+}++type Spec = { url?: string; headers?: Record<string, string>; command?: string; args?: string[]; env?: Record<string, string> };+type Turn = { systemPrompt?: string; mcpConfig: { mcpServers: Record<string, Spec & { env?: Record<string, string> }> } };+const turnDumps = () => join(home, "turns");+const readTurns = () => new Map(readdirSync(turnDumps()).filter((name) => name.endsWith(".json")).flatMap((name) => {+ try { return [[name, readFileSync(join(turnDumps(), name), "utf8")] as const]; } catch { return []; }+}));++/** The turn a message to a new bot starts, as its engine was given it. */+async function turnOf(name: string): Promise<Turn> {+ const bot = (await api("POST", "/api/bots", { token: owner, body: { name, modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } } })).body.bot;+ const before = readTurns();+ expect((await api("POST", `/api/bots/${bot.id}/messages`, { token: owner, body: { text: "Search my notes on my Mac." } })).status).toBe(202);+ let turn: Turn | undefined;+ await expect.poll(() => {+ for (const [file, text] of readTurns()) {+ if (before.get(file) === text) continue;+ try { const found = JSON.parse(text) as Turn; if (found.mcpConfig?.mcpServers?.agents?.env?.OMB_BOT_ID === bot.id) { turn = found; return true; } } catch {}+ }+ return false;+ }, { timeout: 15_000 }).toBe(true);+ return turn!;+}++/** Talks to one MCP server of a turn as its engine would: over HTTP at its address, or through the stdio gate it runs. */+function engineFor(spec: Spec): (method: string, params?: unknown) => Promise<any> {+ if (spec.url) {+ let id = 0;+ return async (method, params = {}) => {+ const response = await fetch(spec.url!, { method: "POST", headers: { ...spec.headers, "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify({ jsonrpc: "2.0", id: ++id, method, params }) });+ return (await response.json()) as any;+ };+ }+ const engine = spawn(spec.command!, spec.args ?? [], { env: { PATH: process.env.PATH, HOME: home, ...spec.env }, stdio: ["pipe", "pipe", "pipe"] });+ engines.push(engine);+ const replies = new Map<number, (value: any) => void>();+ createInterface({ input: engine.stdout! }).on("line", (line) => { try { const message = JSON.parse(line); replies.get(message.id)?.(message); replies.delete(message.id); } catch {} });+ let id = 0;+ return (method, params = {}) => new Promise((resolve) => {+ const next = ++id; replies.set(next, resolve);+ engine.stdin!.write(`${JSON.stringify({ jsonrpc: "2.0", id: next, method, params })}\n`);+ });+}++async function connected(call: ReturnType<typeof engineFor>) {+ expect((await call("initialize", { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "engine", version: "1" } })).result).toBeTruthy();+ return call;+}++beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), "omb-cloud-lent-mcp-"));+ const dataDir = join(home, ".openmausbot");+ mkdirSync(dataDir, { recursive: true });+ mkdirSync(turnDumps());+ const cli = join(home, "fixture-claude.mjs");+ writeFileSync(cli, `#!/usr/bin/env node+if (process.argv[2] === "auth") { console.log(JSON.stringify({ loggedIn: true, email: "[email protected]" })); process.exit(0); }+process.env.FAKE_CLAUDE_VERSION = "2.1.284";+if (process.argv[2] !== "--version") { process.env.FAKE_CLAUDE_DUMP = ${JSON.stringify(join(home, "turns"))} + "/" + process.pid + ".json"; process.env.FAKE_CLAUDE_TEXT_DUMP = ${JSON.stringify(join(home, "one-shot.json"))}; process.env.FAKE_CLAUDE_MODE = "hang"; }+await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-claude-cli.ts")).href)});+`, { mode: 0o755 });+ writeFileSync(join(dataDir, "config.json"), JSON.stringify({ instances: {+ ...Object.fromEntries(["codex", "cursor", "githubCopilot", "openaiCompat", "qwen", "hermes", "pi", "grok"].map((id) => [id, { driver: "not-a-real-driver" }])),+ claude: { driver: "claudeAgent", displayName: "Claude", config: { cli } },+ } }));+ port = await freePortBlock([0, 1]);+ base = `http://127.0.0.1:${port}`;+ const offlinePrelude = `data:text/javascript,${encodeURIComponent('const real = globalThis.fetch; globalThis.fetch = async (url, init) => String(url).startsWith("http://127.0.0.1:") ? real(url, init) : new Response("offline fixture", { status: 503 });')}`;+ child = spawn(process.execPath, ["--import", offlinePrelude, join(SERVER_DIR, "index.ts")], {+ cwd: join(SERVER_DIR, ".."),+ env: {+ PATH: process.env.PATH, ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}),+ HOME: home, USERPROFILE: home, OMB_DATA_DIR: dataDir, OMB_PORT: String(port), OMB_WEBHOOK_PORT: String(port + 1),+ OMB_CLOUD_ROLE: "home", OMB_CLOUD_MACHINE_ID: "3f9c2a4e-8b1d-4c6e-9a7f-2d5e8c1b0a93", OMB_CLOUD_ADMIN_URL: "https://cloud.example.test",+ OMB_CLOUD_BOOTSTRAP_SECRET: secret, OMB_PUBLIC_URL: `https://${HOST}`,+ },+ stdio: ["ignore", "pipe", "pipe"],+ });+ child.stdout?.on("data", (chunk) => { log += chunk; });+ child.stderr?.on("data", (chunk) => { log += chunk; });+ const deadline = Date.now() + 20_000;+ for (;;) {+ if (child.exitCode !== null) throw new Error(`the Cloud home exited:\n${log}`);+ try { if ((await fetch(`${base}/api/health`)).ok) break; } catch {}+ if (Date.now() > deadline) throw new Error(`the Cloud home did not start:\n${log}`);+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ owner = await adminPairing();+}, hostTimeout(30_000));++afterAll(async () => {+ connector?.close();+ for (const engine of engines) engine.kill();+ await new Promise((resolve) => (macServer ? macServer.close(resolve) : resolve(null)));+ if (child) await waitForExit(child, { signal: "SIGTERM" });+ if (home) await removeTempDir(home);+});++it("a bot on My Cloud uses MCP servers on the person's lent Mac, only as the Mac lends them, and is told plainly when it can't", async () => {+ // On the Mac: an MCP server at a loopback address, and one that is a program.+ macServer = createServer(async (req, res) => {+ let body = ""; for await (const chunk of req) body += chunk;+ const message = JSON.parse(body);+ macRequests.push({ authorization: req.headers.authorization, method: message.method, client: message.params?.clientInfo?.name });+ if (!("id" in message)) { res.writeHead(202).end(); return; }+ const result = message.method === "initialize" ? { protocolVersion: "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: "mac-notes", version: "1" } }+ : message.method === "tools/list" ? { tools: [{ name: "search_notes", description: "Search the notes on this Mac", inputSchema: { type: "object", properties: { q: { type: "string" } } } }] }+ : { content: [{ type: "text", text: `On the Mac: ${message.params.arguments.q}` }] };+ res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }));+ });+ await new Promise<void>((resolve) => macServer!.listen(0, "127.0.0.1", resolve));+ const macUrl = `http://127.0.0.1:${(macServer.address() as { port: number }).port}/mcp`;+ const script = join(home, "mac-program.mjs");+ writeFileSync(script, `import readline from "node:readline";+const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");+readline.createInterface({ input: process.stdin }).on("line", (line) => {+ const message = JSON.parse(line);+ if (!("id" in message)) return;+ if (message.method === "initialize") return send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: "mac-program", version: "1" } } });+ if (message.method === "tools/list") return send({ jsonrpc: "2.0", id: message.id, result: { tools: [{ name: "whoami", inputSchema: { type: "object" } }] } });+ send({ jsonrpc: "2.0", id: message.id, result: { content: [{ type: "text", text: JSON.stringify({ parent: process.ppid, key: process.env.NOTES_TOKEN }) }] } });+});+`);++ // As the move left them on My Cloud: marked as running on the Mac.+ const runsOn = { environmentId: MAC_INSTALL, label: "Ada's Mac" };+ for (const [name, server] of Object.entries({ local: { type: "http", url: macUrl, headers: { Authorization: "Bearer mac-header-key" } }, notes: { command: process.execPath, args: [script], env: { NOTES_TOKEN: "mac-env-key" } } })) {+ expect((await api("POST", "/api/mcp/servers", { token: owner, body: { name, ...server, runsOn } })).status).toBe(201);+ expect((await api("PATCH", `/api/mcp/servers/${name}`, { token: owner, body: { enabled: true } })).status).toBe(200);+ }+ const notYet = await api("POST", "/api/mcp/servers/local/test", { token: owner });+ expect(notYet).toEqual({ status: 409, body: { error: "local runs on Ada's Mac, which isn't lent to My Cloud: it works once OpenMausBot is open on that computer and signed in to My Cloud." } });++ // The Mac lends itself to My Cloud through the real connector, terminal off as lending starts.+ const env = { id: "my-cloud", name: "My Cloud", origin: base };+ const file = join(home, "desktop-profile", "computer-sharing.json");+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, JSON.stringify({ version: 1, records: { [env.id]: { sessionId: null, environmentId: null, id: randomUUID(), secret: randomBytes(32).toString("hex"), enabled: true,+ folders: [], terminal: false, computer: false, internet: true, cloud: { accountId: "acct_fixture", origin: base } } } }));+ connector = createComputerSharing({+ file, environments: () => [env], localEnvironments: () => [MAC_INSTALL], myCloud: () => env, ownClouds: () => [env], cuaConnection: async () => null, enabled: async () => false,+ cloud: () => ({ status: "connected", accountId: "acct_fixture", origin: base }), home: join(home, "mac-home"),+ fetch: (url: string, init: RequestInit) => fetch(url, { ...init, headers: { ...init.headers as Record<string, string>, authorization: `Bearer ${owner}`, host: HOST, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https", origin: `https://${HOST}` } }),+ });+ connector.start();+ await expect.poll(() => connector!.cloudState(env).connected, { timeout: 8000 }).toBe(true);+ const name = hostname().slice(0, 120);++ // Test, from Settings: the address server's tools, listed on the Mac; the program needs the Mac's terminal.+ expect(await api("POST", "/api/mcp/servers/local/test", { token: owner })).toEqual({ status: 200, body: { ok: true, tools: [{ name: "search_notes", description: "Search the notes on this Mac" }] } });+ const program = await api("POST", "/api/mcp/servers/notes/test", { token: owner });+ expect(program.status).toBe(409);+ expect(program.body.error).toContain(`notes starts a program on`);+ expect(program.body.error).toContain("which doesn't let My Cloud run programs right now");++ // A bot's turn: the address server is one of its MCP servers, at My Cloud's own address with no Mac key in it.+ const first = await turnOf("Notes bot");+ const local = first.mcpConfig.mcpServers.local!;+ expect(local).toBeDefined();+ expect(first.mcpConfig.mcpServers.notes).toBeUndefined();+ expect(JSON.stringify(first.mcpConfig)).not.toMatch(/mac-header-key|mac-env-key|mac-program/);+ expect(first.systemPrompt).toContain("notes starts a program on");+ const call = await connected(engineFor(local));+ const listed = await call("tools/list");+ expect(listed.result.tools.map((tool: { name: string }) => tool.name)).toEqual(["search_notes"]);+ const answer = await call("tools/call", { name: "search_notes", arguments: { q: "plan" } });+ expect(answer.result).toEqual({ content: [{ type: "text", text: "On the Mac: plan" }] });+ // It reached the Mac's server from the Mac's connector, with the key saved on My Cloud.+ expect(macRequests.filter((request) => request.method === "initialize").every((request) => request.client === "openmausbot-lent")).toBe(true);+ expect(macRequests.every((request) => request.authorization === "Bearer mac-header-key")).toBe(true);+ expect(connector.activity(env.id).map((entry) => [entry.action, entry.ok])).toEqual(expect.arrayContaining([["mcp_tools", true], ["mcp_call", true]]));++ // The person lets My Cloud run commands on this Mac: the program starts there, from the connector, never on My Cloud.+ await connector.lendTerminal(true);+ await expect.poll(async () => (await api("GET", "/api/shared-computers", { token: owner })).body.computers?.[0]?.scopes?.terminal, { timeout: 8000 }).toBe(true);+ const second = await turnOf("Program bot");+ const notes = second.mcpConfig.mcpServers.notes!;+ expect(notes).toBeDefined();+ const programCall = await connected(engineFor(notes));+ const who = JSON.parse((await programCall("tools/call", { name: "whoami", arguments: {} })).result.content[0].text);+ expect(who).toEqual({ parent: process.pid, key: "mac-env-key" });+ expect(who.parent).not.toBe(child.pid);++ // A server added on My Cloud at a loopback address nothing there answers is marked as running on this Mac; one on the+ // internet is not.+ const closed = await freePortBlock([0]);+ const added = await api("POST", "/api/mcp/servers", { token: owner, body: { name: "fresh", type: "http", url: `http://127.0.0.1:${closed}/mcp`, headers: {} } });+ expect(added.status).toBe(201);+ expect(added.body.servers.find((server: { name: string }) => server.name === "fresh")).toMatchObject({ runsOn: { environmentId: MAC_INSTALL, label: name } });+ const web = await api("POST", "/api/mcp/servers", { token: owner, body: { name: "web", type: "http", url: "https://mcp.example.com/mcp", headers: {} } });+ expect(web.body.servers.find((server: { name: string }) => server.name === "web")).not.toHaveProperty("runsOn");++ // The person pauses lending: Test and the bot's call both say so in plain words, and nothing reaches the Mac.+ connector.pause();+ await expect.poll(async () => (await api("POST", "/api/mcp/servers/local/test", { token: owner })).status, { timeout: 8000 }).toBe(409);+ const paused = await api("POST", "/api/mcp/servers/local/test", { token: owner });+ expect(paused.body.error).toMatch(/^local runs on .+, which no longer lends itself to My Cloud: OpenMausBot on it is paused or signed out\.$/);+ const before = macRequests.length;+ const refused = await call("tools/call", { name: "search_notes", arguments: { q: "plan" } });+ expect(refused.result.isError).toBe(true);+ expect(refused.result.content[0].text).toContain("no longer lends itself to My Cloud");+ expect(refused.result.content[0].text).not.toContain("Could not reach");+ expect(macRequests.length).toBe(before);+}, hostTimeout(90_000));diff --git a/server/environment.test.ts b/server/environment.test.tsindex 06eeab8fce..d79b422dc0 100644--- a/server/environment.test.ts+++ b/server/environment.test.ts@@ -129,7 +129,7 @@ describe("environment identity", () => {expect(environmentDescriptor({ environmentId: "abc", desktopManaged: true, sharedComputers: false }).capabilities).not.toHaveProperty("sharedComputers");expect(environmentDescriptor({ environmentId: "abc", desktopManaged: true, sharedComputers: true }).capabilities)- .toEqual({ remoteSessions: true, sharedComputers: true, lendingDetails: true, commandTimeouts: true, longCommands: true, fileEdits: true, selfUpdate: "desktop-managed", emailSignIn: false, jobs: true });+ .toEqual({ remoteSessions: true, sharedComputers: true, lendingDetails: true, commandTimeouts: true, longCommands: true, fileEdits: true, lentMcp: true, selfUpdate: "desktop-managed", emailSignIn: false, jobs: true });expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, cloudHome: true }).capabilities).toEqual({ remoteSessions: true, cloudHome: true, move: 1, selfUpdate: "operator", emailSignIn: false, jobs: true });expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, cloudHome: false }).capabilities).not.toHaveProperty("cloudHome");@@ -138,10 +138,17 @@ describe("environment identity", () => {expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, ownHome: false }).capabilities).not.toHaveProperty("move");// A lent computer may lend its internet connection only to a Cloud home that lends at all.expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, cloudHome: true, sharedComputers: true }).capabilities)- .toEqual({ remoteSessions: true, sharedComputers: true, lendingDetails: true, commandTimeouts: true, longCommands: true, fileEdits: true, deviceLink: true, myChromeLink: true, computerAsks: true, cloudHome: true, move: 1, selfUpdate: "operator", emailSignIn: false, jobs: true });+ .toEqual({ remoteSessions: true, sharedComputers: true, lendingDetails: true, commandTimeouts: true, longCommands: true, fileEdits: true, deviceLink: true, lentMcp: true, myChromeLink: true, computerAsks: true, cloudHome: true, move: 1, selfUpdate: "operator", emailSignIn: false, jobs: true });expect(environmentDescriptor({ environmentId: "abc", desktopManaged: true, sharedComputers: true }).capabilities).not.toHaveProperty("deviceLink");});+ it("advertises lentMcp wherever computers are lent, except on a team Cloud", () => {+ const base = { environmentId: "abc", desktopManaged: false };+ expect(environmentDescriptor({ ...base, sharedComputers: true, cloudHome: true }).capabilities.lentMcp).toBe(true);+ expect(environmentDescriptor({ ...base, sharedComputers: true, cloudHome: true, cloudTeam: true }).capabilities).not.toHaveProperty("lentMcp");+ expect(environmentDescriptor({ ...base, sharedComputers: false, cloudHome: true }).capabilities).not.toHaveProperty("lentMcp");+ });+it("advertises myChromeLink only on a personal Cloud home with lending", () => {const base = { environmentId: "abc", desktopManaged: false };expect(environmentDescriptor({ ...base, sharedComputers: true, cloudHome: true }).capabilities.myChromeLink).toBe(true);diff --git a/server/environment.ts b/server/environment.tsindex 8fc89cc37c..6df8f4c189 100644--- a/server/environment.ts+++ b/server/environment.ts@@ -39,6 +39,8 @@ export interface EnvironmentDescriptor {longCommands?: true;/** A lent computer may say it takes edit_file, append_file and delete_file; only then does this server send them. */fileEdits?: true;+ /** A lent computer may say it runs the MCP servers saved here that run on it (mcp_tools, mcp_call). Never a team Cloud. */+ lentMcp?: true;/** A person's own OMB Cloud home. */cloudHome?: true;/** A team's Cloud home: `label` is the team's name. */@@ -152,6 +154,7 @@ export function environmentDescriptor(input: { environmentId: string; desktopMan// lendingDetails: a lent computer may say its platform, and this server remembers what was lent to it....(input.sharedComputers === true ? { sharedComputers: true as const, lendingDetails: true as const, commandTimeouts: true as const, longCommands: true as const, fileEdits: true as const } : {}),...(input.sharedComputers === true && input.cloudHome === true ? { deviceLink: true as const } : {}),+ ...(input.sharedComputers === true && input.cloudTeam !== true ? { lentMcp: true as const } : {}),...(input.sharedComputers === true && input.cloudHome === true && input.cloudTeam !== true ? { myChromeLink: true as const, computerAsks: true as const } : {}),...(input.cloudHome === true ? { cloudHome: true as const, move: 1 as const } : {}),...(input.ownHome === true && input.cloudHome !== true ? { move: 1 as const } : {}),diff --git a/server/host/mcp-chat.ts b/server/host/mcp-chat.tsindex b119b262cb..e8da58b607 100644--- a/server/host/mcp-chat.ts+++ b/server/host/mcp-chat.ts@@ -9,6 +9,7 @@ import { appendDecision } from "../decision-log.ts";import { json } from "../harness/http.ts";import type { ManagedDesktopPolicy } from "../managed-policy.ts";import { mcpOAuthRedirectUri, type McpOAuthManager } from "../mcp-oauth.ts";+import type { LentMcp } from "../lent-mcp.ts";import { listMcpServers } from "../mcp-registry.ts";import type { RequestAuth } from "../request-auth.ts";import { applyMcpChange, showMcpActivity, type InternalMcpDeps } from "../routes/internal-mcp.ts";@@ -42,6 +43,8 @@ export interface McpChatDeps {broadcast(payload: Record<string, unknown>): void;publicOrigins(): ReadonlyArray<string | null | undefined>;threadVisible(auth: RequestAuth, threadId: string): boolean;+ /** MCP servers that run on a computer lent here. Built after this module, so read when used. */+ lending?(): Pick<LentMcp, "place" | "principal">;}const mcpServerUrl = (server: object) => ("url" in server && typeof server.url === "string" ? server.url : undefined);@@ -108,9 +111,18 @@ export function createMcpChat(deps: McpChatDeps) {usedBy: (name) => store.bots.filter((bot) => bot.id !== sender.id && !bot.hidden && Object.hasOwn(mcpServersHost.mounted(bot), name) && canUseMcpServer(bot.toolScope, name)).map((bot) => bot.name),requestApproval: ({ action, name, subtitle, targetHash, fields }) => mcpRequests.propose({ action, name, botId: sender.id, threadId, targetHash }, subtitle, fields, from),requestSignIn: (name, server) => mcpSignInCards.request({ bot: sender, threadId, ...(from ? { from } : {}) }, name, server),+ ...lentDeps(sender, threadId, generation),};}+ /** In a live turn, whose lent computers it may use, and where a server it adds that needs the person's computer runs. */+ function lentDeps(sender: BotRecord, threadId: string, generation: string | undefined): Pick<InternalMcpDeps, "lender" | "place"> {+ const lending = deps.lending?.();+ if (!lending || !generation) return {};+ const lender = () => lending.principal({ botId: sender.id, threadId, generation });+ return { lender, place: (server, computer) => lending.place(server, { principal: lender(), ...(computer ? { computer } : {}) }) };+ }+function mcpServerResponse() {const policy = managedPolicy.current();const servers = listMcpServers(cfg.mcpServers).map((server) => {diff --git a/server/host/mcp-config.ts b/server/host/mcp-config.tsindex f24f7a6a3e..bba64d71c0 100644--- a/server/host/mcp-config.ts+++ b/server/host/mcp-config.ts@@ -35,6 +35,8 @@ export interface McpConfigDeps {botsPath?(): BrokerPath | null;/** How Test starts a command server when no bot asks: as the turns of its bot, or of any bot (server/mcp-probe.ts `asBot`). */probeAs?(server: { bot?: string }): NonNullable<McpProbeOptions["asBot"]>;+ /** Test for a server that runs on another computer: on that computer, through lending, for whoever tests (`lender`). */+ testElsewhere?(name: string, server: StoredMcpServer & { runsOn: McpRunsOn }, lender: string | null, signal: AbortSignal): Promise<McpConfigResult>;}export type McpConfigRefusal = { status: number; error: string; code?: string } & Partial<Pick<UserError, "errorKey" | "errorParams">>;@@ -57,6 +59,8 @@ export interface McpConfig {signal: AbortSignal;/** A person's own connection, asked for only when the server is theirs; null when there is no one to answer for it. */person?: (url: string) => { oauth: McpOAuthManager; key?: { header: string; value: string } } | null;+ /** Whose lent computers a server that runs elsewhere is tested on; null or absent: nobody's. */+ lender?: string | null;}): Promise<McpConfigResult>;/** The one flag every writer of `cfg.mcpServers` takes: two writers must not interleave a read with a save. */busy: BusyFlag;@@ -225,12 +229,13 @@ export function createMcpConfig(deps: McpConfigDeps & { changed(): void }): McpCdeps.connectionsChanged?.("removed");return saved(200);}),- test: async (name, { signal, person, asBot }) => {+ test: async (name, { signal, person, asBot, lender }) => {const raw = cfg.mcpServers?.[name];if (raw === undefined) return { status: 404, error: "MCP server not found." };const parsed = parseStoredMcpServer(name, raw);if (!parsed.ok) return { status: 400, error: parsed.error };- if (parsed.server.runsOn) return { status: 409, error: runsElsewhere(parsed.server.runsOn) };+ const { runsOn } = parsed.server;+ if (runsOn) return deps.testElsewhere ? deps.testElsewhere(name, { ...parsed.server, runsOn }, lender ?? null, signal) : { status: 409, error: runsElsewhere(runsOn) };if (mcpProbesInFlight >= MAX_CONCURRENT_MCP_PROBES) {return { status: 429, error: "Two MCP connection tests are already running." };}diff --git a/server/index.ts b/server/index.tsindex 2ca4a5bad2..7f48df1278 100644--- a/server/index.ts+++ b/server/index.ts@@ -20,7 +20,7 @@ import { autoCompactWindow } from "./drivers/claude.ts";import { RoomContextTracker, roomResetNote } from "./room-context.ts";import { createRoomTranscript, GROUP_CONTEXT_MESSAGES } from "./host/room-transcript.ts";import { createRoomSessions } from "./host/room-sessions.ts";-import { LentComputers, provenRequestPerson, SharedComputers, sharedComputerOperation } from "./shared-computers.ts"; import { lentScreenResult } from "./lent-screen-guidance.ts"; import { DeviceLinks } from "./device-links.ts";+import { LentComputers, provenRequestPerson, SharedComputers, sharedComputerOperation } from "./shared-computers.ts"; import { lentScreenResult } from "./lent-screen-guidance.ts"; import { DeviceLinks } from "./device-links.ts"; import { createLentMcp, isLentMcpPath } from "./lent-mcp.ts";import { cloudHomeLendingRefusal, createCloudRoutineAuthors, ownerOnlyConversation } from "./cloud-lending.ts"; import { createOwnHome } from "./own-home.ts"; import { createPlacesElsewhere } from "./places-elsewhere.ts"; import { createPlacesElsewhereRoutes } from "./routes/places-elsewhere.ts"; import { assertRoomFolder } from "./room-folder.ts"; import { cloudConnectedAppsBrokerUrl, startCloudHomeConnectedApps, stopCloudHomeConnectedApps } from "./cloud-connected-apps.ts"; import { createTeamConnectionsHost } from "./host/team-connections-host.ts"; import { createCloudLendingTurns } from "./host/cloud-lending-turns.ts"; import { createTeamConnectionRoutes } from "./routes/team-connections.ts";import { botMemoryFiles, createLendingMemory } from "./lending-memory.ts";import { SharedComputerControl } from "./shared-computer-control.ts";@@ -1606,7 +1606,7 @@ type InternalCapability = {threadId: string;generation: string;depth: number;- kind: "agents" | "connectors" | "computer" | "browser" | "hooks" | "phone" | "data" | "highlevel" | "email" | "device";+ kind: "agents" | "connectors" | "computer" | "browser" | "hooks" | "phone" | "data" | "highlevel" | "email" | "device" | "lent";skillAuthoring: boolean;createdBots: number;createdRooms?: number;@@ -2848,7 +2848,7 @@ const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, storconst routineHolds = CLOUD_HOME ? createRoutineHoldsHost({ dataDir: DATA_DIR, store, mcpServers: () => Object.keys(cfg.mcpServers ?? {}).length, log: (line) => console.warn(line),appsConnected: async () => composio.configured(cfg) ? Object.values(await composio.connectedServices(cfg)).some((service) => service.connected) : false }) : null;const skillsHost = createSkillsLibraryHost({ store, cfg, appendSkillRequestCard, engineConfig: (instanceId) => providerConfigs()[instanceId], instanceOf: (instanceId) => { const instance = registry.get(instanceId); return instance ? { instanceId, driverKind: instance.driverKind } : undefined; } });-const { listBotSkills, readBotSkillFile } = skillsHost; const cloudConnections = createCloudConnectionsHost({ cloudHome: CLOUD_HOME, ownHome: ownHome.owner, config: () => cfg, environmentId: ENVIRONMENT_ID, mcpOAuth, highlevel, heldKeys, dataDir: DATA_DIR, email: { accounts: () => emailService.store.list(), adopt: (accounts) => emailService.adopt(accounts) }, stayedNotices: { bots: () => store.bots, language: (threadId) => threadLanguage(threadId), say: (threadId, text, kind) => { store.appendMessage(threadId, kind === "line" ? { role: "bot", kind: "text", text } : { role: "bot", kind: "activity", tool: { name: `notice: ${text}`, ok: true } }); }, notify: (text, bot, threadId) => notify(buildNoticeNotification(bot, threadId, text)) }, engines: async () => selectableInstances(await registry.describe()).filter((instance) => readyToRun(instance, selectionContext)).map((instance) => instance.instanceId) });+const { listBotSkills, readBotSkillFile } = skillsHost; const cloudConnections = createCloudConnectionsHost({ cloudHome: CLOUD_HOME, ownHome: ownHome.owner, config: () => cfg, environmentId: ENVIRONMENT_ID, mcpOAuth, highlevel, heldKeys, dataDir: DATA_DIR, email: { accounts: () => emailService.store.list(), adopt: (accounts) => emailService.adopt(accounts) }, stayedNotices: { bots: () => store.bots, language: (threadId) => threadLanguage(threadId), say: (threadId, text, kind) => { store.appendMessage(threadId, kind === "line" ? { role: "bot", kind: "text", text } : { role: "bot", kind: "activity", tool: { name: `notice: ${text}`, ok: true } }); }, notify: (text, bot, threadId) => notify(buildNoticeNotification(bot, threadId, text)), lent: (runsOn) => { const at = sharedComputers.runsOn(CLOUD_HOME_LENDER, runsOn); return Boolean(at.online ?? at.known?.lent); } }, engines: async () => selectableInstances(await registry.describe()).filter((instance) => readyToRun(instance, selectionContext)).map((instance) => instance.instanceId) }); const lentMcp = createLentMcp({ cfg: () => cfg, computers: sharedComputers, policy: (servers) => managedPolicy.filterMcp(servers), bot: (id) => store.bot(id), principal: (turn) => (CLOUD_TEAM || !lendingEnabled() ? null : sharedComputerPrincipal(turn)), notice: (turn) => (CLOUD_HOME ? cloudLendingRefusalNotice(turn) : null), refusal: (turn) => (CLOUD_HOME ? cloudLendingRefusalForBot(turn) : null), mint: (turn) => mintInternalCapability({ ...turn, kind: "lent", depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 }), active: (turn) => activeInternalGenerationByThread.get(turn.threadId) === turn.generation, origin: `http://127.0.0.1:${PORT}`, personal: CLOUD_PERSONAL, place: CLOUD_HOME ? "My Cloud" : "this server" }); // Security: a team Cloud lends nothing, so nobody's own computer serves its bots.const highlevelHost = createHighLevelHost({ service: highlevel, dataDir: DATA_DIR, bot: (id) => store.bot(id),inRoom: (threadId) => Boolean(store.groupByThread(threadId)), appendMessage: (threadId, message) => { store.appendMessage(threadId, message as Parameters<typeof store.appendMessage>[1]); } }); const emailHost = createEmailHost({ service: emailService, dataDir: DATA_DIR, bot: (id) => store.bot(id), inRoom: (threadId) => Boolean(store.groupByThread(threadId)), appendMessage: (threadId, message) => { store.appendMessage(threadId, message as Parameters<typeof store.appendMessage>[1]); }, appAllowed: () => managedPolicy.appAllowed("email"), onChange: (listener) => store.onChange(listener as never), markOutside: (threadId) => outsideLineage.mark(threadId) });const phones = createPhones({@@ -7950,7 +7950,7 @@ async function beginTurn(// User MCP servers' tools are never pre-allowed: every call rides the normal permission flow.if (instance.adapter.capabilities.customMcp === true && !proactive.fence.confines(threadId) && !botApiThread(threadId)) {const custom = await mcpServersHost.prepare(bot).then(() => teamConnections.turnMcp(bot, threadId, dispatchClaimId));- attachCustomMcp(integrations, custom, cfg, { botId: bot.id, threadId });+ attachCustomMcp(integrations, { ...custom, ...lentMcp.mounts(bot, { botId: bot.id, threadId, generation: dispatchClaimId }) }, cfg, { botId: bot.id, threadId });if (Object.keys(custom).length) Object.assign(integrations, chatAppsMcp.turnMounts(custom, bot.toolScope));}const worksInWorkspace = supportsWorkspaceFiles(instance.driverKind);@@ -8406,7 +8406,7 @@ async function beginTurn({ id: "plan", label: "Surface", text: surfacePrompt({ computer: mountedComputer, browser: Boolean(integrations.browser) }, { pinned: plan.pinned, note: plan.note + vpsUnavailableNote + vmUpdateNote + (computerSkipped && plan.computer !== "off" ? computerSkippedNote(redactSecretsInText(computerSkipped)) : ""), canSelect: computerSelectionTurns.has(threadId), cloudHome: Boolean(CLOUD_HOME), botOpened: plan.botOpened, ownComputer: CLOUD_HOME && integrations.agents && lendingEnabled() ? sharedComputers.known(CLOUD_HOME_LENDER) : undefined }) },{ id: "cloud-home", label: "My Cloud", text: CLOUD_HOME ? cloudHomePrompt(Boolean(integrations.agents) && lendingEnabled(), syncedFolders(DATA_DIR), sharedComputers.known(CLOUD_HOME_LENDER), CLOUD_PERSONAL) + firstHourHooks.prompt(bot.id, threadId) : "" },{ id: "composio", label: "Connected apps", text: integrations.composio ? composioSystemPrompt(liveBot?.connectorTools ?? bot.connectorTools) + describeConnectorScopes((liveBot ?? bot).connectorScopes) : "" },- { id: "mcp", label: "MCP servers", text: customMcpPrompt(Object.keys(integrations.custom ?? {}), mcpServersHost.off(bot)) }, { id: "to-connect", label: "Connections to make", text: cloudConnections.prompt(liveBot ?? bot) + teamConnections.prompt(threadId, dispatchClaimId, integrations) },+ { id: "mcp", label: "MCP servers", text: customMcpPrompt(Object.keys(integrations.custom ?? {}), mcpServersHost.off(bot)) }, { id: "to-connect", label: "Connections to make", text: cloudConnections.prompt(liveBot ?? bot, lentMcp.lines(liveBot ?? bot, { botId: bot.id, threadId, generation: dispatchClaimId })) + teamConnections.prompt(threadId, dispatchClaimId, integrations) },{ id: "browser", label: "Browser", text: integrations.browser ? browserPromptFor(bot, Boolean(integrations.agents)) : "" },{ id: "data", label: "Data", text: integrations.data ? BUILT_IN_DATA_SYSTEM_PROMPT : "" },{ id: "highlevel", label: "HighLevel", text: integrations.highlevel ? highlevelHost.prompt(liveBot ?? bot) : "" }, { id: "email", label: "Email", text: instance.adapter.capabilities.highlevelMcp === true ? emailHost.prompt(liveBot ?? bot) : "" },@@ -9342,7 +9342,7 @@ async function resolveAndSendTeamSetup(res: ServerResponse, args: { botId: strinconst { mcpRequests, mcpSignInCards, mcpServerDeps, resolveAndSendMcp, mcpServerResponse, mcpPolicyRefusal } = createMcpChat({ store, cfg, mcpOAuth, teamConnections, mcpServersHost, managedPolicy,secretCards: () => secretCards, mcpConfig: () => mcpConfig, teamCloud: Boolean(CLOUD_TEAM), threadLanguage, answerCardNode, followCard: (threadId, from, to) => coordinator.followCard(threadId, from, to), fullAccessForSource, cloudGuestDriven, liveTurnByThread, broadcast,- publicOrigins: () => [CLOUD_HOME?.publicOrigin, hostedWorkspaceConfiguration()?.tenant.origin, savedCustomDomain(), FALLBACK_PUBLIC_URL], threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId) });+ publicOrigins: () => [CLOUD_HOME?.publicOrigin, hostedWorkspaceConfiguration()?.tenant.origin, savedCustomDomain(), FALLBACK_PUBLIC_URL], threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), lending: () => lentMcp });const routineTimeZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";function sendRoutineResolution(res: ServerResponse,@@ -9871,7 +9871,7 @@ async function runClaimedGroupMemberTurn(return true;}if (instance.adapter.capabilities.customMcp === true) {- attachCustomMcp(integrations, await mcpServersHost.prepare(bot).then(() => teamConnections.turnMcp(bot, threadId, internalGeneration)), cfg, { botId: bot.id, threadId });+ attachCustomMcp(integrations, { ...await mcpServersHost.prepare(bot).then(() => teamConnections.turnMcp(bot, threadId, internalGeneration)), ...lentMcp.mounts(bot, { botId: bot.id, threadId, generation: internalGeneration }) }, cfg, { botId: bot.id, threadId });}// An interrupt during connected-app setup must still stop the queued room operation before it starts a process.if (isCancelled?.()) return false;@@ -12408,7 +12408,7 @@ const mcpConfig = createMcpConfig({fallbackPublicUrl: FALLBACK_PUBLIC_URL,mcpConfigBusy: { get: () => mcpConfigBusy, set: (busy) => { mcpConfigBusy = busy; } },mcpServerResponse, mcpPolicyRefusal, persistMcpServers, savedCustomDomain, appCatalog: chatAppsMcp, forgetPeople: (name) => teamConnections.forgetServer(name), health: mcpServersHost.health, botsPath: () => brokerPath(botBox),- connectionsChanged: (change) => void routineHolds?.connections(change), probeAs: mcpServersHost.probeAs,+ connectionsChanged: (change) => void routineHolds?.connections(change), probeAs: mcpServersHost.probeAs, testElsewhere: (name, server, lender, signal) => lentMcp.test(name, server, lender, signal),changed: () => broadcast({ kind: "mcp.changed" }) });const persistAnnouncedMcpServers = (next: Record<string, unknown>) => { persistMcpServers(next); broadcast({ kind: "mcp.changed" }); };const postiz = createPostiz({ cfg: () => cfg, mcpOAuth, persistMcpServers: persistAnnouncedMcpServers, mcpConfigBusy: mcpConfig.busy, mcpPolicyRefusal, appCatalog: chatAppsMcp, team: teamConnections, loopback: !CLOUD_HOME && !HOSTED_WORKSPACE }); ROUTES.push(createPostizRoutes({ postiz }), createConfigRoutes({@@ -12437,7 +12437,7 @@ ROUTES.push(createMcpServerRoutes({cfg, bot: (id) => store.bot(id), sessions, mcpOAuth, teamConnections,cloudHome: CLOUD_HOME,fallbackPublicUrl: FALLBACK_PUBLIC_URL,- mcpServerResponse, savedCustomDomain, appCatalog: chatAppsMcp, config: mcpConfig }));+ mcpServerResponse, savedCustomDomain, appCatalog: chatAppsMcp, config: mcpConfig, lender: sessionLendingPrincipal, place: (server, auth) => lentMcp.place(server, { principal: sessionLendingPrincipal(auth), ...(auth.kind === "session" ? { session: auth.session.id } : {}), newest: true }) }));ROUTES.push(createSetupImportRoutes({ local: DESKTOP_MANAGED && !CLOUD_HOME && !HOSTED_WORKSPACE, cfg, mcpPolicyRefusal, persistMcpServers: persistAnnouncedMcpServers,mcpConfigBusy: mcpConfig.busy }));ROUTES.push(createComputerRoutes({@@ -12977,7 +12977,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {: path === HIGHLEVEL_INTERNAL_MCP_PATH? "highlevel" : path === EMAIL_INTERNAL_MCP_PATH ? "email": path === PHONE_INTERNAL_MCP_PATH- ? "device"+ ? "device" : isLentMcpPath(path) ? "lent": path === "/api/internal/phone/claim"? "phone": path.startsWith("/api/internal/connectors/")@@ -13025,7 +13025,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {throw Object.assign(new Error("the internal turn capability has expired"), { status: 401 });}};- const botFolders = async () => ({ roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), vmWorkspace: (await attachmentVmForTurn(internalCapability))?.workspaceDir ?? null }); if (await internalToolRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, folders: botFolders }) !== PASS || await waitRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, ...waitTurnChecks(internalCapability, internalSender) }) !== PASS || await teamMessages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await devsReports.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || (computerAsks && await computerAsks.internal({ method, path, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS) || await imageTools.internal({ method, path, res, json, readBody: readInternalBody, threadId: internalCapability.threadId, requireActive: requireActiveInternalCapability, personTurn: turnOrigin(internalCapability).kind === "user" || (Boolean(roomRun(internalCapability.generation)?.requestMessageId) && guestDrivenTurns.get(internalCapability.threadId) !== internalCapability.generation) }) !== PASS) return; const pagesCall = new AbortController(); res.once("close", () => { if (!res.writableEnded) pagesCall.abort(); }); if (await publishedPages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, requireActive: requireActiveInternalCapability, signal: pagesCall.signal, folders: botFolders, post: (text, publishedPage, bundle) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return !source ? null : (!source.group && bundle && publishedPages.show({ threadId: internalCapability.threadId, card: publishedPage, bundle })) || store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, publishedPage, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id; } }) !== PASS) return;+ const botFolders = async () => ({ roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), vmWorkspace: (await attachmentVmForTurn(internalCapability))?.workspaceDir ?? null }); if (await lentMcp.route({ method, path, req, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS || await internalToolRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, folders: botFolders }) !== PASS || await waitRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, ...waitTurnChecks(internalCapability, internalSender) }) !== PASS || await teamMessages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await devsReports.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || (computerAsks && await computerAsks.internal({ method, path, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS) || await imageTools.internal({ method, path, res, json, readBody: readInternalBody, threadId: internalCapability.threadId, requireActive: requireActiveInternalCapability, personTurn: turnOrigin(internalCapability).kind === "user" || (Boolean(roomRun(internalCapability.generation)?.requestMessageId) && guestDrivenTurns.get(internalCapability.threadId) !== internalCapability.generation) }) !== PASS) return; const pagesCall = new AbortController(); res.once("close", () => { if (!res.writableEnded) pagesCall.abort(); }); if (await publishedPages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, requireActive: requireActiveInternalCapability, signal: pagesCall.signal, folders: botFolders, post: (text, publishedPage, bundle) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return !source ? null : (!source.group && bundle && publishedPages.show({ threadId: internalCapability.threadId, card: publishedPage, bundle })) || store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, publishedPage, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id; } }) !== PASS) return;const delegatedThisTurn = (taskId: string) => {(internalCapability.delegatedThisTurn ??= new Set()).add(taskId);};diff --git a/server/lent-computers.ts b/server/lent-computers.tsindex 34a7c48f43..ba2478c639 100644--- a/server/lent-computers.ts+++ b/server/lent-computers.ts@@ -12,6 +12,7 @@ export type LentPlatform = typeof LENT_PLATFORMS[number];const recordSchema = z.object({id: z.string().uuid(), person: z.string().min(1).max(200), name: z.string().min(1).max(120), platform: z.enum(LENT_PLATFORMS).nullable(),folders: z.number().int().min(0).max(20), terminal: z.boolean(), screen: z.boolean(), internet: z.boolean().optional(), chrome: z.boolean().optional(),+ environments: z.array(z.string().uuid()).max(8).optional(),lastSeenAt: z.number(), lastUsedAt: z.number().nullable(), stoppedAt: z.number().nullable(),}).strict();const fileSchema = z.object({ version: z.literal(1), computers: z.array(recordSchema).max(200) });@@ -66,12 +67,14 @@ export class LentComputers {/** A computer that registered, now lending these scopes. Each new grant has a new id, so a computer is known by its* name: lending again from the same computer updates its one record. A person's newest computers are kept. */- connected(person: string, input: { id: string; name: string; platform?: LentPlatform; folders: number; terminal: boolean; screen: boolean; internet?: boolean; chrome?: boolean }): void {+ connected(person: string, input: { id: string; name: string; platform?: LentPlatform; folders: number; terminal: boolean; screen: boolean; internet?: boolean; chrome?: boolean; environments?: string[] }): void {const at = this.now();const same = (computer: LentComputer) => computer.person === person && (computer.id === input.id || computer.name === input.name);const previous = this.computers.find(same);const next: LentComputer = { id: input.id, person, name: input.name, platform: input.platform ?? previous?.platform ?? null, folders: input.folders,- terminal: input.terminal, screen: input.screen, internet: input.internet === true, chrome: input.chrome === true, lastSeenAt: at, lastUsedAt: previous?.lastUsedAt ?? null, stoppedAt: null };+ terminal: input.terminal, screen: input.screen, internet: input.internet === true, chrome: input.chrome === true,+ ...(input.environments?.length ? { environments: input.environments } : previous?.environments ? { environments: previous.environments } : {}),+ lastSeenAt: at, lastUsedAt: previous?.lastUsedAt ?? null, stoppedAt: null };const others = this.computers.filter((computer) => !same(computer));const mine = [next, ...others.filter((computer) => computer.person === person)].slice(0, PER_PERSON);this.computers = [...mine, ...others.filter((computer) => computer.person !== person)];diff --git a/server/lent-mcp.test.ts b/server/lent-mcp.test.tsnew file mode 100644index 0000000000..a56c80467d--- /dev/null+++ b/server/lent-mcp.test.ts@@ -0,0 +1,212 @@+import { EventEmitter } from "node:events";+import type { IncomingMessage, ServerResponse } from "node:http";+import { describe, expect, it, vi } from "vitest";++import { createLentMcp, isLoopbackUrl, LENT_MCP_PATH, lentLine, needsTheirComputer, type HereChecks, type LentMcpDeps } from "./lent-mcp.ts";+import { PASS } from "./routes/table.ts";+import type { SharedComputers } from "./shared-computers.ts";++const MAC = { environmentId: "11111111-1111-4111-8111-111111111111", label: "Ada's Mac" };+const TURN = { botId: "kiwi", threadId: "t-1", generation: "g-1" };+const local = { type: "http" as const, url: "http://127.0.0.1:19501/mcp", headers: { Authorization: "Bearer saved-header" }, enabled: true, runsOn: MAC };+const notes = { command: "/Users/ada/bin/notes-mcp", args: [], env: { NOTES_TOKEN: "saved-env" }, enabled: true, runsOn: MAC };+const here = (over: Partial<HereChecks> = {}): HereChecks => ({ exists: () => false, program: () => true, answers: async () => false, ...over });++type Online = NonNullable<ReturnType<SharedComputers["runsOn"]>["online"]>;+function fixture(options: { online?: Partial<Online> | null; known?: { lent: boolean } | null; principal?: string | null; servers?: Record<string, unknown>; mcpServers?: string[]; toolScope?: unknown; answer?: (operation: Record<string, unknown>) => unknown; lenders?: ReturnType<SharedComputers["mcpLenders"]>; here?: HereChecks } = {}) {+ const requests: Array<{ operation: Record<string, unknown>; principal: string | null }> = [];+ const online = options.online === null ? null : { id: "mac-1", name: "Ada's Mac", platform: "darwin" as const, terminal: false, mcpServers: true, ...options.online };+ const computers: LentMcpDeps["computers"] = {+ runsOn: (principal) => (principal === "cloud-home" ? { online, known: options.known === null ? null : { name: "Ada's Mac", platform: "darwin", lent: options.known?.lent ?? true } } : { online: null, known: null }),+ mcpLenders: (principal) => (principal === "cloud-home" ? options.lenders ?? [] : []),+ request: async (operation, principal) => {+ requests.push({ operation: operation as Record<string, unknown>, principal });+ const answer = options.answer?.(operation as Record<string, unknown>);+ if (answer instanceof Error) throw answer;+ return answer ?? (operation.action === "mcp_tools" ? { tools: [{ name: "search", description: "Find notes", inputSchema: { type: "object" } }] } : { content: [{ type: "text", text: "found it" }] });+ },+ };+ const minted: string[] = [];+ const lent = createLentMcp({+ cfg: () => ({ mcpServers: options.servers ?? { local, notes } }),+ computers,+ policy: (servers) => servers,+ bot: (id) => (id === "kiwi" ? { id, ...(options.mcpServers ? { mcpServers: options.mcpServers } : {}), toolScope: options.toolScope } : undefined),+ principal: () => (options.principal === undefined ? "cloud-home" : options.principal),+ notice: () => "Someone else wrote in this conversation, so it can't use your Mac. Start a new conversation to use it.",+ refusal: () => "Someone else wrote in this conversation, so it can't use your Mac. Start a new conversation to use it. Only the person can change this.",+ mint: () => { minted.push("token"); return "turn-bearer"; },+ active: () => true,+ origin: "http://127.0.0.1:4242",+ personal: true,+ place: "My Cloud",+ here: options.here ?? here(),+ });+ return { lent, requests, minted };+}++const rpc = (method: string, params: unknown = {}, id = 1) => ({ jsonrpc: "2.0", id, method, params });++async function route(lent: ReturnType<typeof createLentMcp>, path: string, body: unknown, method = "POST") {+ const json = vi.fn();+ const res = Object.assign(new EventEmitter(), { writeHead: vi.fn(function (this: unknown) { return this; }), end: vi.fn() }) as unknown as ServerResponse & { writeHead: ReturnType<typeof vi.fn> };+ const out = await lent.route({ method, path, req: {} as IncomingMessage, res, turn: TURN, readBody: async () => body, json });+ return { out, json, res };+}++describe("which new servers need the person's own computer", () => {+ it("a loopback address nothing here answers, never one this server answers or an address on the internet", async () => {+ for (const url of ["http://127.0.0.1:19501/mcp", "http://localhost:3000/mcp", "http://[::1]:8080/mcp", "https://127.0.0.2/mcp"]) expect(isLoopbackUrl(url), url).toBe(true);+ for (const url of ["https://mcp.linear.app/mcp", "http://192.168.1.4/mcp", "http://127.0.0.1.example.com/mcp", "ftp://127.0.0.1/x", "not a url"]) expect(isLoopbackUrl(url), url).toBe(false);+ const server = { type: "http" as const, url: "http://127.0.0.1:19501/mcp", headers: {}, enabled: true };+ expect(await needsTheirComputer(server, here())).toBe(true);+ expect(await needsTheirComputer(server, here({ answers: async () => true })), "a service on this server is this server's").toBe(false);+ expect(await needsTheirComputer({ ...server, url: "https://mcp.linear.app/mcp" }, here())).toBe(false);+ });++ it("a command that is a path here lacks, a program here lacks, or one that reads a path in their home folder", async () => {+ const stdio = (command: string, args: string[] = [], env: Record<string, string> = {}) => ({ command, args, env, enabled: true });+ expect(await needsTheirComputer(stdio("/Users/ada/bin/notes-mcp"), here())).toBe(true);+ expect(await needsTheirComputer(stdio("/usr/bin/node", ["server.js"]), here({ exists: (path) => path === "/usr/bin/node" }))).toBe(false);+ expect(await needsTheirComputer(stdio("obsidian-mcp"), here({ program: () => false }))).toBe(true);+ expect(await needsTheirComputer(stdio("npx", ["-y", "notes-mcp"]), here())).toBe(false);+ expect(await needsTheirComputer(stdio("node", ["/Users/ada/notes/server.js"]), here())).toBe(true);+ expect(await needsTheirComputer(stdio("npx", ["-y", "fs-mcp", "--root=C:\\Users\\Ada\\Notes"]), here())).toBe(true);+ expect(await needsTheirComputer(stdio("npx", ["-y", "fs-mcp"], { NOTES_DIR: "/home/ada/notes" }), here())).toBe(true);+ expect(await needsTheirComputer(stdio("node", ["/data/server.js"]), here()), "a path outside a home folder may be this server's own").toBe(false);+ });+});++describe("a server that runs on the person's computer, in a turn", () => {+ it("mounts each one the turn's lent computer can run as a server at this server's address, with no saved key in it", () => {+ const { lent, minted } = fixture({ online: { terminal: true } });+ const mounted = lent.mounts({ id: "kiwi" }, TURN);+ expect(mounted).toEqual({+ local: { type: "http", url: `http://127.0.0.1:4242${LENT_MCP_PATH}local`, headers: { authorization: "Bearer turn-bearer" } },+ notes: { type: "http", url: `http://127.0.0.1:4242${LENT_MCP_PATH}notes`, headers: { authorization: "Bearer turn-bearer" } },+ });+ expect(JSON.stringify(mounted)).not.toMatch(/saved-header|saved-env|notes-mcp/);+ expect(minted).toHaveLength(1);+ });++ it("leaves out what can't be reached now and says why in plain words: offline, no longer lent, never lent, too old, no terminal", () => {+ const say = (options: Parameters<typeof fixture>[0]) => {+ const { lent } = fixture(options);+ return [Object.keys(lent.mounts({ id: "kiwi" }, TURN)), Object.fromEntries(lent.lines({ id: "kiwi" }, TURN))];+ };+ expect(say({ online: null })).toEqual([[], {+ local: "local runs on your Mac (Ada's Mac), which is offline right now: OpenMausBot on it is closed, or the Mac is asleep or off.",+ notes: "notes runs on your Mac (Ada's Mac), which is offline right now: OpenMausBot on it is closed, or the Mac is asleep or off.",+ }]);+ expect(say({ online: null, known: { lent: false } })[1]).toMatchObject({ local: "local runs on your Mac (Ada's Mac), which no longer lends itself to My Cloud: OpenMausBot on it is paused or signed out." });+ expect(say({ online: null, known: null })[1]).toMatchObject({ local: "local runs on Ada's Mac, which isn't lent to My Cloud: it works once OpenMausBot is open on that computer and signed in to My Cloud." });+ expect(say({ online: { mcpServers: false } })[1]).toMatchObject({ local: "local runs on your Mac (Ada's Mac), whose OpenMausBot is too old to run it for My Cloud: update OpenMausBot on that Mac." });+ expect(say({})).toEqual([["local"], { notes: "notes starts a program on your Mac (Ada's Mac), which doesn't let My Cloud run programs right now: turn on \"Let Clouds run commands on this Mac\" from the OpenMausBot icon on that Mac." }]);+ });++ it("mounts nothing for a turn that can't use the lent computer, and says why", () => {+ const { lent, minted } = fixture({ principal: null });+ expect(lent.mounts({ id: "kiwi" }, TURN)).toEqual({});+ expect(minted).toEqual([]);+ expect(lent.lines({ id: "kiwi" }, TURN).get("local")).toBe("local runs on Ada's Mac. Someone else wrote in this conversation, so it can't use your Mac. Start a new conversation to use it.");+ });++ it("only the bot's own servers: off, another bot's, left out of its list or its tool selection are never mounted", () => {+ const servers = { local, off: { ...local, enabled: false }, theirs: { ...notes, bot: "other" }, here: { ...local, runsOn: undefined }, unlisted: local, unselected: local };+ const bot = { id: "kiwi", mcpServers: ["local", "off", "theirs", "here", "unselected"], toolScope: { deny: ["mcp:unselected:*"] } };+ const { lent } = fixture({ servers, online: { terminal: true } });+ expect(Object.keys(lent.mounts(bot, TURN))).toEqual(["local"]);+ });+});++describe("the MCP endpoint a turn's engine reaches", () => {+ it("answers initialize and ping itself, and lists and calls tools on the lent computer with the server as saved", async () => {+ const { lent, requests } = fixture();+ expect((await route(lent, `${LENT_MCP_PATH}local`, rpc("initialize", { protocolVersion: "2025-06-18" }))).json).toHaveBeenCalledWith(expect.anything(), 200, { jsonrpc: "2.0", id: 1, result: { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "openmausbot-local", version: "1" } } });+ expect(requests).toEqual([]);+ const notification = await route(lent, `${LENT_MCP_PATH}local`, { jsonrpc: "2.0", method: "notifications/initialized" });+ expect(notification.res.writeHead).toHaveBeenCalledWith(202);+ const listed = await route(lent, `${LENT_MCP_PATH}local`, rpc("tools/list"));+ expect(listed.json).toHaveBeenCalledWith(expect.anything(), 200, { jsonrpc: "2.0", id: 1, result: { tools: [{ name: "search", description: "Find notes", inputSchema: { type: "object" } }] } });+ const called = await route(lent, `${LENT_MCP_PATH}local`, rpc("tools/call", { name: "search", arguments: { q: "plan" } }, 2));+ expect(called.json).toHaveBeenCalledWith(expect.anything(), 200, { jsonrpc: "2.0", id: 2, result: { content: [{ type: "text", text: "found it" }] } });+ expect(requests).toEqual([+ { principal: "cloud-home", operation: { computer_id: "mac-1", action: "mcp_tools", server: { name: "local", url: "http://127.0.0.1:19501/mcp", type: "http", headers: { Authorization: "Bearer saved-header" } } } },+ { principal: "cloud-home", operation: { computer_id: "mac-1", action: "mcp_call", server: { name: "local", url: "http://127.0.0.1:19501/mcp", type: "http", headers: { Authorization: "Bearer saved-header" } }, tool_name: "search", arguments: { q: "plan" } } },+ ]);+ expect((await route(lent, `${LENT_MCP_PATH}local`, rpc("tools/list"))).json, "listed again within ten minutes: kept").toHaveBeenCalled();+ expect(requests.filter((request) => request.operation.action === "mcp_tools")).toHaveLength(1);+ });++ it("refuses a server that isn't this bot's now, a turn that can't use the computer, and an offline computer, with no job sent", async () => {+ const quiet = fixture();+ const unknown = await route(quiet.lent, `${LENT_MCP_PATH}evil`, rpc("tools/call", { name: "x" }));+ expect(unknown.json.mock.calls[0]![2]).toEqual({ jsonrpc: "2.0", id: 1, result: { content: [{ type: "text", text: "evil isn't one of your MCP servers on another computer now." }], isError: true } });+ for (const name of ["__proto__", "constructor", "local/../notes"]) {+ expect((await route(quiet.lent, `${LENT_MCP_PATH}${name}`, rpc("tools/list"))).json.mock.calls[0]![2].error.message).toContain("isn't one of your MCP servers");+ }+ const refused = fixture({ principal: null });+ const call = await route(refused.lent, `${LENT_MCP_PATH}local`, rpc("tools/call", { name: "search" }));+ expect(call.json.mock.calls[0]![2].result.content[0].text).toContain("Only the person can change this.");+ const list = await route(refused.lent, `${LENT_MCP_PATH}local`, rpc("tools/list"));+ expect(list.json.mock.calls[0]![2].error.message, "listing raises no card").not.toContain("Only the person");+ const away = fixture({ online: null });+ const offline = await route(away.lent, `${LENT_MCP_PATH}local`, rpc("tools/call", { name: "search" }));+ expect(offline.json.mock.calls[0]![2].result).toEqual({ content: [{ type: "text", text: "local runs on your Mac (Ada's Mac), which is offline right now: OpenMausBot on it is closed, or the Mac is asleep or off." }], isError: true });+ expect([...quiet.requests, ...refused.requests, ...away.requests]).toEqual([]);+ });++ it("passes on the computer's refusal and a failed listing, takes POST only and leaves other paths alone", async () => {+ const { lent } = fixture({ answer: (operation) => (operation.action === "mcp_tools" ? { content: [{ type: "text", text: "local is not answering at 127.0.0.1:19501 on this computer" }], isError: true } : new Error("Ada's Mac is busy")) });+ const listed = await route(lent, `${LENT_MCP_PATH}local`, rpc("tools/list"));+ expect(listed.json.mock.calls[0]![2]).toEqual({ jsonrpc: "2.0", id: 1, error: { code: -32603, message: "local is not answering at 127.0.0.1:19501 on this computer" } });+ const called = await route(lent, `${LENT_MCP_PATH}local`, rpc("tools/call", { name: "search" }));+ expect(called.json.mock.calls[0]![2].result).toEqual({ content: [{ type: "text", text: "Ada's Mac is busy" }], isError: true });+ expect((await route(lent, `${LENT_MCP_PATH}local`, null, "GET")).res.writeHead).toHaveBeenCalledWith(405, { allow: "POST" });+ expect((await route(lent, "/api/internal/shared-computers", {})).out).toBe(PASS);+ expect((await route(lent, `${LENT_MCP_PATH}local`, rpc("resources/list"))).json.mock.calls[0]![2].error.code).toBe(-32601);+ });+});++describe("Test, and adding a server that needs the person's computer", () => {+ it("Test lists the tools on the computer it runs on, or says plainly why it can't, never 'could not reach'", async () => {+ const signal = new AbortController().signal;+ expect(await fixture().lent.test("local", local, "cloud-home", signal)).toEqual({ status: 200, body: { ok: true, tools: [{ name: "search", description: "Find notes" }] } });+ const offline = await fixture({ online: null }).lent.test("local", local, "cloud-home", signal);+ expect(offline).toEqual({ status: 409, error: "local runs on your Mac (Ada's Mac), which is offline right now: OpenMausBot on it is closed, or the Mac is asleep or off." });+ expect(await fixture().lent.test("notes", notes, "cloud-home", signal)).toMatchObject({ status: 409, error: expect.stringContaining("doesn't let My Cloud run programs") });+ expect(await fixture().lent.test("local", local, null, signal)).toEqual({ status: 409, error: "local runs on Ada's Mac, so it is checked there the next time one of your conversations uses it." });+ const failing = fixture({ answer: () => ({ content: [{ type: "text", text: "local is not answering at 127.0.0.1:19501 on this computer" }], isError: true }) });+ expect(await failing.lent.test("local", local, "cloud-home", signal)).toEqual({ status: 200, body: { ok: false, reason: "unreachable", error: "local is not answering at 127.0.0.1:19501 on this computer" } });+ });++ const lender = (name: string, session: string, environmentId: string, seen: number) => ({ id: `${name}-id`, name, platform: "darwin" as const, session, environmentId, seen });+ const address = { type: "http" as const, url: "http://127.0.0.1:19501/mcp", headers: {}, enabled: true };++ it("marks a new loopback or local server as running on the one lent computer, and nothing else", async () => {+ const one = fixture({ lenders: [lender("Ada's Mac", "s-mac", MAC.environmentId, 2)] });+ expect(await one.lent.place(address, { principal: "cloud-home" })).toEqual({ ok: true, server: { ...address, runsOn: MAC } });+ const internet = { ...address, url: "https://mcp.linear.app/mcp" };+ expect(await one.lent.place(internet, { principal: "cloud-home" })).toEqual({ ok: true, server: internet });+ expect(await one.lent.place(address, { principal: null }), "a team Cloud, or a turn that can't use the computer").toEqual({ ok: true, server: address });+ const kept = { ...address, runsOn: { environmentId: "22222222-2222-4222-8222-222222222222", label: "Studio" } };+ expect(await one.lent.place(kept, { principal: "cloud-home" })).toEqual({ ok: true, server: kept });+ expect(await fixture().lent.place(address, { principal: "cloud-home" }), "nothing lent now: it stays as added").toEqual({ ok: true, server: address });+ });++ it("with several lent: the one named, else the one the adder is on, else the newest for the person, else the bot asks", async () => {+ const studio = "33333333-3333-4333-8333-333333333333";+ const { lent } = fixture({ lenders: [lender("Studio", "s-studio", studio, 3), lender("Ada's Mac", "s-mac", MAC.environmentId, 2)] });+ expect(await lent.place(address, { principal: "cloud-home", computer: "ada's mac" })).toMatchObject({ server: { runsOn: MAC } });+ expect(await lent.place(address, { principal: "cloud-home", computer: "Laptop" })).toEqual({ ok: false, error: "No computer called Laptop is lent to My Cloud now. These are: Studio, Ada's Mac." });+ expect(await lent.place(address, { principal: "cloud-home", session: "s-mac" })).toMatchObject({ server: { runsOn: MAC } });+ expect(await lent.place(address, { principal: "cloud-home", session: "s-phone", newest: true })).toMatchObject({ server: { runsOn: { environmentId: studio, label: "Studio" } } });+ expect(await lent.place(address, { principal: "cloud-home" })).toEqual({ ok: false, error: "This server runs on the person's own computer, and several are lent to My Cloud: Studio, Ada's Mac. Ask the person which one in one short question, then add it again with computer set to its name." });+ });+});++it("the words for each case", () => {+ const words = { personal: false, place: "this server" };+ expect(lentLine("notes", { kind: "offline", computer: "MILIND-PC", device: "PC" }, words)).toBe("notes runs on MILIND-PC, which is offline right now: OpenMausBot on it is closed, or the PC is asleep or off.");+ expect(lentLine("notes", { kind: "offline", computer: "MILIND-PC", device: "PC" }, { ...words, personal: true })).toBe("notes runs on your PC (MILIND-PC), which is offline right now: OpenMausBot on it is closed, or the PC is asleep or off.");+});diff --git a/server/lent-mcp.ts b/server/lent-mcp.tsnew file mode 100644index 0000000000..c2385b42ea--- /dev/null+++ b/server/lent-mcp.ts@@ -0,0 +1,296 @@+// MCP servers saved here that run on a computer lent to this server (`runsOn`). A bot's turn reaches each one as an MCP+// server at this server's own address, and every call goes to that computer as a lending job: nothing here starts its+// command or fetches its address. Security: the computer gets the server exactly as it is saved here, keys included,+// and runs it only as its own lending allows; the keys never reach the bot.+import { createHash } from "node:crypto";+import { existsSync } from "node:fs";+import type { IncomingMessage, ServerResponse } from "node:http";+import { connect } from "node:net";+import { homedir } from "node:os";+import { delimiter, join } from "node:path";++import { canUseMcpServer } from "../shared/tool-scope.ts";+import type { AppConfig } from "./config.ts";+import type { McpServerSpec } from "./contracts.ts";+import { augmentedPath } from "./env-path.ts";+import { deviceWord, type LentPlatform } from "./lent-computers.ts";+import type { McpProbeResult } from "./mcp-probe.ts";+import { isRemoteMcpServer, mcpServerServes, parseStoredMcpServer, type McpRunsOn, type StoredMcpServer } from "./mcp-registry.ts";+import { PASS } from "./routes/table.ts";+import type { LentMcpServer, SharedComputers } from "./shared-computers.ts";++export const LENT_MCP_PATH = "/api/internal/lent/mcp/";+export const isLentMcpPath = (path: string): boolean => path.startsWith(LENT_MCP_PATH);++const LOOPBACK = /^(?:localhost|127(?:\.\d{1,3}){3}|::1)$/iu;+/** A path on the person's own computer: their home folder (macOS, Linux, `~`) or a Windows drive. */+const PERSONAL_PATH = /^(?:~[\\/]|\/Users\/|\/home\/|[A-Za-z]:[\\/])/u;+const LISTING_MS = 10 * 60_000;+const MAX_TOOLS = 100;+const PROTOCOLS = ["2024-11-05", "2025-03-26", "2025-06-18"];++export function isLoopbackUrl(url: string): boolean {+ try {+ const { protocol, hostname } = new URL(url);+ return (protocol === "http:" || protocol === "https:") && LOOPBACK.test(hostname.replace(/^\[|\]$/gu, ""));+ } catch { return false; }+}++export interface HereChecks {+ exists(path: string): boolean;+ /** A program by its bare name is on this server's PATH. */+ program(command: string): boolean;+ /** Something on this server answers at this loopback address. */+ answers(url: string): Promise<boolean>;+}++const expand = (path: string) => (path.startsWith("~") ? join(homedir(), path.slice(2)) : path);+const pathLike = (command: string) => /[\\/]/u.test(command) || command.startsWith("~") || command.startsWith(".");++/** A server added here that only the person's own computer can run: a loopback address nothing here answers, or a command+ * that this server lacks, or that is or reads a path in their home folder this server does not have. */+export async function needsTheirComputer(server: StoredMcpServer, here: HereChecks): Promise<boolean> {+ if (isRemoteMcpServer(server)) return isLoopbackUrl(server.url) && !(await here.answers(server.url));+ const command = server.command.trim();+ if (pathLike(command)) return !here.exists(expand(command));+ if (!here.program(command)) return true;+ return [...server.args, ...Object.values(server.env)].some((value) => [value, ...value.split("=").slice(1)]+ .some((piece) => PERSONAL_PATH.test(piece) && !here.exists(expand(piece))));+}++export function answersHere(url: string): Promise<boolean> {+ const { hostname, port, protocol } = new URL(url);+ return new Promise((resolve) => {+ const socket = connect({ host: hostname.replace(/^\[|\]$/gu, ""), port: Number(port) || (protocol === "https:" ? 443 : 80) });+ const done = (answered: boolean) => { socket.destroy(); resolve(answered); };+ socket.setTimeout(500, () => done(false));+ socket.once("connect", () => done(true));+ socket.once("error", () => done(false));+ });+}++export function lentDefinition(name: string, server: StoredMcpServer): LentMcpServer {+ return isRemoteMcpServer(server)+ ? { name, url: server.url, type: server.type, headers: { ...server.headers } }+ : { name, command: server.command, args: [...server.args], env: { ...server.env } };+}++const definitionKey = (definition: LentMcpServer) => createHash("sha256").update(JSON.stringify(definition)).digest("hex");++type ElsewhereServer = StoredMcpServer & { runsOn: McpRunsOn };+type Bot = { id: string; mcpServers?: string[]; toolScope?: unknown };++/** The saved servers that run on another computer and that this bot's turns use: on, for this bot, in its list and its+ * tool selection. */+export function elsewhereServers(cfg: Pick<AppConfig, "mcpServers">, bot: Bot): Array<[string, ElsewhereServer]> {+ return Object.entries(cfg.mcpServers ?? {}).flatMap(([name, raw]): Array<[string, ElsewhereServer]> => {+ if (bot.mcpServers && !bot.mcpServers.includes(name)) return [];+ const parsed = parseStoredMcpServer(name, raw);+ if (!parsed.ok || !parsed.server.enabled || !parsed.server.runsOn || !mcpServerServes(parsed.server, bot.id) || !canUseMcpServer(bot.toolScope, name)) return [];+ return [[name, parsed.server as ElsewhereServer]];+ });+}++export type LentState =+ | { kind: "ready"; computerId: string }+ | { kind: "offline" | "stopped" | "never" | "outdated" | "no-terminal"; computer: string; device: "Mac" | "PC" | "computer" };++export function lentState(computers: Pick<SharedComputers, "runsOn">, principal: string | null, server: ElsewhereServer): LentState {+ const { online, known } = computers.runsOn(principal, server.runsOn);+ const at = (platform: LentPlatform | null | undefined, name: string) => ({ computer: name, device: deviceWord(platform) });+ if (online) {+ if (!online.mcpServers) return { kind: "outdated", ...at(online.platform, online.name) };+ if (!isRemoteMcpServer(server) && !online.terminal) return { kind: "no-terminal", ...at(online.platform, online.name) };+ return { kind: "ready", computerId: online.id };+ }+ if (known) return { kind: known.lent ? "offline" : "stopped", ...at(known.platform, known.name) };+ return { kind: "never", computer: server.runsOn.label, device: "computer" };+}++/** `personal`: one person's place, whose computers are "your Mac"; `place`: this server, as the person knows it. */+export function lentLine(name: string, state: Exclude<LentState, { kind: "ready" }>, { personal, place }: { personal: boolean; place: string }): string {+ const { computer, device } = state;+ const theirs = personal && device !== "computer" ? `your ${device} (${computer})` : computer;+ switch (state.kind) {+ case "offline": return `${name} runs on ${theirs}, which is offline right now: OpenMausBot on it is closed, or the ${device} is asleep or off.`;+ case "stopped": return `${name} runs on ${theirs}, which no longer lends itself to ${place}: OpenMausBot on it is paused or signed out.`;+ case "never": return `${name} runs on ${theirs}, which isn't lent to ${place}: it works once OpenMausBot is open on that computer and signed in to ${place}.`;+ case "outdated": return `${name} runs on ${theirs}, whose OpenMausBot is too old to run it for ${place}: update OpenMausBot on that ${device}.`;+ case "no-terminal": return `${name} starts a program on ${theirs}, which doesn't let ${place} run programs right now: turn on "Let Clouds run commands on this ${device}" from the OpenMausBot icon on that ${device}.`;+ }+}++type Turn = { botId: string; threadId: string; generation: string };+type Rpc = { jsonrpc?: unknown; id?: string | number | null; method?: unknown; params?: unknown };++export interface LentMcpDeps {+ cfg(): Pick<AppConfig, "mcpServers">;+ computers: Pick<SharedComputers, "runsOn" | "mcpLenders" | "request">;+ /** The managed policy over a bot's servers. */+ policy<T extends object>(servers: Record<string, T>): Record<string, T>;+ bot(id: string): Bot | null | undefined;+ /** Whom this turn may use lent computers for; null: nobody. */+ principal(turn: Turn): string | null;+ /** Why this turn can't use a lent computer, in words for the bot; null when nothing says so. */+ notice(turn: Turn): string | null;+ /** The same, for a call the bot made: where the person can allow it on a card, the card goes up too. */+ refusal(turn: Turn): string | null;+ /** This turn's bearer for LENT_MCP_PATH, minted only while it runs. */+ mint(turn: Turn): string;+ active(turn: Turn): boolean;+ /** This server's own loopback address, `http://127.0.0.1:<port>`. */+ origin: string;+ personal: boolean;+ place: string;+ here?: HereChecks;+}++const reply = (id: Rpc["id"], result: unknown) => ({ jsonrpc: "2.0", id: id ?? null, result });+const rpcError = (id: Rpc["id"], message: string, code = -32603) => ({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });+const callError = (id: Rpc["id"], text: string) => reply(id, { content: [{ type: "text", text }], isError: true });+const failed = (result: unknown): string | null => {+ const answer = result as { isError?: unknown; content?: Array<{ text?: unknown }> } | null;+ return answer?.isError === true ? String(answer.content?.[0]?.text ?? "The MCP server failed.") : null;+};++export function createLentMcp(deps: LentMcpDeps) {+ const here: HereChecks = deps.here ?? { exists: existsSync, program: (command) => Boolean(whichHere(command)), answers: answersHere };+ const listings = new Map<string, { at: number; tools: Promise<unknown[]> }>();+ const words = { personal: deps.personal, place: deps.place };++ const servers = (bot: Bot) => deps.policy(Object.fromEntries(elsewhereServers(deps.cfg(), bot)));++ /** The tools a computer lists for a server, kept ten minutes, since every turn's engine asks again as it starts. */+ function tools(computerId: string, definition: LentMcpServer, principal: string, active: () => boolean, fresh = false): Promise<unknown[]> {+ const key = `${computerId}\n${definitionKey(definition)}`;+ const known = listings.get(key);+ if (!fresh && known && Date.now() - known.at < LISTING_MS) return known.tools;+ const listed = deps.computers.request({ computer_id: computerId, action: "mcp_tools", server: definition }, principal, active).then((result) => {+ const error = failed(result);+ if (error) throw new Error(error);+ const list = (result as { tools?: unknown })?.tools;+ if (!Array.isArray(list)) throw new Error(`${definition.name} listed no tools.`);+ return list;+ });+ listings.set(key, { at: Date.now(), tools: listed });+ listed.catch(() => { if (listings.get(key)?.tools === listed) listings.delete(key); });+ return listed;+ }++ async function rpc(name: string, frame: unknown, turn: Turn): Promise<unknown | undefined> {+ if (!frame || typeof frame !== "object" || Array.isArray(frame)) return rpcError(null, "Invalid request.", -32600);+ const message = frame as Rpc;+ if (message.jsonrpc !== "2.0" || typeof message.method !== "string") return rpcError(null, "Invalid request.", -32600);+ if (!Object.hasOwn(message, "id")) return undefined;+ const { id, method } = message;+ if (method === "initialize") {+ const asked = (message.params as { protocolVersion?: unknown } | undefined)?.protocolVersion;+ return reply(id, { protocolVersion: PROTOCOLS.includes(String(asked)) ? asked : "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: `openmausbot-${name}`, version: "1" } });+ }+ if (method === "ping") return reply(id, {});+ if (method !== "tools/list" && method !== "tools/call") return rpcError(id, "Method not found.", -32601);+ const refuse = (text: string) => (method === "tools/call" ? callError(id, text) : rpcError(id, text));+ const bot = deps.bot(turn.botId);+ const mine = bot ? servers(bot) : {};+ const server = Object.hasOwn(mine, name) ? mine[name] : undefined;+ if (!server) return refuse(`${name} isn't one of your MCP servers on another computer now.`);+ const principal = deps.principal(turn);+ if (!principal) return refuse((method === "tools/call" ? deps.refusal(turn) : deps.notice(turn)) ?? `This conversation can't use ${server.runsOn.label}.`);+ const state = lentState(deps.computers, principal, server);+ if (state.kind !== "ready") return refuse(lentLine(name, state, words));+ const definition = lentDefinition(name, server);+ const active = () => deps.active(turn);+ try {+ if (method === "tools/list") return reply(id, { tools: await tools(state.computerId, definition, principal, active) });+ const params = (message.params ?? {}) as { name?: unknown; arguments?: unknown };+ if (typeof params.name !== "string" || !params.name) return callError(id, "Name the tool to call.");+ const args = params.arguments && typeof params.arguments === "object" && !Array.isArray(params.arguments) ? params.arguments as Record<string, unknown> : {};+ const result = await deps.computers.request({ computer_id: state.computerId, action: "mcp_call", server: definition, tool_name: params.name, arguments: args }, principal, active);+ return reply(id, result && typeof result === "object" ? result : { content: [] });+ } catch (error) {+ return refuse(error instanceof Error ? error.message : `${name} did not answer.`);+ }+ }++ return {+ principal: (turn: Turn): string | null => deps.principal(turn),++ /** A turn's servers that run on a lent computer it may use now, as servers at this server's address. One it can't+ * reach is left out, and lines() says why. */+ mounts(bot: Bot, turn: Turn): Record<string, McpServerSpec> {+ const principal = deps.principal(turn);+ if (!principal) return {};+ const mounted: Record<string, McpServerSpec> = {};+ let token: string | null = null;+ for (const [name, server] of Object.entries(servers(bot))) {+ const state = lentState(deps.computers, principal, server);+ if (state.kind !== "ready") continue;+ token ??= deps.mint(turn);+ mounted[name] = { type: "http", url: `${deps.origin}${LENT_MCP_PATH}${name}`, headers: { authorization: `Bearer ${token}` } };+ void tools(state.computerId, lentDefinition(name, server), principal, () => deps.active(turn)).catch(() => {});+ }+ return mounted;+ },++ /** What the bot is told about each of its servers that runs elsewhere and that its turn can't reach now, by name. */+ lines(bot: Bot, turn: Turn): Map<string, string> {+ const principal = deps.principal(turn);+ const said = new Map<string, string>();+ for (const [name, server] of Object.entries(servers(bot))) {+ const state = lentState(deps.computers, principal, server);+ if (state.kind === "ready") continue;+ const refusal = principal ? null : deps.notice(turn);+ said.set(name, refusal ? `${name} runs on ${server.runsOn.label}. ${refusal}` : lentLine(name, state, words));+ }+ return said;+ },++ /** Runs only once the turn's bearer is checked. */+ async route(ctx: { method: string; path: string; req: IncomingMessage; res: ServerResponse; turn: Turn; readBody(): Promise<unknown>; json(res: ServerResponse, status: number, body: unknown): void }): Promise<typeof PASS | void> {+ if (!isLentMcpPath(ctx.path)) return PASS;+ const name = ctx.path.slice(LENT_MCP_PATH.length);+ if (ctx.method !== "POST") { ctx.res.writeHead(405, { allow: "POST" }).end(); return; }+ const answer = await rpc(name, await ctx.readBody(), ctx.turn);+ if (answer === undefined) { ctx.res.writeHead(202).end(); return; }+ ctx.json(ctx.res, 200, answer);+ },++ async test(name: string, server: StoredMcpServer & { runsOn: McpRunsOn }, principal: string | null, signal: AbortSignal): Promise<{ status: 200; body: McpProbeResult } | { status: 409; error: string }> {+ const state = lentState(deps.computers, principal, server);+ if (!principal) return { status: 409, error: `${name} runs on ${server.runsOn.label}, so it is checked there the next time one of your conversations uses it.` };+ if (state.kind !== "ready") return { status: 409, error: lentLine(name, state, words) };+ try {+ const listed = await tools(state.computerId, lentDefinition(name, server), principal, () => !signal.aborted, true);+ const named = listed.flatMap((tool) => (tool && typeof tool === "object" && typeof (tool as { name?: unknown }).name === "string" ? [tool as { name: string; description?: unknown }] : []));+ const shown = named.slice(0, MAX_TOOLS).map((tool) => ({ name: tool.name, ...(typeof tool.description === "string" ? { description: tool.description.slice(0, 500) } : {}) }));+ return { status: 200, body: { ok: true, tools: shown, ...(named.length > shown.length ? { total: named.length } : {}) } };+ } catch (error) {+ return { status: 200, body: { ok: false, reason: "unreachable", error: error instanceof Error ? error.message : `${name} did not answer.` } };+ }+ },++ /** A server added here that needs the person's own computer, marked as running on the one of theirs lent now: the one+ * named, else the one this session lends from, else the only one. With several and none of those, the adder is asked. */+ async place(server: StoredMcpServer, who: { principal: string | null; session?: string; computer?: string; newest?: boolean }): Promise<{ ok: true; server: StoredMcpServer } | { ok: false; error: string }> {+ if (server.runsOn || !who.principal) return { ok: true, server };+ const lenders = deps.computers.mcpLenders(who.principal);+ if (!lenders.length || !(await needsTheirComputer(server, here))) return { ok: true, server };+ const asked = who.computer?.trim().toLowerCase();+ const named = asked ? lenders.find((lender) => lender.name.toLowerCase() === asked) : undefined;+ const names = lenders.map((lender) => lender.name).join(", ");+ if (asked && !named) return { ok: false, error: `No computer called ${who.computer} is lent to ${deps.place} now. These are: ${names}.` };+ const chosen = named ?? lenders.find((lender) => lender.session === who.session) ?? (lenders.length === 1 || who.newest ? lenders[0] : undefined);+ if (!chosen) return { ok: false, error: `This server runs on the person's own computer, and several are lent to ${deps.place}: ${names}. Ask the person which one in one short question, then add it again with computer set to its name.` };+ return { ok: true, server: { ...server, runsOn: { environmentId: chosen.environmentId, label: chosen.name } } };+ },+ };+}++export type LentMcp = ReturnType<typeof createLentMcp>;++function whichHere(command: string): string | null {+ const dirs = augmentedPath().split(delimiter).filter(Boolean);+ const suffixes = process.platform === "win32" ? ["", ".exe", ".cmd", ".bat"] : [""];+ for (const dir of dirs) for (const suffix of suffixes) if (existsSync(join(dir, `${command}${suffix}`))) return join(dir, `${command}${suffix}`);+ return null;+}diff --git a/server/routes/internal-mcp.test.ts b/server/routes/internal-mcp.test.tsindex 35a543b521..0f7c51a33b 100644--- a/server/routes/internal-mcp.test.ts+++ b/server/routes/internal-mcp.test.ts@@ -7,7 +7,7 @@ import { dirname, join } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";import type { AppConfig } from "../config.ts";-import { createMcpConfig } from "../host/mcp-config.ts";+import { createMcpConfig, type McpConfigDeps } from "../host/mcp-config.ts";import type { TeamConnectionsHost } from "../host/team-connections-host.ts";import { addBotMcpServer, keepForBot } from "../mcp-bot-servers.ts";import { botListing, mcpOwner } from "../mcp-bot-rules.ts";@@ -45,6 +45,11 @@ interface Options {boxed?: boolean;usedBy?: Record<string, string[]>;signInRefusal?: { status: number; error: string };+ /** Lending: how a server on another computer is tested there, whose computers this turn may use, and where an added+ * server that needs the person's computer runs. */+ testElsewhere?: McpConfigDeps["testElsewhere"];+ lender?: string | null;+ place?: InternalMcpDeps["place"];}function fixture(options: Options = {}) {@@ -62,6 +67,7 @@ function fixture(options: Options = {}) {persistMcpServers: (next) => { cfg.mcpServers = next; },savedCustomDomain: () => null,changed: () => {},+ ...(options.testElsewhere ? { testElsewhere: options.testElsewhere } : {}),});let clock = Date.now();const vault = new SecretVault(() => clock);@@ -116,6 +122,8 @@ function fixture(options: Options = {}) {signIns.push({ name, url: server.url });return { posted: true };},+ ...(options.lender !== undefined ? { lender: () => options.lender ?? null } : {}),+ ...(options.place ? { place: options.place } : {}),};const route = createInternalMcpRoutes(deps);const ref = (value: string) => vault.saveRef(owner, `card-${value}`, "Key", value);@@ -358,15 +366,61 @@ describe("internal mcp_server route, Full access", () => {expect(stored("linear")).toMatchObject({ url: linear.url, enabled: true });});- it("refuses a server that runs on another computer, test included", async () => {+ it("never changes, turns on or removes a server that runs on another computer, and never starts it here", async () => {const probe = probeWith({ ok: true, tools: [] });- const { post, stored, lines } = fixture({ servers: { notes: { ...notes, enabled: false, runsOn: MAC } } });- const out = await post({ action: "enable", name: "notes" });- expect(out).toEqual({ status: 403, body: { error: "This server runs on Ada's Mac, so it can't be changed here." } });+ const { post, stored, cfg } = fixture({ servers: { notes: { ...notes, enabled: false, runsOn: MAC } } });+ const before = structuredClone(cfg.mcpServers);+ for (const change of [{ action: "enable" }, { action: "disable" }, { action: "update", command: "evil", args: [] }, { action: "remove" }]) {+ expect(await post({ ...change, name: "notes" })).toEqual({ status: 403, body: { error: "This server runs on Ada's Mac, so it can't be changed here." } });+ }+ expect(cfg.mcpServers).toEqual(before);expect(stored("notes")?.enabled).toBe(false);- expect(await post({ action: "test", name: "notes" })).toEqual({ status: 409, body: { error: "This server runs on Ada's Mac, so it isn't started here." } });+ expect((await post({ action: "test", name: "notes" })).body.text).toBe("MCP server notes: Not tested: This server runs on Ada's Mac, so it isn't started here.");expect(probe).not.toHaveBeenCalled();- expect(lines).toEqual([]);+ });++ it("tests a server that runs on another computer there, for the person this turn acts for", async () => {+ const probe = probeWith({ ok: true, tools: [] });+ const testElsewhere = vi.fn<NonNullable<McpConfigDeps["testElsewhere"]>>(async () => ({ status: 200, body: { ok: true, tools: [{ name: "search_notes" }] } }));+ const { post } = fixture({ servers: { notes: { ...notes, runsOn: MAC } }, testElsewhere, lender: "cloud-home" });+ expect((await post({ action: "test", name: "notes" })).body.text).toBe("MCP server notes: Test: it started and listed its tools: search_notes. That does not show what they return: call one to check.");+ expect(testElsewhere).toHaveBeenCalledWith("notes", expect.objectContaining({ command: "npx", runsOn: MAC }), "cloud-home", expect.any(AbortSignal));+ expect(probe).not.toHaveBeenCalled();++ testElsewhere.mockResolvedValueOnce({ status: 409, error: "notes runs on your Mac (Ada's Mac), which is offline right now: OpenMausBot on it is closed, or the Mac is asleep or off." });+ const offline = await post({ action: "test", name: "notes" });+ expect(offline.body.text).toBe("MCP server notes: Not tested: notes runs on your Mac (Ada's Mac), which is offline right now: OpenMausBot on it is closed, or the Mac is asleep or off.");+ expect(offline.body.text).not.toContain("Could not reach");+ });++ it("a server the bot adds that needs the person's computer is marked as running there, and the person's card turns it on", async () => {+ probeWith({ ok: true, tools: [] });+ const testElsewhere = vi.fn<NonNullable<McpConfigDeps["testElsewhere"]>>(async () => ({ status: 200, body: { ok: true, tools: [{ name: "search_notes" }] } }));+ const place = vi.fn<NonNullable<InternalMcpDeps["place"]>>(async (server) => ({ ok: true, server: { ...server, runsOn: MAC } }));+ const { post, stored, card, respond, chat } = fixture({ full: false, testElsewhere, lender: "cloud-home", place });+ const added = await post({ action: "add", name: "local", type: "http", url: "http://127.0.0.1:19501/mcp" });+ expect(added.status).toBe(201);+ expect(added.body.text).toContain("It runs on Ada's Mac, the person's own computer, and its tools reach you through it while it is online.");+ expect(place).toHaveBeenCalledWith(expect.objectContaining({ url: "http://127.0.0.1:19501/mcp" }), undefined);+ expect(stored("local")).toMatchObject({ url: "http://127.0.0.1:19501/mcp", enabled: false, runsOn: MAC });+ expect(card()?.subtitle).toBe("http://127.0.0.1:19501/mcp\nRuns on Ada's Mac.");+ expect(chat).toHaveLength(1);+ expect((await respond("allow"))?.status).toBe(200);+ expect(stored("local")?.enabled).toBe(true);+ expect(testElsewhere).toHaveBeenCalledWith("local", expect.objectContaining({ runsOn: MAC }), "cloud-home", expect.any(AbortSignal));+ });++ it("an add that can't tell which lent computer runs it saves nothing and says what to ask; a named one is passed on", async () => {+ const place = vi.fn<NonNullable<InternalMcpDeps["place"]>>(async () => ({ ok: false, error: "This server runs on the person's own computer, and several are lent to My Cloud: Ada's Mac, Studio. Ask the person which one in one short question, then add it again with computer set to its name." }));+ const { post, cfg } = fixture({ place });+ const refused = await post({ action: "add", name: "local", command: "/Users/ada/bin/notes-mcp" });+ expect(refused.status).toBe(409);+ expect(refused.body.error).toContain("Ask the person which one");+ expect(cfg.mcpServers).toEqual({});+ place.mockImplementationOnce(async (server) => ({ ok: true, server: { ...server, runsOn: { environmentId: "env-studio", label: "Studio" } } }));+ expect((await post({ action: "add", name: "local", command: "/Users/ada/bin/notes-mcp", computer: "Studio" })).status).toBe(201);+ expect(place).toHaveBeenLastCalledWith(expect.objectContaining({ command: "/Users/ada/bin/notes-mcp" }), "Studio");+ expect(cfg.mcpServers?.local).toMatchObject({ runsOn: { environmentId: "env-studio", label: "Studio" } });});it("refuses removing a server the organisation's policy refuses, with the policy's words", async () => {@@ -539,14 +593,14 @@ describe("internal mcp_server route, Full access", () => {expect(body.dropped).toBeUndefined();});- it("list marks a server on another computer as not this bot's and a policy-refused one as managed", async () => {+ it("list names the computer a server runs on and marks a policy-refused one as managed", async () => {const refuse = (name: string) => (name === "linear" ? "Not approved." : undefined);const { call } = fixture({ servers: { linear, notes: { ...notes, runsOn: MAC } }, refuse });const { body } = await call("GET");const rows = JSON.parse(body.text!.slice(body.text!.indexOf("\n") + 1)) as Array<Record<string, unknown>>;expect(rows).toEqual([expect.objectContaining({ name: "linear", owner: "managed", managedBy: "Acme IT", forThisBot: true }),- expect.objectContaining({ name: "notes", owner: "elsewhere", forThisBot: false }),+ expect.objectContaining({ name: "notes", owner: "elsewhere", runsOn: "Ada's Mac", forThisBot: true }),]);});diff --git a/server/routes/internal-mcp.ts b/server/routes/internal-mcp.tsindex 7a1b41ff71..0321abc7f6 100644--- a/server/routes/internal-mcp.ts+++ b/server/routes/internal-mcp.ts@@ -75,6 +75,11 @@ export interface InternalMcpDeps {/** Shows the person a Sign in card for a server reached by URL; the bot ends its turn and OpenMausBot resumes it when* they finish or set the card aside. */requestSignIn(name: string, server: StoredRemoteMcpServer): { posted: true } | { status: number; error: string };+ /** Whose lent computers this turn may use; null: nobody's. */+ lender?(): string | null;+ /** A server this bot adds that needs the person's own computer, marked as running on the one of theirs lent now+ * (`computer`: the one the bot names, by its name), or why it can't be added yet. */+ place?(server: StoredMcpServer, computer: string | undefined): Promise<{ ok: true; server: StoredMcpServer } | { ok: false; error: string }>;}type Deps = Omit<InternalMcpDeps, "readBody">;@@ -139,12 +144,12 @@ export function showMcpActivity(async function act(deps: Ctx, body: unknown, signal: AbortSignal): Promise<Outcome> {if (!body || typeof body !== "object" || Array.isArray(body)) return { status: 400, error: "request body must be a JSON object" };- const { action, name, ...rest } = body as Record<string, unknown>;+ const { action, name, computer, ...rest } = body as Record<string, unknown>;if (!ACTIONS.includes(action as McpAction)) return { status: 400, error: `mcp_server needs action: one of ${ACTIONS.join(", ")}.` };if (action === "list") return list(deps);if (typeof name !== "string" || !name) return { status: 400, error: `mcp_server ${String(action)} needs name.` };const fields = Object.fromEntries(Object.entries(rest).filter(([key]) => !BOT_STRIPPED_KEYS.includes(key)));- if (action === "add") return add(deps, name, fields, signal);+ if (action === "add") return add(deps, name, fields, signal, typeof computer === "string" ? computer : undefined);const servers = deps.cfg().mcpServers ?? {};if (!Object.hasOwn(servers, name)) {@@ -157,12 +162,13 @@ async function act(deps: Ctx, body: unknown, signal: AbortSignal): Promise<Outcoconst may = botMayChange(owner, server);if (action === "sign_in") return signIn(deps, name, server, owner);if (action === "test") {- if (server.runsOn) return { status: 409, error: runsElsewhere(server.runsOn) };if (owner === "theirs" && !may.ok) return { status: 403, error: may.error };return test(deps, name, server, signal);}- if (!may.ok) return { status: 403, error: may.error };+ // The person's own answer to the card for a server this bot added turns it on, wherever it runs.+ const theirAnswer = deps.approved === true && action === "enable" && owner === "elsewhere";+ if (!may.ok && !theirAnswer) return { status: 403, error: may.error };if (owner === "shared" && !deps.teamAdmin()) return { status: 403, error: ASK_ADMIN };if (action === "disable") return disable(deps, name);if (action === "restart") return restart(deps, name, server, signal);@@ -187,7 +193,7 @@ function list(deps: Deps): Outcome {return [botListing(name, server, {owner,authState: isRemoteMcpServer(server) ? deps.authState(name, server.url) : "none",- forThisBot: !server.runsOn && (!deps.sender.mcpServers || deps.sender.mcpServers.includes(name)) && deps.canUse(name),+ forThisBot: (!deps.sender.mcpServers || deps.sender.mcpServers.includes(name)) && deps.canUse(name),managedBy: deps.managedBy(name, server),})];});@@ -195,7 +201,7 @@ function list(deps: Deps): Outcome {return { status: 200, text: `MCP servers you can see (${rows.length}):\n${JSON.stringify(rows)}` };}-async function add(deps: Deps, name: string, fields: Record<string, unknown>, signal: AbortSignal): Promise<Outcome> {+async function add(deps: Deps, name: string, fields: Record<string, unknown>, signal: AbortSignal, computer?: string): Promise<Outcome> {const managed = deps.addRefusal?.();if (managed) return { status: 403, error: managed };if (!deps.teamAdmin()) return { status: 403, error: ASK_ADMIN };@@ -204,10 +210,12 @@ async function add(deps: Deps, name: string, fields: Record<string, unknown>, siif (!redeemed.ok) return { status: 400, error: redeemed.error };const added = deps.botAdd(deps.cfg().mcpServers ?? {}, redeemed.value);if (!added.ok) return { status: added.status, error: added.error };- const saved = deps.config.add(name, added.server);+ const placed = deps.place ? await deps.place(added.server, computer) : { ok: true as const, server: added.server };+ if (!placed.ok) return { status: 409, error: placed.error };+ const server = placed.server;+ const saved = deps.config.add(name, server);if ("error" in saved) return refused(saved);redeemed.commit();- const server = added.server;const where = folderText(deps, server, added.moved ?? []);if (!deps.fullAccess()) {@@ -394,7 +402,9 @@ function ask(deps: Deps, proposal: Parameters<Deps["requestApproval"]>[0]): Outc}function turnOnText(deps: Deps, server: StoredMcpServer): string {- return `${botServerTarget(server)}\n${serverLine(deps.language(), isRemoteMcpServer(server) ? "server.mcp.card.internet" : "server.mcp.card.local")}`;+ const where = server.runsOn ? serverLine(deps.language(), "server.mcp.card.elsewhere", { computer: server.runsOn.label })+ : serverLine(deps.language(), isRemoteMcpServer(server) ? "server.mcp.card.internet" : "server.mcp.card.local");+ return `${botServerTarget(server)}\n${where}`;}const when = (deps: Ctx) => (deps.approved ? WHEN.approved : WHEN.live);@@ -413,6 +423,7 @@ async function probe(deps: Deps, name: string, server: StoredMcpServer, signal:signal,asBot: { id: deps.sender.id, cwd: deps.ownCwd() },person: (url) => deps.testAs(name, url),+ lender: deps.lender?.() ?? null,});if ("error" in result) return { text: `Not tested: ${result.error}`, line: ["server.mcp.testFailed"] };const probed = result.body as McpProbeResult;@@ -457,8 +468,9 @@ function selection(deps: Deps, name: string): string {}function folderText(deps: Deps, server: StoredMcpServer, moved: ReadonlyArray<{ to: string }>): string {- if (isRemoteMcpServer(server)) return "";- return (server.bot ? " It uses files in your own folder, so it works only for you, not for other bots." : "")+ const elsewhere = server.runsOn ? ` It runs on ${server.runsOn.label}, the person's own computer, and its tools reach you through it while it is online.` : "";+ if (isRemoteMcpServer(server)) return elsewhere;+ return elsewhere + (server.bot ? " It uses files in your own folder, so it works only for you, not for other bots." : "")+ (moved.length ? ` Its files were in this conversation's temporary folder, so they were copied to ${moved.map(({ to }) => relative(deps.ownCwd(), to)).join(", ")} in your own folder, and it runs from there: change them there.` : "");}diff --git a/server/routes/mcp-servers.ts b/server/routes/mcp-servers.tsindex 3e12f23bea..fc59868892 100644--- a/server/routes/mcp-servers.ts+++ b/server/routes/mcp-servers.ts@@ -2,8 +2,9 @@ import { userError, userErrorFields } from "../user-errors.ts";import { hostedWorkspaceConfiguration } from "../enterprise.ts";import { runsElsewhere, type McpConfig, type McpConfigDeps, type McpConfigResult } from "../host/mcp-config.ts";import { McpOAuthError, McpSignInError, mcpCallbackOrigin } from "../mcp-oauth.ts";-import { isRemoteMcpServer, mcpServerBody, mcpServerServes, parseMcpServerMutation, parseMcpServersImport, parseStoredMcpServer } from "../mcp-registry.ts";+import { isRemoteMcpServer, mcpServerBody, mcpServerServes, parseMcpServerMutation, parseMcpServersImport, parseStoredMcpServer, type StoredMcpServer } from "../mcp-registry.ts";import { personKey } from "../person-key.ts";+import type { RequestAuth } from "../request-auth.ts";import { toolBudgetOf } from "../tool-budgets.ts";import { isLoopbackHost, isProxied, provesSameOrigin, requestOrigin } from "../request-auth.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -28,6 +29,10 @@ export interface McpServerRouteDeps extends Pick<McpConfigDeps, "cfg" | "sessionbot(id: string): { id: string; mcpServers?: readonly string[] | null } | null;/** Secrets as booleans, sign-in state attached. */mcpServerResponse(): { servers: readonly ListedMcpServer[] };+ /** Whose lent computers this request may test a server on; null: nobody's. */+ lender?(auth: RequestAuth): string | null;+ /** A server the person adds that needs their own computer, marked as running on the one of theirs lent now. */+ place?(server: StoredMcpServer, auth: RequestAuth): Promise<{ ok: true; server: StoredMcpServer } | { ok: false; error: string }>;}export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {@@ -85,6 +90,7 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {const member = auth.kind === "session" ? sessionMember(auth.session) : null;return member ? deps.teamConnections.people.connection(personKey({ id: "", email: member.member.email }), name, url) : null;},+ lender: deps.lender?.(auth) ?? null,});return answer(res, json, result);} finally {@@ -155,7 +161,9 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {const name = typeof body?.name === "string" ? body.name : "";const parsed = parseMcpServerMutation(name, mcpServerBody(body));if (!parsed.ok) return json(res, 400, { error: parsed.error });- return answer(res, json, config.add(name, parsed.server));+ const placed = deps.place ? await deps.place(parsed.server, auth) : { ok: true as const, server: parsed.server };+ if (!placed.ok) return json(res, 409, { error: placed.error });+ return answer(res, json, config.add(name, placed.server));}// The {"mcpServers": {...}} block other agent tools write; imported servers stay disabled until enabled.@@ -171,7 +179,14 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {}if (!text.trim()) return { status: 400, error: "Paste the JSON block first." };const parsed = parseMcpServersImport(text);- return parsed.ok ? { servers: parsed.servers } : { status: 400, error: parsed.error };+ if (!parsed.ok) return { status: 400, error: parsed.error };+ const servers: Record<string, StoredMcpServer> = {};+ for (const [name, server] of Object.entries(parsed.servers)) {+ const placed = deps.place ? await deps.place(server, auth) : { ok: true as const, server };+ if (!placed.ok) return { status: 409, error: placed.error };+ servers[name] = placed.server;+ }+ return { servers };}));}diff --git a/server/shared-computers.test.ts b/server/shared-computers.test.tsindex fc903b9d85..c6691d8a28 100644--- a/server/shared-computers.test.ts+++ b/server/shared-computers.test.ts@@ -442,3 +442,87 @@ it("a lent call's screen lock left behind by an earlier lent call frees itself fcontrol.release(next);expect(resources.free("computer:host")).toBe(true);});++describe("MCP servers a lent computer runs for this server", () => {+ const home = randomUUID();+ const command = { name: "notes", command: "npx", args: ["-y", "notes-mcp"], env: { NOTES_TOKEN: "saved" } };+ const address = { name: "local", url: "http://127.0.0.1:19501/mcp", type: "http" as const, headers: {} };+ const lender = (scopes: Record<string, unknown> = {}) => ({ ...registration(), name: "Ada's Mac", platform: "darwin" as const, mcpServers: true as const, environments: [home], ...scopes });++ it("takes the new fields from a desktop that runs them, and an MCP job only with the server it names", () => {+ expect(sharedComputerOperation.safeParse({ computer_id: randomUUID(), action: "mcp_tools", server: command }).success).toBe(true);+ expect(sharedComputerOperation.safeParse({ computer_id: randomUUID(), action: "mcp_call", server: address, tool_name: "x".repeat(200), arguments: { q: 1 } }).success).toBe(true);+ for (const server of [{ ...command, extra: true }, { ...address, url: undefined }, { ...command, name: "Bad Name" }]) {+ expect(sharedComputerOperation.safeParse({ computer_id: randomUUID(), action: "mcp_tools", server }).success).toBe(false);+ }+ });++ it("refuses a desktop too old to run them, and a command server where the terminal isn't lent; an address needs no terminal", () => {+ expect(sharedComputerScopeRefusal({ ...lender(), mcpServers: undefined }, { action: "mcp_tools", server: address })).toContain("older OpenMausBot");+ expect(sharedComputerScopeRefusal(lender(), { action: "mcp_call", server: command })).toBe("notes starts a program on Ada's Mac, which doesn't let this server run programs right now. Tell the person in one sentence that they can turn on \"Let Clouds run commands on this Mac\" from the OpenMausBot icon in its menu bar.");+ expect(sharedComputerScopeRefusal(lender(), { action: "mcp_call", server: command }, "ask_for_computer")).toContain('Call ask_for_computer with need "terminal"');+ expect(sharedComputerScopeRefusal(lender({ terminal: true }), { action: "mcp_call", server: command })).toBeNull();+ expect(sharedComputerScopeRefusal(lender(), { action: "mcp_tools", server: address })).toBeNull();+ expect(sharedComputerScopeRefusal(lender(), { action: "mcp_tools" })).toBe("Name the MCP server.");+ });++ it("finds the computer an MCP server runs on by its installs, online or as last known, and never another person's", () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-lent-mcp-"));+ let live = true;+ const broker = new SharedComputers(() => live, new LentComputers(join(dir, "lent.json")));+ const computer = lender(); broker.register(computer, alice, secret);+ const runsOn = { environmentId: home, label: "Old name" };+ expect(broker.runsOn(alice.person, runsOn)).toEqual({ online: { id: computer.id, name: "Ada's Mac", platform: "darwin", terminal: false, mcpServers: true }, known: { name: "Ada's Mac", platform: "darwin", lent: true } });+ expect(broker.runsOn(bob.person, runsOn)).toEqual({ online: null, known: null });+ expect(broker.runsOn(alice.person, { environmentId: randomUUID(), label: "Ada's Mac" }).online, "its installs are known, so its name alone is not it").toBeNull();+ expect(broker.mcpLenders(alice.person)).toEqual([expect.objectContaining({ id: computer.id, name: "Ada's Mac", session: alice.session, environmentId: home })]);+ expect(broker.mcpLenders(bob.person)).toEqual([]);+ live = false;+ expect(broker.runsOn(alice.person, runsOn)).toEqual({ online: null, known: { name: "Ada's Mac", platform: "darwin", lent: true } });+ expect(broker.mcpLenders(alice.person)).toEqual([]);+ live = true;+ broker.disconnect(computer.id, alice.session, secret);+ expect(broker.runsOn(alice.person, runsOn).known).toEqual({ name: "Ada's Mac", platform: "darwin", lent: false });+ const restarted = new SharedComputers(() => true, new LentComputers(join(dir, "lent.json")));+ expect(restarted.runsOn(alice.person, runsOn).known, "remembered across restarts").toEqual({ name: "Ada's Mac", platform: "darwin", lent: false });+ broker.close(); restarted.close();+ rmSync(dir, { recursive: true, force: true });+ });++ it("an older desktop that never said its installs is known by its name", () => {+ const broker = new SharedComputers(() => true);+ const computer = { ...registration(), name: "Ada's Mac", platform: "darwin" as const }; broker.register(computer, alice, secret);+ expect(broker.runsOn(alice.person, { environmentId: home, label: "Ada's Mac" }).online).toMatchObject({ id: computer.id, mcpServers: false });+ expect(broker.mcpLenders(alice.person), "it can't run them, so nothing added here is marked as running on it").toEqual([]);+ broker.close();+ });++ it("an MCP call waits for the computer's current action instead of failing as busy, and gets its own deadline", async () => {+ vi.useFakeTimers();+ const broker = new SharedComputers(() => true);+ const computer = lender(); broker.register(computer, alice, secret);+ const first = broker.request({ computer_id: computer.id, action: "mcp_tools", server: address }, alice.person, () => true);+ const second = broker.request({ computer_id: computer.id, action: "mcp_call", server: address, tool_name: "search" }, alice.person, () => true);+ const job = await broker.poll(computer.id, alice.session, secret);+ expect(job?.operation.action).toBe("mcp_tools");+ broker.liveJob(computer.id, alice.session, secret, job!.id);+ broker.complete(computer.id, alice.session, secret, job!.id, { tools: [{ name: "search" }] });+ await expect(first).resolves.toEqual({ tools: [{ name: "search" }] });+ await vi.advanceTimersByTimeAsync(300);+ const next = await broker.poll(computer.id, alice.session, secret);+ expect(next?.operation).toMatchObject({ action: "mcp_call", tool_name: "search" });+ broker.liveJob(computer.id, alice.session, secret, next!.id);+ await vi.advanceTimersByTimeAsync(300_000);+ broker.complete(computer.id, alice.session, secret, next!.id, { content: [{ type: "text", text: "found" }] });+ await expect(second, "a tool call has five minutes, not 45 seconds").resolves.toEqual({ content: [{ type: "text", text: "found" }] });+ broker.register(computer, alice, secret);+ const blocked = broker.request({ computer_id: computer.id, action: "mcp_tools", server: address }, alice.person, () => true);+ const late = broker.request({ computer_id: computer.id, action: "mcp_tools", server: address }, alice.person, () => true);+ const stuck = expect(late).rejects.toThrow(/busy/);+ await vi.advanceTimersByTimeAsync(31_000);+ await stuck;+ const closed = expect(blocked).rejects.toThrow(/Workspace stopped/);+ broker.close();+ await closed;+ });+});diff --git a/server/shared-computers.ts b/server/shared-computers.tsindex 01ec5d8efc..f1ad76e42e 100644--- a/server/shared-computers.ts+++ b/server/shared-computers.ts@@ -22,24 +22,41 @@ export const sharedComputerRegistration = z.object({longCommands: z.literal(true).optional(),/** It takes edit_file, append_file and delete_file; sent only to a server that advertises fileEdits. */fileEdits: z.literal(true).optional(),+ /** It runs the MCP servers this server keeps for it (mcp_tools, mcp_call); sent only to a server that advertises lentMcp. */+ mcpServers: z.literal(true).optional(),+ /** The environment ids of its own OpenMausBot installs, which an MCP server's `runsOn` names; sent with mcpServers. */+ environments: z.array(z.string().uuid()).max(8).optional(),}).strict();+const wireSecrets = z.record(z.string().min(1).max(256), z.string().max(16_384));+/** An MCP server as this server keeps it for a lent computer: that computer starts, or reaches, exactly this and nothing else. */+export const lentMcpServer = z.union([+ z.object({ name: z.string().regex(/^[a-z][a-z0-9_-]{0,31}$/u), command: z.string().min(1).max(1_024), args: z.array(z.string().max(4_096)).max(64), env: wireSecrets }).strict(),+ z.object({ name: z.string().regex(/^[a-z][a-z0-9_-]{0,31}$/u), url: z.string().min(1).max(2_048), type: z.enum(["http", "sse"]), headers: wireSecrets }).strict(),+]);+export type LentMcpServer = z.infer<typeof lentMcpServer>;export const sharedComputerOperation = z.object({computer_id: z.string().uuid(),- action: z.enum(["list_files", "read_file", "write_file", "edit_file", "append_file", "delete_file", "run_command", "computer_tools", "computer_call"]),+ action: z.enum(["list_files", "read_file", "write_file", "edit_file", "append_file", "delete_file", "run_command", "computer_tools", "computer_call", "mcp_tools", "mcp_call"]),folder_id: z.string().uuid().optional(), path: z.string().max(2048).optional(),content: z.string().max(350_000).optional(), encoding: z.enum(["utf8", "base64"]).optional(),old_text: z.string().min(1).max(350_000).optional(), new_text: z.string().max(350_000).optional(),expected_sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(),- command: z.string().max(8000).optional(), timeout_seconds: z.number().int().min(1).max(900).optional(), tool_name: z.string().max(100).optional(),- arguments: z.record(z.string(), z.unknown()).optional(),+ command: z.string().max(8000).optional(), timeout_seconds: z.number().int().min(1).max(900).optional(), tool_name: z.string().max(256).optional(),+ arguments: z.record(z.string(), z.unknown()).optional(), server: lentMcpServer.optional(),}).strict();type Registration = z.infer<typeof sharedComputerRegistration>;type Operation = z.infer<typeof sharedComputerOperation>;const COMMAND_SECONDS = 120;const OLD_MAX_COMMAND_SECONDS = 240;+/** The desktop gives a server's first start (a package runner fetching it) 130 seconds and a tool call 300. */+const MCP_DEADLINE_MS = { mcp_tools: 145_000, mcp_call: 315_000 } as const;+/** How long an MCP call waits behind the computer's current action, since an engine calls its tools side by side. */+const MCP_QUEUE_MS = 30_000;+const isMcp = (operation: Pick<Operation, "action">): operation is Operation & { action: "mcp_tools" | "mcp_call" } => operation.action === "mcp_tools" || operation.action === "mcp_call";/** A command's deadline is its own limit on the desktop plus time for the result to come back. */const jobDeadlineMs = (registration: Registration, operation: Operation) =>- operation.action === "run_command" && registration.commandTimeouts ? (operation.timeout_seconds ?? COMMAND_SECONDS) * 1000 + 15_000 : 45_000;+ isMcp(operation) ? MCP_DEADLINE_MS[operation.action]+ : operation.action === "run_command" && registration.commandTimeouts ? (operation.timeout_seconds ?? COMMAND_SECONDS) * 1000 + 15_000 : 45_000;/** The registering session alone may poll, answer and disconnect; only that person's bot turns may see or use it. */export type SharedComputerOwner = { session: string; person: string };export type SharedComputerStatus = {@@ -76,8 +93,19 @@ export function responseGone(res: { once(event: "close", listener: () => void):}/** The desktop's grant is the authority and checks every operation again; the server just never queues work outside what it lends. */-export function sharedComputerScopeRefusal(registration: Registration, operation: Pick<Operation, "action" | "folder_id">, askTool: string | null = null): string | null {+export function sharedComputerScopeRefusal(registration: Registration, operation: Pick<Operation, "action" | "folder_id" | "server">, askTool: string | null = null): string | null {switch (operation.action) {+ case "mcp_tools":+ case "mcp_call": {+ const device = deviceWord(registration.platform);+ if (!registration.mcpServers) return `${registration.name} runs an older OpenMausBot that can't run MCP servers for this server. Tell the person in one sentence to update OpenMausBot on that ${device}.`;+ if (!operation.server) return "Name the MCP server.";+ if (!("command" in operation.server) || registration.terminal) return null;+ // Security: a command server starts a program on the person's computer, which is what its terminal switch lends.+ const starts = `${operation.server.name} starts a program on ${registration.name}, which doesn't let this server run programs right now.`;+ return askTool ? `${starts} Call ${askTool} with need "terminal" and why: it asks them with a one-tap Turn on, and you carry on once it's on. Never run it another way or anywhere else.`+ : `${starts} Tell the person in one sentence that they can turn on "Let Clouds run commands on this ${device}" from the OpenMausBot icon in its ${device === "Mac" ? "menu bar" : "taskbar"}.`;+ }case "run_command":if (!registration.terminal && askTool) return `${registration.name} doesn't let this Cloud run commands right now. Call ${askTool} with need "terminal" and why: it asks them with a one-tap Turn on, and you carry on once it's on. Never run the command another way or anywhere else.`;return registration.terminal ? null : `${registration.name} does not lend its terminal, so commands cannot run there. Do not try to run the command another way or anywhere else; use its folders, or tell the person in one sentence what to run themselves, or, when it is their own Cloud, that they can turn on "Let Clouds run commands on this ${deviceWord(registration.platform)}" from the OpenMausBot icon in its menu bar or taskbar.`;@@ -161,7 +189,8 @@ export class SharedComputers {}private remember(registration: Registration, person: string) {this.lent?.connected(person, { id: registration.id, name: registration.name, platform: registration.platform,- folders: registration.folders.length, terminal: registration.terminal, screen: registration.computer, internet: registration.internet === true, chrome: registration.chrome === true });+ folders: registration.folders.length, terminal: registration.terminal, screen: registration.computer, internet: registration.internet === true, chrome: registration.chrome === true,+ ...(registration.environments ? { environments: registration.environments } : {}) });}private reap() {for (const [key, entry] of this.computers) {@@ -186,6 +215,29 @@ export class SharedComputers {return [...this.computers.values()].filter(entry => entry.owner.person === principal && this.online(entry)).map(({ registration: { id, name, platform, computer, terminal } }) => ({ id, name, ...(platform ? { platform } : {}), computer, terminal }));}+ /** The computer of this person's that `runsOn` names: online now (and what it lends), else as last known, else neither.+ * It is known by its installs' environment ids, or, from a desktop that never said them, by its name. */+ runsOn(principal: string | null, runsOn: { environmentId: string; label: string }): {+ online: { id: string; name: string; platform: LentPlatform | null; terminal: boolean; mcpServers: boolean } | null;+ known: { name: string; platform: LentPlatform | null; lent: boolean } | null;+ } {+ if (!principal) return { online: null, known: null };+ const names = (environments: readonly string[] | undefined, name: string) => environments?.includes(runsOn.environmentId) ?? name === runsOn.label;+ const entry = [...this.computers.values()].find((candidate) => candidate.owner.person === principal && this.online(candidate) && names(candidate.registration.environments, candidate.registration.name));+ const record = this.lent?.list(principal).find((candidate) => names(candidate.environments, candidate.name));+ return {+ online: entry ? { id: entry.registration.id, name: entry.registration.name, platform: entry.registration.platform ?? null, terminal: entry.registration.terminal, mcpServers: entry.registration.mcpServers === true } : null,+ known: record ? { name: record.name, platform: record.platform, lent: record.stoppedAt === null } : null,+ };+ }+ /** This person's online computers that run MCP servers for this server, each with the session that lent it and its first+ * install's environment id: where a server added here that needs their computer is marked as running. */+ mcpLenders(principal: string | null): { id: string; name: string; platform: LentPlatform | null; session: string; environmentId: string; seen: number }[] {+ if (!principal) return [];+ return [...this.computers.values()].filter((entry) => entry.owner.person === principal && this.online(entry) && entry.registration.mcpServers === true && entry.registration.environments?.length)+ .map((entry) => ({ id: entry.registration.id, name: entry.registration.name, platform: entry.registration.platform ?? null, session: entry.owner.session, environmentId: entry.registration.environments![0]!, seen: entry.seen }))+ .sort((a, b) => b.seen - a.seen);+ }/** Every computer this person lent, now or before, newest first: online, offline since, or no longer lent. */known(principal: string | null): KnownLentComputer[] {if (!principal) return [];@@ -322,13 +374,19 @@ export class SharedComputers {}await new Promise(resolve => setTimeout(resolve, 250));}- const entry = lent()!;+ let entry = lent()!;const refusal = sharedComputerScopeRefusal(entry.registration, operation, this.askTool);if (refusal) throw failure(refusal, 403);if (operation.action === "run_command" && entry.registration.commandTimeouts && !entry.registration.longCommands && (operation.timeout_seconds ?? 0) > OLD_MAX_COMMAND_SECONDS) {throw failure(`${entry.registration.name} runs an older OpenMausBot that stops a command after at most ${OLD_MAX_COMMAND_SECONDS} seconds. Give timeout_seconds of ${OLD_MAX_COMMAND_SECONDS} or less, or run longer jobs in the background with output to a file.`, 400);}- if (entry.jobs.size >= 1) throw failure("This shared computer is busy. Wait for its current action to finish.");+ for (const until = Date.now() + (isMcp(operation) ? MCP_QUEUE_MS : 0); entry.jobs.size >= 1;) {+ if (Date.now() >= until || !active()) throw failure("This shared computer is busy. Wait for its current action to finish.");+ await new Promise(resolve => setTimeout(resolve, 250));+ const again = lent();+ if (!again || !this.online(again)) throw failure(this.offline(principal, operation.computer_id));+ entry = again;+ }if (!active()) throw failure("The requesting turn ended", 401);const { timeout_seconds: _timeout, ...withoutTimeout } = operation;const timed = entry.registration.commandTimeouts ? operation : withoutTimeout;diff --git a/src/locales/en.json b/src/locales/en.jsonindex 1185c582fa..c4fe3ac6fc 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -260,6 +260,7 @@"server.mcp.card.remove": "Remove {name}?","server.mcp.card.internet": "Reached over the internet. Once on, your bots can use its tools.","server.mcp.card.local": "Runs on this computer.",+ "server.mcp.card.elsewhere": "Runs on {computer}.","server.mcp.card.newKey": "new key for {key}","server.mcp.card.cleared": "Clears the saved {items}.","server.mcp.card.usedBy": "Used by {names}.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex b6bf9530a6..4977185e7f 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -243,6 +243,7 @@"server.mcp.card.remove": "Remover {name}?","server.mcp.card.internet": "A conexão é pela internet. Com o servidor ligado, seus bots podem usar as ferramentas dele.","server.mcp.card.local": "Roda neste computador.",+ "server.mcp.card.elsewhere": "Roda em {computer}.","server.mcp.card.newKey": "nova chave para {key}","server.mcp.card.cleared": "Limpa estes dados salvos: {items}.","server.mcp.card.usedBy": "Usado por {names}.",