Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
MCP servers on a lent computer: pass the calling bot and conversation as an unverified hint
AdityaUmale8a8a85f69521
diff --git a/docs/custom-mcp-servers.md b/docs/custom-mcp-servers.mdindex cf12a84655..a6889727be 100644--- a/docs/custom-mcp-servers.md+++ b/docs/custom-mcp-servers.md@@ -414,6 +414,22 @@ An HTTP 401 tells the bot to send the message again (a sign-in is refreshedwhen a message starts) and, if that fails, to sign in again or check theserver's header values in Plugins → MCP servers.+### Which bot made a call, on a server that runs on a lent computer++A server saved on a Cloud to run on a computer lent to it is started by that+computer. Each tool call it gets names the bot and conversation that made it,+in the call's `_meta`:++```json+{ "_meta": { "openmausbot/caller": { "botId": "…", "threadId": "…", "verified": false } } }+```++It is a hint for the server's own logs or per-bot settings, never proof of+who called: the Cloud says it, the computer passes it on as it is, and+OpenMausBot never uses it to allow or refuse anything. The Cloud sends it+only to a desktop app new enough to pass it on, so an older one keeps running+calls as before; a listing of the server's tools never carries it.+## What a Claude bot sees, and the "Also use my Claude Code MCP servers" switchA bot on the Claude engine gets the tools and instructions its owner gave it:diff --git a/electron/computer-sharing.mjs b/electron/computer-sharing.mjsindex 34c1629503..74a8419767 100644--- a/electron/computer-sharing.mjs+++ b/electron/computer-sharing.mjs@@ -6,7 +6,7 @@ import { randomBytes, randomUUID } from "node:crypto";import { setTimeout as delay } from "node:timers/promises";import { allowedServerOrigin } from "./server-address.mjs";import { createSharedCua, executeSharedOperation, personalSecretPaths, sharedComputerError, validCommandSeconds } from "./shared-computer-access.mjs";-import { createLentMcp, LENT_MCP_ACTIONS, ownPorts, validLentMcpServer } from "./lent-mcp.mjs";+import { createLentMcp, LENT_MCP_ACTIONS, ownPorts, validLentMcpJob } from "./lent-mcp.mjs";import { sharedCuaConnection } from "./shared-cua-connection.mjs";export { sharedCuaConnection };import { createLendingActivity, describeSharedOperation } from "./lending-activity.mjs";@@ -110,7 +110,7 @@ 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", "server"]);+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", "caller"]);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. */@@ -125,7 +125,7 @@ export function validSharedOperation(operation, computerId) {(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, 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);+ validLentMcpJob(operation);}export function cloudLendingVerdict(binding, current, env) {@@ -148,9 +148,9 @@ export function ownServerSession(auth) {}/** What a Cloud that keeps MCP servers for this computer hears: it runs them, and which installs here it is. */-const lendsMcp = environments => {+const lendsMcp = (environments, caller) => {const ids = Array.isArray(environments) ? environments.filter(uuid).slice(0, 8) : [];- return { mcpServers: true, ...(ids.length ? { environments: ids } : {}) };+ return { mcpServers: true, ...(ids.length ? { environments: ids } : {}), ...(caller ? { mcpCaller: true } : {}) };};/** A Cloud grant lends the internet connection unless it was unticked: one kept without `internet` lends it too. */@@ -417,7 +417,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo// A server of the person's own says what it takes from them in their own sign-in's answer (`lending`), never before pairing.const offered = { ...descriptor.capabilities, ...(ownServerSession(auth) && auth.lending && typeof auth.lending === "object" ? auth.lending : {}) };if (required && offered.sharedComputers !== true) throw new Error(UPDATE_SERVER);- return { supported: offered.sharedComputers === true, auth, info: { sessionId: auth.id, environmentId: descriptor.environmentId }, details: offered.lendingDetails === true, link: offered.deviceLink === true, chrome: offered.myChromeLink === true, timeouts: offered.commandTimeouts === true, long: offered.longCommands === true, edits: offered.fileEdits === true, asks: offered.computerAsks === true, mcp: offered.lentMcp === true };+ return { supported: offered.sharedComputers === true, auth, info: { sessionId: auth.id, environmentId: descriptor.environmentId }, details: offered.lendingDetails === true, link: offered.deviceLink === true, chrome: offered.myChromeLink === true, timeouts: offered.commandTimeouts === true, long: offered.longCommands === true, edits: offered.fileEdits === true, asks: offered.computerAsks === true, mcp: offered.lentMcp === true, caller: offered.mcpCaller === true };};const identity = async env => {await requireEnabled();@@ -430,8 +430,8 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo* 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; };/** What the server says it takes, remembered for its connect; a server of the person's own never gets the device link. */- const takes = (env, { details, link, chrome: takesChrome, timeouts, long, edits, mcp }) => {- for (const [set, on] of [[supportsDetails, details], [supportsLink, link], [supportsChrome, takesChrome], [supportsTimeouts, timeouts], [supportsLong, long], [supportsEdits, edits], [supportsMcp, mcp]]) {+ const takes = (env, { details, link, chrome: takesChrome, timeouts, long, edits, mcp, caller }) => {+ for (const [set, on] of [[supportsDetails, details], [supportsLink, link], [supportsChrome, takesChrome], [supportsTimeouts, timeouts], [supportsLong, long], [supportsEdits, edits], [supportsMcp, mcp], [supportsMcpCaller, caller]]) {if (on) set.add(env.id); else set.delete(env.id);}};@@ -451,8 +451,8 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lotakes(env, { ...described, link: false, chrome: false });return described.info;};- /** The Clouds that keep MCP servers for this computer to run. */- const supportsMcp = new Set();+ /** The Clouds that keep MCP servers for this computer to run, and those that say which bot and conversation made a call. */+ const supportsMcp = new Set(), supportsMcpCaller = new Set();const supportsDetails = new Set();const supportsLink = new Set();/** The Clouds that take the person's Chrome over the device link. */@@ -539,7 +539,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lo...(supportsTimeouts.has(env.id) ? { commandTimeouts: true } : {}),...(supportsLong.has(env.id) ? { longCommands: true } : {}),...(supportsEdits.has(env.id) ? { fileEdits: true } : {}),- ...((grant.cloud || grant.own) && supportsMcp.has(env.id) ? lendsMcp(localEnvironments()) : {}),+ ...((grant.cloud || grant.own) && supportsMcp.has(env.id) ? lendsMcp(localEnvironments(), supportsMcpCaller.has(env.id)) : {}),}, signal, grant.secret);if (signal.aborted) break;status.set(env.id, { connected: true });diff --git a/electron/lend-own-server.node-test.mjs b/electron/lend-own-server.node-test.mjsindex 1cfea4d3df..afb80a237b 100644--- a/electron/lend-own-server.node-test.mjs+++ b/electron/lend-own-server.node-test.mjs@@ -31,13 +31,13 @@ async function scratch(t) {/** A self-hosted server as this desktop's sign-in there sees it: `scopes`, whether nobody else signs in there (`own`, which* the server says only to its one owner, with what it takes from them), and whether it is a team's or a Cloud. Its public* description offers no lending, as before pairing. */-function selfHosted({ scopes = ["admin", "client"], own = true, extra = {}, mcp = true } = {}) {+function selfHosted({ scopes = ["admin", "client"], own = true, extra = {}, mcp = true, caller = false } = {}) {const json = (value, status = 200) => ({ ok: status < 400, status, headers: { get: () => null }, body: (async function* () { yield Buffer.from(JSON.stringify(value)); })() });const state = { environmentId: randomUUID(), sessionId: randomUUID(), scopes, own, extra, connects: [], disconnects: [], polls: 0 };state.fetch = async (url, init) => {const route = new URL(url).pathname;const owner = state.own && state.scopes.includes("admin");- if (route === "/api/auth/session") return json({ kind: "session", id: state.sessionId, scopes: state.scopes, ...(owner ? { own: true, lending: { sharedComputers: true, lendingDetails: true, fileEdits: true, ...(mcp ? { lentMcp: true } : {}) } } : {}), ...state.extra });+ if (route === "/api/auth/session") return json({ kind: "session", id: state.sessionId, scopes: state.scopes, ...(owner ? { own: true, lending: { sharedComputers: true, lendingDetails: true, fileEdits: true, ...(mcp ? { lentMcp: true } : {}), ...(mcp && caller ? { mcpCaller: true } : {}) } } : {}), ...state.extra });if (route === "/.well-known/openmausbot/environment") return json({ environmentId: state.environmentId, capabilities: { remoteSessions: true } });const body = init?.body ? JSON.parse(init.body) : {};if (route === "/api/shared-computers/connect") { state.connects.push(body); return json({ ok: true }); }@@ -91,12 +91,22 @@ test("once the person allows it, a server of their own gets the apps on the screassert.deepEqual({ computer: connect.computer, terminal: connect.terminal, folders: connect.folders, mcpServers: connect.mcpServers, environments: connect.environments, fileEdits: connect.fileEdits },{ computer: true, terminal: false, folders: [], mcpServers: true, environments: [server.environmentId], fileEdits: true });assert.equal("internet" in connect || "chrome" in connect, false, "the device link is a Cloud's alone");+ assert.equal("mcpCaller" in connect, false, "an older server refuses fields it does not know");assert.equal(await mac.sharing.ownOffer(garage), null, "answered for this pairing");assert.deepEqual(mac.summaries.at(-1).lending, [garage.id]);assert.deepEqual(mac.summaries.at(-1).clouds, ["Garage"], "the menu-bar item names it like a Cloud");assert.equal(mac.summaries.at(-1).terminalSwitch, false, "the Clouds' terminal switch stays out of the menu without a Cloud");});+test("a server of their own that takes an MCP call's caller hears that this computer passes it on", async t => {+ const server = selfHosted({ caller: true });+ const mac = await desktop(t, server);+ await mac.sharing.ownOffer(garage);+ await mac.sharing.lendOwn(garage, { folders: [], terminal: false, computer: true });+ await until(() => server.connects.length === 1 && mac.sharing.state(garage.id).connected, "the server to take this computer");+ assert.deepEqual({ mcpServers: server.connects[0].mcpServers, mcpCaller: server.connects[0].mcpCaller }, { mcpServers: true, mcpCaller: true });+});+test("a narrower pairing, a server others sign in to, a team's server or a Cloud is never asked about and is never lent", async t => {for (const [what, server] of [["client scope", selfHosted({ scopes: ["client"] })], ["others sign in there", selfHosted({ own: false })], ["team", selfHosted({ extra: { team: { id: "t", role: "admin" } } })], ["Cloud", selfHosted({ extra: { cloudHome: true } })]]) {const mac = await desktop(t, server);diff --git a/electron/lent-mcp.d.mts b/electron/lent-mcp.d.mtsindex 55b03a9e08..425bce9470 100644--- a/electron/lent-mcp.d.mts+++ b/electron/lent-mcp.d.mts@@ -2,7 +2,9 @@ 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 const CALLER_META: "openmausbot/caller";export function validLentMcpServer(server: unknown): server is LentMcpServer;+export function validLentMcpJob(operation: { action?: unknown; server?: unknown; caller?: unknown }): boolean;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[];@@ -16,6 +18,6 @@ export function createLentMcp(options?: {/** The ports a URL server is refused on: this computer's own. */ports?: () => Promise<number[]>;}): {- call(operation: { action: "mcp_tools" | "mcp_call"; server: LentMcpServer; tool_name?: string; arguments?: Record<string, unknown> }, signal: AbortSignal): Promise<unknown>;+ call(operation: { action: "mcp_tools" | "mcp_call"; server: LentMcpServer; tool_name?: string; arguments?: Record<string, unknown>; caller?: { botId: string; threadId: string } }, signal: AbortSignal): Promise<unknown>;close(): Promise<void>;};diff --git a/electron/lent-mcp.mjs b/electron/lent-mcp.mjsindex 61c468b953..5fdc49fa97 100644--- a/electron/lent-mcp.mjs+++ b/electron/lent-mcp.mjs@@ -13,6 +13,17 @@ import { DESKTOP_PORTS } from "./desktop-ports.mjs";import { commandPath } from "./shell-path.mjs";export const LENT_MCP_ACTIONS = new Set(["mcp_tools", "mcp_call"]);+/** Where a tools/call's `_meta` says which bot and conversation made it, as the Cloud says: a hint for the MCP server,+ * never proof of identity (`verified: false`). */+export const CALLER_META = "openmausbot/caller";+const callerMeta = caller => caller ? { _meta: { [CALLER_META]: { botId: caller.botId, threadId: caller.threadId, verified: false } } } : {};+const callerId = value => typeof value === "string" && value.length > 0 && value.length <= 128;+/** A job's MCP server, only on an MCP action, and its caller, only on a tool call: passed on as a hint, never trusted. */+export function validLentMcpJob({ action, server, caller }) {+ const validCaller = caller === undefined || (action === "mcp_call" && Boolean(caller) && typeof caller === "object" &&+ !Array.isArray(caller) && Object.keys(caller).length === 2 && callerId(caller.botId) && callerId(caller.threadId));+ return (LENT_MCP_ACTIONS.has(action) ? validLentMcpServer(server) : server === undefined) && validCaller;+}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}$/;@@ -300,7 +311,8 @@ export function createLentMcp({ environment = async () => ({ ...inheritedEnviron});}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));+ const meta = callerMeta(operation.caller);+ return use(server, signal, client => client.request("tools/call", { name: operation.tool_name, arguments: operation.arguments ?? {}, ...meta }, signal, CALL_MS));},/** Resolves once every server it started has exited, or after five seconds. */close: () => Promise.all([...running.keys()].map(stop)).then(() => {}),diff --git a/electron/lent-mcp.node-test.mjs b/electron/lent-mcp.node-test.mjsindex bce15345cd..ee212b75c4 100644--- a/electron/lent-mcp.node-test.mjs+++ b/electron/lent-mcp.node-test.mjs@@ -5,7 +5,7 @@ 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, inheritedEnvironment, isLoopbackAddress, lentMcpRefusal, ownEnvironmentIds, ownPorts, validLentMcpServer, windowsLaunch } from "./lent-mcp.mjs";+import { CALLER_META, createLentMcp, inheritedEnvironment, isLoopbackAddress, lentMcpRefusal, ownEnvironmentIds, ownPorts, validLentMcpServer, windowsLaunch } from "./lent-mcp.mjs";import { executeSharedOperation } from "./shared-computer-access.mjs";import { validSharedOperation } from "./computer-sharing.mjs";@@ -53,6 +53,13 @@ test("takes a server only in the shape the Cloud sends, and an MCP job only withassert.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);+ const caller = { botId: "kiwi", threadId: "t-1" };+ assert.equal(validSharedOperation({ computer_id: id, action: "mcp_call", server: command, tool_name: "x", caller }, id), true);+ for (const bad of [{ ...caller, extra: 1 }, { botId: "kiwi" }, { botId: "", threadId: "t" }, { botId: "k", threadId: "t".repeat(129) }, { botId: 1, threadId: "t" }, [], null, "kiwi"]) {+ assert.equal(validSharedOperation({ computer_id: id, action: "mcp_call", server: command, tool_name: "x", caller: bad }, id), false, JSON.stringify(bad));+ }+ assert.equal(validSharedOperation({ computer_id: id, action: "mcp_tools", server: command, caller }, id), false, "only a tool call names its caller");+ assert.equal(validSharedOperation({ computer_id: id, action: "read_file", path: "a", caller }, 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", () => {@@ -180,6 +187,9 @@ test("an address on this computer gets MCP messages with its saved headers, as Jassert.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"]);+ assert.equal("_meta" in seen[3].message.params, false, "no caller from the Cloud: no _meta");+ await lent.call({ action: "mcp_call", server, tool_name: "search", arguments: { q: "plan" }, caller: { botId: "kiwi", threadId: "t-1" } }, signal());+ assert.deepEqual(seen[4].message.params, { name: "search", arguments: { q: "plan" }, _meta: { [CALLER_META]: { botId: "kiwi", threadId: "t-1", verified: false } } }, "the caller goes to the MCP server as an unverified hint");});test("an address that refuses its keys, redirects or isn't there says so plainly, with no key in the words", async t => {diff --git a/server/environment.test.ts b/server/environment.test.tsindex 70d8323c1b..d7c9253238 100644--- a/server/environment.test.ts+++ b/server/environment.test.ts@@ -136,7 +136,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, lentMcp: true, selfUpdate: "desktop-managed", emailSignIn: false, jobs: true });+ .toEqual({ remoteSessions: true, sharedComputers: true, lendingDetails: true, commandTimeouts: true, longCommands: true, fileEdits: true, lentMcp: true, mcpCaller: 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", install: expect.any(String), emailSignIn: false, jobs: true });expect(environmentDescriptor({ environmentId: "abc", desktopManaged: false, cloudHome: false }).capabilities).not.toHaveProperty("cloudHome");@@ -145,7 +145,7 @@ 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, lentMcp: true, myChromeLink: true, computerAsks: true, cloudHome: true, move: 1, selfUpdate: "operator", install: expect.any(String), emailSignIn: false, jobs: true });+ .toEqual({ remoteSessions: true, sharedComputers: true, lendingDetails: true, commandTimeouts: true, longCommands: true, fileEdits: true, deviceLink: true, lentMcp: true, mcpCaller: true, myChromeLink: true, computerAsks: true, cloudHome: true, move: 1, selfUpdate: "operator", install: expect.any(String), emailSignIn: false, jobs: true });expect(environmentDescriptor({ environmentId: "abc", desktopManaged: true, sharedComputers: true }).capabilities).not.toHaveProperty("deviceLink");});@@ -153,6 +153,7 @@ describe("environment identity", () => {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: true, cloudHome: true, cloudTeam: true }).capabilities).not.toHaveProperty("mcpCaller");expect(environmentDescriptor({ ...base, sharedComputers: false, cloudHome: true }).capabilities).not.toHaveProperty("lentMcp");});diff --git a/server/environment.ts b/server/environment.tsindex 058761d4a2..1fd5e4b289 100644--- a/server/environment.ts+++ b/server/environment.ts@@ -123,7 +123,7 @@ export function serverInstall(env: NodeJS.ProcessEnv = process.env, script = pro/** What a server only its one owner signs in to takes from that owner's own desktop by default: told in the owner's own* /api/auth/session answer, never in the description anyone may read before pairing. */-export const OWNER_LENDING = Object.freeze({ sharedComputers: true, lendingDetails: true, commandTimeouts: true, longCommands: true, fileEdits: true, lentMcp: true } as const);+export const OWNER_LENDING = Object.freeze({ sharedComputers: true, lendingDetails: true, commandTimeouts: true, longCommands: true, fileEdits: true, lentMcp: true, mcpCaller: true } as const);export function environmentDescriptor(input: { environmentId: string; desktopManaged: boolean; emailSignIn?: boolean; sharedComputers?: boolean; cloudHome?: boolean; cloudTeam?: boolean; ownHome?: boolean; label?: string }): EnvironmentDescriptor {return {@@ -137,7 +137,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.cloudTeam !== true ? { lentMcp: true as const, mcpCaller: 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/lent-mcp.test.ts b/server/lent-mcp.test.tsindex 2606dff63b..445b016d3b 100644--- a/server/lent-mcp.test.ts+++ b/server/lent-mcp.test.ts@@ -49,10 +49,10 @@ function fixture(options: { keys?: LentMcpDeps["keys"]; online?: Partial<Online>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") {+async function route(lent: ReturnType<typeof createLentMcp>, path: string, body: unknown, method = "POST", turn = TURN) {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 });+ const out = await lent.route({ method, path, req: {} as IncomingMessage, res, turn, readBody: async () => body, json });return { out, json, res };}@@ -169,8 +169,10 @@ describe("the MCP endpoint a turn's engine reaches", () => {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" } } },+ { 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" }, caller: { botId: "kiwi", threadId: "t-1" } } },]);+ await route(lent, `${LENT_MCP_PATH}local`, rpc("tools/call", { name: "search", arguments: {} }, 3), "POST", { ...TURN, threadId: "t".repeat(129) });+ expect(requests.at(-1)!.operation, "an id the desktop wouldn't take: the call goes without its caller").not.toHaveProperty("caller");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);});diff --git a/server/lent-mcp.ts b/server/lent-mcp.tsindex d5e4e3d0e3..acb7510460 100644--- a/server/lent-mcp.ts+++ b/server/lent-mcp.ts@@ -17,7 +17,7 @@ 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";+import type { LentMcpServer, McpCaller, SharedComputers } from "./shared-computers.ts";import type { McpKeys } from "./vault/mcp-keys.ts";export const LENT_MCP_PATH = "/api/internal/lent/mcp/";@@ -130,6 +130,11 @@ export function lentLine(name: string, state: Exclude<LentState, { kind: "ready"}type Turn = { botId: string; threadId: string; generation: string };+/** Which bot and conversation made a call, for the MCP server: left out when an id isn't in the shape the desktop takes,+ * so a hint never costs the call itself. */+const callerId = (id: string): boolean => id.length > 0 && id.length <= 128;+const callerOf = (turn: Turn): { caller?: McpCaller } =>+ callerId(turn.botId) && callerId(turn.threadId) ? { caller: { botId: turn.botId, threadId: turn.threadId } } : {};type Rpc = { jsonrpc?: unknown; id?: string | number | null; method?: unknown; params?: unknown };export interface LentMcpDeps {@@ -223,7 +228,7 @@ export function createLentMcp(deps: LentMcpDeps) {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, bot?.name && bot.color ? { name: bot.name, color: bot.color } : null);+ const result = await deps.computers.request({ computer_id: state.computerId, action: "mcp_call", server: definition, tool_name: params.name, arguments: args, ...callerOf(turn) }, principal, active, bot?.name && bot.color ? { name: bot.name, color: bot.color } : null);return reply(id, result && typeof result === "object" ? result : { content: [] });} catch (error) {return refuse(error instanceof Error ? error.message : `${name} did not answer.`);diff --git a/server/shared-computers.test.ts b/server/shared-computers.test.tsindex 300cf9289e..78f971f3d6 100644--- a/server/shared-computers.test.ts+++ b/server/shared-computers.test.ts@@ -189,6 +189,27 @@ describe("shared computer authority and lifecycle", () => {broker.close();}});+ it("sends an MCP call's caller only to a desktop that said it takes one, so an older desktop keeps running MCP calls", async () => {+ const server = { name: "local", url: "http://127.0.0.1:19501/mcp", type: "http" as const, headers: {} };+ const caller = { botId: "kiwi", threadId: "t-1" };+ for (const [scopes, sent] of [[{ mcpServers: true as const }, false], [{ mcpServers: true as const, mcpCaller: true as const }, true]] as const) {+ const broker = new SharedComputers(() => true);+ const computer = { ...registration(), ...scopes }; broker.register(computer, alice, secret);+ const call = broker.request({ computer_id: computer.id, action: "mcp_call", server, tool_name: "search", arguments: {}, caller }, alice.person, () => true);+ call.catch(() => {});+ const job = await broker.poll(computer.id, alice.session, secret);+ expect(job!.operation.caller, JSON.stringify(scopes)).toEqual(sent ? caller : undefined);+ expect("caller" in job!.operation).toBe(sent);+ broker.close();+ }+ const broker = new SharedComputers(() => true);+ const computer = { ...registration(), mcpServers: true as const, mcpCaller: true as const }; broker.register(computer, alice, secret);+ const list = broker.request({ computer_id: computer.id, action: "mcp_tools", server, caller }, alice.person, () => true);+ list.catch(() => {});+ expect("caller" in (await broker.poll(computer.id, alice.session, secret))!.operation, "only a tool call names its caller").toBe(false);+ broker.close();+ expect(sharedComputerOperation.safeParse({ computer_id: computer.id, action: "mcp_call", server, tool_name: "x", caller }).success, "a bot's own operation can't name a caller").toBe(false);+ });it("turn cancellation rejects queued and already delivered actions", async () => {vi.useFakeTimers();const broker = new SharedComputers(() => true);diff --git a/server/shared-computers.ts b/server/shared-computers.tsindex ace06a61f1..4e56edd61d 100644--- a/server/shared-computers.ts+++ b/server/shared-computers.ts@@ -26,6 +26,8 @@ export const sharedComputerRegistration = z.object({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(),+ /** It passes an MCP call's caller on to the MCP server; sent only to a server that advertises mcpCaller. */+ mcpCaller: z.literal(true).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. */@@ -44,8 +46,11 @@ export const sharedComputerOperation = z.object({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();+/** Which bot and conversation made an MCP call: a hint for the MCP server, never proof of identity. Only this server's+ * own lent-MCP route sets it; a bot's shared_computer operation can't (sharedComputerOperation refuses the field). */+export type McpCaller = { botId: string; threadId: string };type Registration = z.infer<typeof sharedComputerRegistration>;-type Operation = z.infer<typeof sharedComputerOperation>;+type Operation = z.infer<typeof sharedComputerOperation> & { caller?: McpCaller };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. */@@ -445,7 +450,9 @@ export class SharedComputers {const { timeout_seconds: _timeout, ...withoutTimeout } = operation;const timed = entry.registration.commandTimeouts ? operation : withoutTimeout;const { old_text: _old, new_text: _new, ...withoutEdits } = timed;- const forDesktop = entry.registration.fileEdits ? timed : withoutEdits;+ const edited = entry.registration.fileEdits ? timed : withoutEdits;+ const { caller: _caller, ...withoutCaller } = edited;+ const forDesktop = entry.registration.mcpCaller && operation.action === "mcp_call" ? edited : withoutCaller;return new Promise((resolve, reject) => {const id = randomUUID();const job: Job = { id, operation: forDesktop, ...(by ? { by: { name: by.name, color: by.color } } : {}), active, sent: false, leased: false, resolve, reject, timer: setTimeout(() => this.finish(entry, job, failure("Computer action timed out. Its outcome is unknown; inspect before retrying.")), jobDeadlineMs(entry.registration, operation)) };