Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix: mask, cap and deliver saved MCP results (review)
AdityaUmale0f4046b05538
diff --git a/server/contracts.ts b/server/contracts.tsindex cd23b9dfa0..127cc71b5a 100644--- a/server/contracts.ts+++ b/server/contracts.ts@@ -197,7 +197,7 @@ 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. */+ /** Engines with no working folder (the chat drivers): where an MCP result too big for the model is saved whole; a folder attach_file can deliver from. */toolResultFolder?: string;/** Also load the person's own CLI MCP setup (Claude Code user scope, claude.ai connectors). */mcpFromUserConfig?: boolean;diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.tsindex 02a2dcca14..a4da6c5535 100644--- a/server/drivers/chat-mcp-tools.test.ts+++ b/server/drivers/chat-mcp-tools.test.ts@@ -4,7 +4,7 @@ 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, SAVED_RESULTS_FOLDER, chatToolNotices, directServers, mountChatTools, trimmedToolsNotice, type ChatToolSession } from "./chat-mcp-tools.ts";+import { ChatToolSessionError, SAVED_RESULTS_FOLDER, SAVED_RESULTS_KEPT, 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";@@ -458,6 +458,33 @@ describe("Chat MCP session", () => {expect(result.text).toContain("[MCP result truncated at 50KB; request less output.]");});+ it("masks key-shaped values before the file is written", async () => {+ const key = `sk-ant-${"k".repeat(40)}`;+ const f = fixture(`if (message.method === "tools/call") { reply(message,{content:[{type:"text",text:${JSON.stringify(`${big}token ${key} end`)}}]}); continue; }`);+ const folder = workFolder();+ await (await f.mount(false, false, undefined, folder)).execute("audit_write", { value: "test" }, f.controller.signal);+ const [saved] = readdirSync(join(folder, SAVED_RESULTS_FOLDER));+ const text = readFileSync(join(folder, SAVED_RESULTS_FOLDER, saved), "utf8");+ expect(text.startsWith(big)).toBe(true);+ expect(text).not.toContain(key);+ });++ it(`keeps only the newest ${SAVED_RESULTS_KEPT} saved results`, async () => {+ const f = bigFixture();+ const folder = workFolder();+ const results = join(folder, SAVED_RESULTS_FOLDER);+ mkdirSync(results);+ const old = Array.from({ length: SAVED_RESULTS_KEPT }, (_, i) => `audit_write-${1_700_000_000_000 + i}-abcdef.txt`);+ for (const name of old) writeFileSync(join(results, name), "old");+ writeFileSync(join(results, "notes.md"), "not a saved result");+ await (await f.mount(false, false, undefined, folder)).execute("audit_write", { value: "test" }, f.controller.signal);+ const left = readdirSync(results);+ expect(left).toHaveLength(SAVED_RESULTS_KEPT + 1);+ expect(left).toContain("notes.md");+ expect(left).not.toContain(old[0]);+ expect(left).toContain(old[1]);+ });+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();diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.tsindex 80c4fc43de..0cedc8bf21 100644--- a/server/drivers/chat-mcp-tools.ts+++ b/server/drivers/chat-mcp-tools.ts@@ -1,11 +1,12 @@// Per-turn MCP transport for the Chat Completions runtime: approval is the caller's, and only// registered, schema-validated calls arrive here.import { createHash, randomBytes } from "node:crypto";-import { lstat, mkdir, writeFile } from "node:fs/promises";+import { lstat, mkdir, readdir, unlink, 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";+import { redactSecretsInText } from "../redact.ts";import { augmentedPath } from "../env-path.ts";import { killCliTree, spawnCli } from "../procs.ts";import { AGENTS_TOOL_ALIASES } from "../../shared/agents-tool-names.ts";@@ -284,8 +285,19 @@ function boundedText(value: string, bytes = Buffer.from(value)): string {/** 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";+/** Only the newest saved results are kept, so repeated big results cannot fill the disk. */+export const SAVED_RESULTS_KEPT = 20;+const SAVED_RESULT_NAME = /-(\d+)-[0-9a-f]{6}\.txt$/;-/** A result over the limit is kept whole in `folder`/mcp-results and the model reads its start and the file's path.+async function pruneSavedResults(dir: string): Promise<void> {+ const saved = (await readdir(dir)).flatMap((name) => {+ const match = SAVED_RESULT_NAME.exec(name);+ return match ? [{ name, at: Number(match[1]) }] : [];+ }).sort((a, b) => b.at - a.at);+ await Promise.all(saved.slice(SAVED_RESULTS_KEPT).map(({ name }) => unlink(join(dir, name))));+}++/** A result over the limit is kept whole (secrets masked) 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);@@ -296,7 +308,9 @@ async function savedOrBounded(value: string, tool: string, folder: string | unde// 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 });+ // Key-shaped values are masked before the result reaches disk, as for every other kept tool result.+ await writeFile(file, redactSecretsInText(value), { flag: "wx", mode: 0o600 });+ await pruneSavedResults(dir).catch(() => {});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 {diff --git a/server/index.ts b/server/index.tsindex 6ebf4f7a07..1e05334877 100644--- a/server/index.ts+++ b/server/index.ts@@ -8569,7 +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) }),+ ...(worksInWorkspace || guestConfined || cloudGuestOpened(threadId) ? {} : { toolResultFolder: messageFileRootsForThread(bot.id, threadId)[0] }),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(() => {});