Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat: save MCP results over 50 KB to a file in the bot's folder
AdityaUmaleb60798ef2d6f
diff --git a/server/contracts.ts b/server/contracts.tsindex f20594f396..cd23b9dfa0 100644--- a/server/contracts.ts+++ b/server/contracts.ts@@ -197,6 +197,8 @@ export interface SendTurnInput {customResultBudgets?: Record<string, number>;};cwd?: string;+ /** Engines with no working folder (the chat drivers): where an MCP result too big for the model is saved whole. */+ toolResultFolder?: string;/** Also load the person's own CLI MCP setup (Claude Code user scope, claude.ai connectors). */mcpFromUserConfig?: boolean;/** Claude Code loads the person's own `~/.claude/skills` from this folder's `.claude/skills` (`--add-dir`). */diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.tsindex 3b3dec7907..02a2dcca14 100644--- a/server/drivers/chat-mcp-tools.test.ts+++ b/server/drivers/chat-mcp-tools.test.ts@@ -1,10 +1,10 @@-import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";import { crc32 } from "node:zlib";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";import { augmentedPath } from "../env-path.ts";-import { ChatToolSessionError, chatToolNotices, directServers, mountChatTools, trimmedToolsNotice, type ChatToolSession } from "./chat-mcp-tools.ts";+import { ChatToolSessionError, SAVED_RESULTS_FOLDER, chatToolNotices, directServers, mountChatTools, trimmedToolsNotice, type ChatToolSession } from "./chat-mcp-tools.ts";import type { ToolScope } from "../../shared/tool-scope.ts";import { catalogServer, CUA_DRIVER_WINDOWS_TOOLS, syntheticToolNames } from "../testing/cua-driver-tools.ts";import { startFakeHttpMcp } from "../testing/fake-http-mcp-server.ts";@@ -73,8 +73,9 @@ function fixture(body = "", toolSchema: Record<string, unknown> = schema) {return {dir, receipt, controller, server,read: () => JSON.parse(readFileSync(receipt, "utf8")) as { pid: number; path: string; omb: Record<string, string>; calls: Array<{ method: string; params?: { name?: string; arguments?: unknown } }> },- async mount(computerUse = false, localComputer = false, toolScope?: ToolScope) {- const session = await mountChatTools(localComputer ? { localComputer: server } : { custom: { audit: server } }, controller.signal, computerUse, toolScope);+ async mount(computerUse = false, localComputer = false, toolScope?: ToolScope, resultFolder?: string, serverName = "audit") {+ const session = await mountChatTools(localComputer ? { localComputer: server } : { custom: { [serverName]: server } }, controller.signal, computerUse, toolScope,+ undefined, undefined, resultFolder);sessions.push(session);return session;},@@ -417,6 +418,56 @@ describe("Chat MCP session", () => {expect(result.text).not.toContain("�");});+ describe("a result over 50KB with a working folder", () => {+ const big = "line of a big kDrive file as base64 text ".repeat(5000);+ const bigFixture = () => fixture(`if (message.method === "tools/call") { reply(message,{content:[{type:"text",text:${JSON.stringify(big)}}]}); continue; }`);+ const workFolder = () => { const dir = mkdtempSync(join(tmpdir(), "omb-chat-mcp-work-")); dirs.push(dir); return dir; };++ it("is saved whole to a file there, and the model gets its start and the path", async () => {+ const f = bigFixture();+ const folder = workFolder();+ const result = await (await f.mount(false, false, undefined, folder)).execute("audit_write", { value: "test" }, f.controller.signal);+ const saved = readdirSync(join(folder, SAVED_RESULTS_FOLDER));+ expect(saved).toHaveLength(1);+ expect(saved[0]).toMatch(/^audit_write-\d+-[0-9a-f]{6}\.txt$/);+ const file = join(folder, SAVED_RESULTS_FOLDER, saved[0]);+ expect(readFileSync(file, "utf8")).toBe(big);+ expect(result.ok).toBe(true);+ expect(result.text.startsWith(big.slice(0, 1000))).toBe(true);+ expect(result.text).toContain(`The full result is saved in ${file}`);+ expect(result.text).toContain(`${Math.ceil(Buffer.byteLength(big) / 1024)}KB`);+ expect(Buffer.byteLength(result.text)).toBeLessThan(52_000);+ });++ it("stays inside the folder whatever the server is called", async () => {+ const f = bigFixture();+ const folder = workFolder();+ const session = await f.mount(false, false, undefined, folder, "../../escape");+ await session.execute(session.definitions[0].function.name, { value: "test" }, f.controller.signal);+ expect(readdirSync(folder)).toEqual([SAVED_RESULTS_FOLDER]);+ expect(readdirSync(join(folder, SAVED_RESULTS_FOLDER))[0]).toMatch(/^[a-z0-9_]+-\d+-[0-9a-f]{6}\.txt$/);+ });++ it("is cut as before when the results folder is a link elsewhere", async () => {+ const f = bigFixture();+ const folder = workFolder();+ const elsewhere = workFolder();+ symlinkSync(elsewhere, join(folder, SAVED_RESULTS_FOLDER));+ const result = await (await f.mount(false, false, undefined, folder)).execute("audit_write", { value: "test" }, f.controller.signal);+ expect(readdirSync(elsewhere)).toEqual([]);+ expect(result.text).toContain("[MCP result truncated at 50KB; request less output.]");+ });++ it("leaves a result under 50KB as it is, with no file", async () => {+ const f = fixture(`if (message.method === "tools/call") { reply(message,{content:[{type:"text",text:"small"}]}); continue; }`);+ const folder = workFolder();+ mkdirSync(join(folder, "keep"));+ const result = await (await f.mount(false, false, undefined, folder)).execute("audit_write", { value: "test" }, f.controller.signal);+ expect(result.text).toBe("small");+ expect(readdirSync(folder)).toEqual(["keep"]);+ });+ });+it.each(["initialize", "tools/list", "tools/call"])("cancels %s and awaits its owned process tree", async (method) => {const f = fixture(`if (message.method === ${JSON.stringify(method)}) {const helper = spawn(process.execPath,["-e","setInterval(()=>{},1000)"],{stdio:"ignore"});diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.tsindex 39fb03379c..80c4fc43de 100644--- a/server/drivers/chat-mcp-tools.ts+++ b/server/drivers/chat-mcp-tools.ts@@ -1,6 +1,8 @@// Per-turn MCP transport for the Chat Completions runtime: approval is the caller's, and only// registered, schema-validated calls arrive here.-import { createHash } from "node:crypto";+import { createHash, randomBytes } from "node:crypto";+import { lstat, mkdir, writeFile } from "node:fs/promises";+import { join } from "node:path";import type { ValidateFunction } from "ajv";import { stripControlPlaneEnv } from "../config.ts";import type { SendTurnInput } from "../contracts.ts";@@ -269,12 +271,37 @@ export function chatToolNotices(session: Pick<ChatToolSession, "skipped" | "trim].filter((line): line is string => line !== undefined);}-function boundedText(value: string): string {- const bytes = Buffer.from(value);- if (bytes.length <= OUTPUT_BYTES) return value;+function preview(bytes: Buffer): string {let end = OUTPUT_BYTES;while ((bytes[end] & 0xc0) === 0x80) end -= 1;- return `${bytes.subarray(0, end).toString()}\n[MCP result truncated at 50KB; request less output.]`;+ return bytes.subarray(0, end).toString();+}++function boundedText(value: string, bytes = Buffer.from(value)): string {+ if (bytes.length <= OUTPUT_BYTES) return value;+ return `${preview(bytes)}\n[MCP result truncated at 50KB; request less output.]`;+}++/** Folder, inside the bot's working folder, that keeps tool results too big to show the model whole. */+export const SAVED_RESULTS_FOLDER = "mcp-results";++/** A result over the limit is kept whole in `folder`/mcp-results and the model reads its start and the file's path.+ * Without a folder, or when the file cannot be written, it is cut as before. */+async function savedOrBounded(value: string, tool: string, folder: string | undefined): Promise<string> {+ const bytes = Buffer.from(value);+ if (bytes.length <= OUTPUT_BYTES || !folder) return boundedText(value, bytes);+ try {+ const dir = join(folder, SAVED_RESULTS_FOLDER);+ await mkdir(dir, { recursive: true, mode: 0o700 });+ // Security: never follow a link the folder's contents put here to write outside the working folder.+ if (!(await lstat(dir)).isDirectory()) throw new Error("not a folder");+ const file = join(dir, `${tool}-${Date.now()}-${randomBytes(3).toString("hex")}.txt`);+ await writeFile(file, bytes, { flag: "wx", mode: 0o600 });+ const kb = Math.ceil(bytes.length / 1024);+ return `${preview(bytes)}\n[MCP result is ${kb}KB; only the first 50KB is shown above. The full result is saved in ${file}]`;+ } catch {+ return boundedText(value, bytes);+ }}/** Smaller models fill optional fields with "" instead of omitting them; for these a blank means omitted. */@@ -325,9 +352,10 @@ export function directServers(servers: ReadonlyArray<{ name: string; tools: numbreturn direct;}-/** Under `schemaProfile` the model reads each tool's schema fitted to its provider; calls are still checked against the full one. */+/** Under `schemaProfile` the model reads each tool's schema fitted to its provider; calls are still checked against the full one.+ * A tool result over 50KB is saved whole in `resultFolder`, the bot's working folder (see savedOrBounded). */export async function mountChatTools(integrations: SendTurnInput["integrations"], signal: AbortSignal, computerUse = false, toolScope?: ToolScope, callTimeoutMs: number = DEFAULT_CALL_MS,- schemaProfile?: ToolSchemaProfile): Promise<ChatToolSession> {+ schemaProfile?: ToolSchemaProfile, resultFolder?: string): Promise<ChatToolSession> {const parsed = parseToolScope(toolScope);if (!parsed.ok) throw new Error(parsed.error);const scope = parsed.scope;@@ -561,7 +589,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]}if (result.structuredContent !== undefined) parts.push(JSON.stringify(result.structuredContent));if (unsupported) parts.unshift(`[${unsupported} unsupported MCP content item(s) omitted. The operation may have taken effect, but its full result cannot be represented; inspect its state before retrying.]`);- return { text: boundedText(parts.join("\n") || (images.length ? "Screenshot captured." : "(empty result)")), ok: result.isError !== true && unsupported === 0,+ return { text: await savedOrBounded(parts.join("\n") || (images.length ? "Screenshot captured." : "(empty result)"), chatToolName(tool.server, tool.name), resultFolder), ok: result.isError !== true && unsupported === 0,...(images.length ? { images } : {}) };} catch (error) {await close();diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex fec49d69df..da77f4316f 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -611,7 +611,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)if (!parsed.ok) throw new Error(parsed.error);const scope = parsed.scope;tools = await mountChatTools(options.tools === false ? undefined : turn.integrations, abort.signal, options.computerUse, scope, turn.mcpCallTimeoutMs,- toolSchemaProfileFor({ url: options.apiUrl, model }));+ toolSchemaProfileFor({ url: options.apiUrl, model }), turn.cwd ?? turn.toolResultFolder);noteToolBudget(turn.botId, tools.budget);for (const message of chatToolNotices(tools)) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });const questionAllowed = options.tools !== false && allowsTool(scope, { kind: "native", name: ASK_USER_TOOL });diff --git a/server/index.ts b/server/index.tsindex 8d66da0e6f..6ebf4f7a07 100644--- a/server/index.ts+++ b/server/index.ts@@ -8569,6 +8569,7 @@ async function beginTurn(...(integrations.browser && browserIsThePlace(turnSurfacePlan(bot, undefined, threadId, true)) ? { preloadBrowserTools: true } : {}),...settingsTurnFields(cfg, DATA_DIR, managedPolicy.restrictsMcp()),cwd,+ ...(worksInWorkspace || guestConfined ? {} : { toolResultFolder: (cloudGuestOpened(threadId) ? undefined : liveBot?.cwd ?? bot.cwd) ?? join(TASK_WORKSPACES_DIR, bot.id, threadId) }),botSettingsFile: botSettingsFile(bot),}, (input) => quickFallback.sendTurn(instance, input, route.quickModel ? { model, own: bot.modelSelection, onFallback: () => store.patchMessage(threadId, userMessage.id, { quickModel: undefined }) } : undefined))), () => companyShutdown || !directTurnClaimExists(bot.id, dispatchClaimId, threadId), async () => {await (runningTurnEngines.get(threadId) ?? instance).adapter.interruptTurn(threadId).catch(() => {});